From simplebob at gmail.com  Mon Jan  1 00:43:30 2007
From: simplebob at gmail.com (Daniel McQuay)
Date: Sun, 31 Dec 2006 18:43:30 -0500
Subject: [Tutor] Starting python from a DOS prompt from any directory?
In-Reply-To: <en9d8p$un$1@sea.gmane.org>
References: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com>
	<en7t1t$ojm$1@sea.gmane.org>
	<F26FB35DD3F82E4FA091D483D36C610C02817887@MAILBE05.MAIL.LA.GOV>
	<en9d8p$un$1@sea.gmane.org>
Message-ID: <6d87ecf40612311543l157b18e6x963d97df99a55295@mail.gmail.com>

yeah, you know what i totally didn't think about setting the environmental
values (yeah Media Center is the same as XP Pro). i guess i should of known
that. geeze now i feel like a moron. however, i didn't know about that quick
little DOS trick.

thanks a lot guys for such a quick response and pointing out the obvious.

this has got to be the best and most friendly list ever.

happy new year to you all,

On 12/31/06, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Steve Oldner" <Steven.Oldner at LA.GOV> wrote
>
> > change defaults (programmers aren't allowed to do system
> > admin stuff, heck, we can't even move our PC's or monitors).
>
> You can just type in the PATH statement every time you
> start DOS
>
> PATH= %PATH%;D:\Python25
>
> And it will have the same effect.
>
> You can even create a Batch file and put it into
> somewhere your PATH can see
>
>
> D:\Python25\python %1 %2 %3 %4 %5 %6 %7 %8 %9
>
> should work.
>
> But how did you install Python if you can't change the
> system? If you have access to install programs you
> have access to set environment variables, at least
> for yourself!
>
> Alan G.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Daniel McQuay
boxster.homelinux.org
H: 814.825.0847
M: 814-341-9013
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20061231/54b85dc5/attachment.html 

From vladoportos at vladoportos.sk  Mon Jan  1 01:48:33 2007
From: vladoportos at vladoportos.sk (Vladimir Strycek)
Date: Mon, 01 Jan 2007 01:48:33 +0100
Subject: [Tutor] SPE - Stani's Python Editor ?
Message-ID: <45985A61.3000101@vladoportos.sk>

Hi all,
some time ago i instaled SPE with python 2.4... it works very good... 
but yesterday my pc crash completly ( some dll went missing somehow :-) 
)... so  after format and  reinstalling of windows i begin to install 
all my programs back...

When i come to python i download new 2.5 version and only version for 
win i could find is SPE-0.8.2.a-wx2.6.1.0-py24 which doesnt work... :-( 
newer version ist just rpm and i need exe for win... any idea if there 
will be exe or any more development in SPE cause homepage is not running 
etc...

Or can you suggest similar IDE for python... ?

Thanks
Best regards
Vladimir

From pyro9219 at gmail.com  Mon Jan  1 04:33:49 2007
From: pyro9219 at gmail.com (Chris Hengge)
Date: Sun, 31 Dec 2006 19:33:49 -0800
Subject: [Tutor] XML-RPC data transfers.
In-Reply-To: <en7u2g$q7c$1@sea.gmane.org>
References: <BAY12-F204AF27D9D281699F3E163B1C60@phx.gbl>
	<c25107380612292114o786c24ft41bea4931562cce6@mail.gmail.com>
	<45967D0C.9040205@tds.net>
	<c25107380612301504m372283cei227a339b2d1303b8@mail.gmail.com>
	<4596FF8F.8080401@gmail.com>
	<c25107380612301721i5c65f39fpe234c43d688f9188@mail.gmail.com>
	<en7u2g$q7c$1@sea.gmane.org>
Message-ID: <c25107380612311933v42c2d4as432eedccc11ba5fd@mail.gmail.com>

Boo bloatware! Don't even mention those... heheh.. I even turn off most the
services on my system to keep things clean.. But thats another story..

Going off your thoughts that I'm asking to do something outside the realm of
the readers here, is there a better place to ask this kind of oddball stuff?
I've looked around and haven't been able to find any support for XML-RPC
(might be a good sign to drop it and move to something else?) I'm on the
win32 list, and python-list, but I mostly just read those since in my mind
most of what I have questions about are noobish things since I'm still
trying to get a handle on this language...

On 12/31/06, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Chris Hengge" <pyro9219 at gmail.com> wrote
>
> > method is a good one. Much like your own answers to most of my
> > questions,
> > you state several ways varying from "probably works" to "how I'd try
> > to do
> > it". Personally, I'd rather understand more of the "how I know it
> > works"
>
> One reason may be that you are doing something unusual.
> Like sending images directly from memory over an XMLRPC
> connection. It should be possible but its not likely something
> many perople on this list will have actually done. So you only
> get suggestions of how they *might* do it ifd they had to.
>
> Because of the reliability issues with XMLRPC I'd always save
> image data to a file and send the file. (As I said earlier I'd try
> to avoid sending the file via RPC but thats another story
> that we've covered') But the advantages of having a file mean
> that the whole process is much more repeatable and resilient
> particularly if the object you are trying to send is subject to
> change - like a screen shot. If you have to resend because
> of RPC errors then the new screen grab might be different
> to the original. The alternative involves holding the screen
> image in RAM for a longish time which makes your program
> into a resource hog which is also bad practice... although
> with PCs having hundreds of Meg of RAM nowadays its
> sadly becoming more common! Bloatware rules :-(
>
> But I suspect the main reason you aren't getting working examples
> is simply that you are trying to do something that is outside
> normal programming experience on this list.
>
> But I may be wrong! ;-)
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20061231/b30e9218/attachment.htm 

From rdm at rcblue.com  Mon Jan  1 06:47:17 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 31 Dec 2006 21:47:17 -0800
Subject: [Tutor] SPE - Stani's Python Editor ?
In-Reply-To: <45985A61.3000101@vladoportos.sk>
References: <45985A61.3000101@vladoportos.sk>
Message-ID: <7.0.1.0.2.20061231213332.06853e20@rcblue.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20061231/b23b96d8/attachment.html 

From alan.gauld at btinternet.com  Mon Jan  1 10:31:04 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 1 Jan 2007 09:31:04 -0000
Subject: [Tutor] XML-RPC data transfers.
References: <BAY12-F204AF27D9D281699F3E163B1C60@phx.gbl><c25107380612292114o786c24ft41bea4931562cce6@mail.gmail.com><45967D0C.9040205@tds.net><c25107380612301504m372283cei227a339b2d1303b8@mail.gmail.com><4596FF8F.8080401@gmail.com><c25107380612301721i5c65f39fpe234c43d688f9188@mail.gmail.com><en7u2g$q7c$1@sea.gmane.org>
	<c25107380612311933v42c2d4as432eedccc11ba5fd@mail.gmail.com>
Message-ID: <enak95$5rm$1@sea.gmane.org>

"Chris Hengge" <pyro9219 at gmail.com> wrote

> Going off your thoughts that I'm asking to do something outside the 
> realm of
> the readers here, is there a better place to ask this kind of 
> oddball stuff?
> I've looked around and haven't been able to find any support for 
> XML-RPC

I'd try the XML SIG and since you are also dealing with
images here the PIL Image SIG

However, the answers you've gotten here are probably
sufficient. Its just that its not something people have
already done for themselves.

One of the fun things about programming is that you
constantly come across problems, even as a relative
beginner, that nobody has done before. People will
help out by suggesting things but ultimately you will
have to break the new ground yourself. It can be frustrating
but when it works a satisfying result!

Have fun,

Alan G.
(Whose garden fence and greenhouse has just been
destroyed by an overnight gale! - no programming for me today...)



From mail at timgolden.me.uk  Mon Jan  1 12:00:40 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 01 Jan 2007 11:00:40 +0000
Subject: [Tutor] XML-RPC data transfers.
In-Reply-To: <c25107380612311933v42c2d4as432eedccc11ba5fd@mail.gmail.com>
References: <BAY12-F204AF27D9D281699F3E163B1C60@phx.gbl>	<c25107380612292114o786c24ft41bea4931562cce6@mail.gmail.com>	<45967D0C.9040205@tds.net>	<c25107380612301504m372283cei227a339b2d1303b8@mail.gmail.com>	<4596FF8F.8080401@gmail.com>	<c25107380612301721i5c65f39fpe234c43d688f9188@mail.gmail.com>	<en7u2g$q7c$1@sea.gmane.org>
	<c25107380612311933v42c2d4as432eedccc11ba5fd@mail.gmail.com>
Message-ID: <4598E9D8.90902@timgolden.me.uk>

Chris Hengge wrote:
> Going off your thoughts that I'm asking to do something outside the 
> realm of the readers here, is there a better place to ask this kind of 
> oddball stuff? I've looked around and haven't been able to find any 
> support for XML-RPC (might be a good sign to drop it and move to 
> something else?) I'm on the win32 list, and python-list, but I mostly 
> just read those since in my mind most of what I have questions about are 
> noobish things since I'm still trying to get a handle on this language...

There's obviously nothing hard-and-fast about what fits
on this list and what on the main Python or python-win32
lists. There's not even that clear a distinction between
the latter two, and I suspect there's a good overlap of
experts reading two or more lists.

If I were to suggest something as a *very* broad guideline
it would be this: if you're unfamiliar with Python qua *language*,
the tutor list is perhaps the better list to ask; if you're
having problems with a particular library, whether one that
comes with Python or a third-party one, the main list might
get you more answers. Obviously there's a sort of middle
ground where the problems you're having with a library stem
from an unfamiliarity with language concepts...

I'm sure many people like myself keep track of several lists
as far as time and interest allows, so for a given problem
you might find the same level of expertise available to you.
If you were to ask, for example, about using WMI under
Win32 in Python your best bet would be the python-win32
list. But as it happens, that's my area of modest expertise
so as long as I'm watching this list you'd have a reasonable
chance of an answer. But that's only because it does happen
to be my area.

If you haven't already, I'd be inclined to put your
XMLRPC-Image question on the main python list. Why
not? If no-one can help, you're no worse off than
you were!

TJG

From rdm at rcblue.com  Mon Jan  1 12:59:55 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 01 Jan 2007 03:59:55 -0800
Subject: [Tutor] Need help with rewriting script to use Decimal module
Message-ID: <7.0.1.0.2.20070101034429.0353de58@rcblue.com>

bestFracForMinimumError() is only a small part of a program I wrote 
long ago, called frac.py 
(<http://www.rcblue.com/Python/fracForWeb.py>). I'm trying to rewrite 
it so as to get more precision by using the Decimal module, but am 
getting nowhere. Errors all over the place. Can some kind and 
knowledgeable soul show me how?

========================================================
import decimal
def d(x):
     return decimal.Decimal(str(x))
decimal.getcontext().prec = 40


def bestFracForMinimumError(decimal, minimumError):
     denom = 0
     while True:
         denom += 1
         num = round(decimal * denom)
         error = abs((num / denom - decimal) / decimal) * 100
         if error <= minimumError:
             break
     return int(num), denom, error

dec = .345765988765560057657654654

me = .0000000001

print bestFracForMinimumError(dec, me)

num, denom, error = bestFracForMinimumError(dec, me)

print "%f = %d/%d with %f per cent error" % (dec, num, denom, error)
=====================================================

Thanks,

Dick Moores


From ziad.rahhal at gmail.com  Mon Jan  1 13:51:29 2007
From: ziad.rahhal at gmail.com (Ziad Rahhal)
Date: Mon, 1 Jan 2007 13:51:29 +0100
Subject: [Tutor] XML-RPC data transfers.
In-Reply-To: <4598E9D8.90902@timgolden.me.uk>
References: <BAY12-F204AF27D9D281699F3E163B1C60@phx.gbl>
	<c25107380612292114o786c24ft41bea4931562cce6@mail.gmail.com>
	<45967D0C.9040205@tds.net>
	<c25107380612301504m372283cei227a339b2d1303b8@mail.gmail.com>
	<4596FF8F.8080401@gmail.com>
	<c25107380612301721i5c65f39fpe234c43d688f9188@mail.gmail.com>
	<en7u2g$q7c$1@sea.gmane.org>
	<c25107380612311933v42c2d4as432eedccc11ba5fd@mail.gmail.com>
	<4598E9D8.90902@timgolden.me.uk>
Message-ID: <d1c58c270701010451w57139c92t148f571f7b389e54@mail.gmail.com>

Did you look at SOAPpy?
if you are interested in doing what you want to do through web-services,
then SOAPpy might be what you are looking for. It does support XML-RPC.
I have developed a working example that sends an image from a
Java Web-service and receives the image at a SOAPpy client that uses XML-RPC
connection style. The image is re-constructed using PIL.

let me know.
Ziad


On 1/1/07, Tim Golden <mail at timgolden.me.uk> wrote:
>
> Chris Hengge wrote:
> > Going off your thoughts that I'm asking to do something outside the
> > realm of the readers here, is there a better place to ask this kind of
> > oddball stuff? I've looked around and haven't been able to find any
> > support for XML-RPC (might be a good sign to drop it and move to
> > something else?) I'm on the win32 list, and python-list, but I mostly
> > just read those since in my mind most of what I have questions about are
> > noobish things since I'm still trying to get a handle on this
> language...
>
> There's obviously nothing hard-and-fast about what fits
> on this list and what on the main Python or python-win32
> lists. There's not even that clear a distinction between
> the latter two, and I suspect there's a good overlap of
> experts reading two or more lists.
>
> If I were to suggest something as a *very* broad guideline
> it would be this: if you're unfamiliar with Python qua *language*,
> the tutor list is perhaps the better list to ask; if you're
> having problems with a particular library, whether one that
> comes with Python or a third-party one, the main list might
> get you more answers. Obviously there's a sort of middle
> ground where the problems you're having with a library stem
> from an unfamiliarity with language concepts...
>
> I'm sure many people like myself keep track of several lists
> as far as time and interest allows, so for a given problem
> you might find the same level of expertise available to you.
> If you were to ask, for example, about using WMI under
> Win32 in Python your best bet would be the python-win32
> list. But as it happens, that's my area of modest expertise
> so as long as I'm watching this list you'd have a reasonable
> chance of an answer. But that's only because it does happen
> to be my area.
>
> If you haven't already, I'd be inclined to put your
> XMLRPC-Image question on the main python list. Why
> not? If no-one can help, you're no worse off than
> you were!
>
> TJG
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070101/fb9b016c/attachment.html 

From kent37 at tds.net  Mon Jan  1 14:37:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 01 Jan 2007 08:37:06 -0500
Subject: [Tutor] Need help with rewriting script to use Decimal module
In-Reply-To: <7.0.1.0.2.20070101034429.0353de58@rcblue.com>
References: <7.0.1.0.2.20070101034429.0353de58@rcblue.com>
Message-ID: <45990E82.8020501@tds.net>

Dick Moores wrote:
> bestFracForMinimumError() is only a small part of a program I wrote 
> long ago, called frac.py 
> (<http://www.rcblue.com/Python/fracForWeb.py>). I'm trying to rewrite 
> it so as to get more precision by using the Decimal module, but am 
> getting nowhere. Errors all over the place. Can some kind and 
> knowledgeable soul show me how?

I don't see where you are actually using the decimal module here, am I 
missing something?

It doesn't help that you cal the argument to your function 'decimal'.

> dec = .345765988765560057657654654

Your Python interpreter probably doesn't have enough precision to 
represent this number directly. Here is what I get:

In [1]: dec = .345765988765560057657654654

In [2]: dec
Out[2]: 0.34576598876556008

Kent



From rdm at rcblue.com  Mon Jan  1 14:44:38 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 01 Jan 2007 05:44:38 -0800
Subject: [Tutor] Need help with rewriting script to use Decimal  module
In-Reply-To: <45990E82.8020501@tds.net>
References: <7.0.1.0.2.20070101034429.0353de58@rcblue.com>
	<45990E82.8020501@tds.net>
Message-ID: <7.0.1.0.2.20070101054029.01f63510@rcblue.com>

At 05:37 AM 1/1/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>bestFracForMinimumError() is only a small part of a program I wrote 
>>long ago, called frac.py 
>>(<http://www.rcblue.com/Python/fracForWeb.py>). I'm trying to 
>>rewrite it so as to get more precision by using the Decimal module, 
>>but am getting nowhere. Errors all over the place. Can some kind 
>>and knowledgeable soul show me how?
>
>I don't see where you are actually using the decimal module here, am 
>I missing something?

You're missing the explanation that I didn't write. ;-)

I pasted what I had before even starting to use Decimal, but left in 
d(), thinking that my helper could use it..

Dick


>It doesn't help that you cal the argument to your function 'decimal'.
>
>>dec = .345765988765560057657654654
>
>Your Python interpreter probably doesn't have enough precision to 
>represent this number directly. Here is what I get:
>
>In [1]: dec = .345765988765560057657654654
>
>In [2]: dec
>Out[2]: 0.34576598876556008
>
>Kent
>
>



From Steven.Oldner at LA.GOV  Mon Jan  1 18:03:41 2007
From: Steven.Oldner at LA.GOV (Steve Oldner)
Date: Mon, 1 Jan 2007 11:03:41 -0600
Subject: [Tutor] Starting python from a DOS prompt from any directory?
References: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com><en7t1t$ojm$1@sea.gmane.org><F26FB35DD3F82E4FA091D483D36C610C02817887@MAILBE05.MAIL.LA.GOV><en9d8p$un$1@sea.gmane.org>
	<6d87ecf40612311543l157b18e6x963d97df99a55295@mail.gmail.com>
Message-ID: <F26FB35DD3F82E4FA091D483D36C610C02817888@MAILBE05.MAIL.LA.GOV>

Dittos, guys.
 
Alan, I work for a state government, so I'm not suppose to download PYTHON without submitting reasons and getting permissions.   I'm an applications programmer working on SAP (ASAP programmer), and we have some COBOL and Cold Fusion also.  So we are pretty compartmentalized.
 
Anyway thanks for the tip and I'll use it next time.
 
Thanks,
 
Steve   

________________________________

From: tutor-bounces at python.org on behalf of Daniel McQuay
Sent: Sun 12/31/2006 5:43 PM
To: Alan Gauld
Cc: tutor at python.org
Subject: Re: [Tutor] Starting python from a DOS prompt from any directory?


yeah, you know what i totally didn't think about setting the environmental values (yeah Media Center is the same as XP Pro). i guess i should of known that. geeze now i feel like a moron. however, i didn't know about that quick little DOS trick. 

thanks a lot guys for such a quick response and pointing out the obvious.

this has got to be the best and most friendly list ever.

happy new year to you all,


On 12/31/06, Alan Gauld <alan.gauld at btinternet.com> wrote: 

	"Steve Oldner" <Steven.Oldner at LA.GOV> wrote
	
	> change defaults (programmers aren't allowed to do system
	> admin stuff, heck, we can't even move our PC's or monitors). 
	
	You can just type in the PATH statement every time you
	start DOS
	
	PATH= %PATH%;D:\Python25
	
	And it will have the same effect.
	
	You can even create a Batch file and put it into
	somewhere your PATH can see 
	
	
	D:\Python25\python %1 %2 %3 %4 %5 %6 %7 %8 %9
	
	should work.
	
	But how did you install Python if you can't change the
	system? If you have access to install programs you
	have access to set environment variables, at least 
	for yourself!
	
	Alan G.
	
	
	_______________________________________________
	Tutor maillist  -  Tutor at python.org
	http://mail.python.org/mailman/listinfo/tutor
	




-- 
Daniel McQuay
boxster.homelinux.org <http://boxster.homelinux.org/> 
H: 814.825.0847
M: 814-341-9013 

From chiselchip at earthlink.net  Mon Jan  1 18:04:27 2007
From: chiselchip at earthlink.net (LandSurveyor)
Date: Mon, 1 Jan 2007 12:04:27 -0500 (GMT-05:00)
Subject: [Tutor] display text in colors
Message-ID: <9213435.1167671067856.JavaMail.root@elwamui-mouette.atl.sa.earthlink.net>

I would like to direct a python script to display 'print' strings in various (chosen) colors; for example:

print \
"""
color this line blue   # in the printout display-be it screen or hardcopy
color this line green  # in the printout display-be it screen or hardcopy
"""
what I tried doing was:
import os
then the line...<os.system('\[\e[31;1m\]')> just before the print command (I borrowed this formatting from my $PS1 format.

Nadda.  Didn't work.  What might I try?

From cappy2112 at gmail.com  Mon Jan  1 18:09:56 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Mon, 1 Jan 2007 09:09:56 -0800
Subject: [Tutor] Starting python from a DOS prompt from any
Message-ID: <8249c4ac0701010909s13544each417e4d35744eb034@mail.gmail.com>

Message: 3
Date: Sun, 31 Dec 2006 00:10:39 -0500
From: "Daniel McQuay" <simplebob at gmail.com>
Subject: [Tutor]  Starting python from a DOS prompt from any
       directory?
>>sorry for such a newbie question but i would like to figure this out
because
>>there are some situations where i need that to work from any directory.



Alan Gauld wrote
>>You need to set up your PATH environment variable to include the
>>python directory. You do this on XP(not so sure about Media Centre!)
>>via the MyComputer->Properties->Advanced->Environment Variables route
>>Once there you need to find the PATH variable and edit it to add the

I recommend adding it to the System Path environment variable, instead of
the Path Environment variable for your current  user login.
You'll have to reboot before it takes affect though.

There's also a simple registry change you can make to open the Python
interpreter in a specific directory, by right clicking on that directory
with Windows Explorer, without having to type 'cd' down a complicated path.
This saves time if you have long directory names.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070101/b6e61e3b/attachment.htm 

From pyro9219 at gmail.com  Mon Jan  1 19:13:06 2007
From: pyro9219 at gmail.com (Chris Hengge)
Date: Mon, 1 Jan 2007 10:13:06 -0800
Subject: [Tutor] XML-RPC data transfers.
In-Reply-To: <4598E9D8.90902@timgolden.me.uk>
References: <BAY12-F204AF27D9D281699F3E163B1C60@phx.gbl>
	<c25107380612292114o786c24ft41bea4931562cce6@mail.gmail.com>
	<45967D0C.9040205@tds.net>
	<c25107380612301504m372283cei227a339b2d1303b8@mail.gmail.com>
	<4596FF8F.8080401@gmail.com>
	<c25107380612301721i5c65f39fpe234c43d688f9188@mail.gmail.com>
	<en7u2g$q7c$1@sea.gmane.org>
	<c25107380612311933v42c2d4as432eedccc11ba5fd@mail.gmail.com>
	<4598E9D8.90902@timgolden.me.uk>
Message-ID: <c25107380701011013ife0966fv7298af8fdd285e23@mail.gmail.com>

The main reason I haven't posted to more then one list is because I'm trying
to avoid looking obnoxious, as well as getting redundant information, or
having to keep answering the same things mutliple times... I might ask this
over there though after I try a few more things. Thanks.

On 1/1/07, Tim Golden <mail at timgolden.me.uk> wrote:
>
> Chris Hengge wrote:
> > Going off your thoughts that I'm asking to do something outside the
> > realm of the readers here, is there a better place to ask this kind of
> > oddball stuff? I've looked around and haven't been able to find any
> > support for XML-RPC (might be a good sign to drop it and move to
> > something else?) I'm on the win32 list, and python-list, but I mostly
> > just read those since in my mind most of what I have questions about are
> > noobish things since I'm still trying to get a handle on this
> language...
>
> There's obviously nothing hard-and-fast about what fits
> on this list and what on the main Python or python-win32
> lists. There's not even that clear a distinction between
> the latter two, and I suspect there's a good overlap of
> experts reading two or more lists.
>
> If I were to suggest something as a *very* broad guideline
> it would be this: if you're unfamiliar with Python qua *language*,
> the tutor list is perhaps the better list to ask; if you're
> having problems with a particular library, whether one that
> comes with Python or a third-party one, the main list might
> get you more answers. Obviously there's a sort of middle
> ground where the problems you're having with a library stem
> from an unfamiliarity with language concepts...
>
> I'm sure many people like myself keep track of several lists
> as far as time and interest allows, so for a given problem
> you might find the same level of expertise available to you.
> If you were to ask, for example, about using WMI under
> Win32 in Python your best bet would be the python-win32
> list. But as it happens, that's my area of modest expertise
> so as long as I'm watching this list you'd have a reasonable
> chance of an answer. But that's only because it does happen
> to be my area.
>
> If you haven't already, I'd be inclined to put your
> XMLRPC-Image question on the main python list. Why
> not? If no-one can help, you're no worse off than
> you were!
>
> TJG
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070101/9e4a9bd9/attachment.html 

From alan.gauld at btinternet.com  Mon Jan  1 20:02:29 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 1 Jan 2007 19:02:29 -0000
Subject: [Tutor] Starting python from a DOS prompt from any directory?
References: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com><en7t1t$ojm$1@sea.gmane.org><F26FB35DD3F82E4FA091D483D36C610C02817887@MAILBE05.MAIL.LA.GOV><en9d8p$un$1@sea.gmane.org><6d87ecf40612311543l157b18e6x963d97df99a55295@mail.gmail.com>
	<F26FB35DD3F82E4FA091D483D36C610C02817888@MAILBE05.MAIL.LA.GOV>
Message-ID: <enbloj$m59$1@sea.gmane.org>


"Steve Oldner" <Steven.Oldner at LA.GOV> wrote
> Alan, I work for a state government, so I'm not suppose to 
> download PYTHON without submitting reasons and 
> getting permissions.   

Sure I understand that, but it looks from your post that 
you have somehow managed to install Python. If your 
account has permissions to install any software then 
you probably have permissions to set at least USER 
level Environmenent Variables (You may not be able to 
set them at SYSTEM level)

> I'm an applications programmer working on SAP 

I know the kind of set up, we have similar teams of 
folks working on Siebel and Oracle.

Alan G.


From alan.gauld at btinternet.com  Mon Jan  1 20:04:26 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 1 Jan 2007 19:04:26 -0000
Subject: [Tutor] Starting python from a DOS prompt from any
References: <8249c4ac0701010909s13544each417e4d35744eb034@mail.gmail.com>
Message-ID: <enbls8$mm7$1@sea.gmane.org>


"Tony Cappellini" <cappy2112 at gmail.com> wrote

> There's also a simple registry change you can make to open the 
> Python
> interpreter in a specific directory,

You can just set up a shortcut with the working directory set.
No need to worry about the registry (although of course the
shortcut does that for you!)

Alan G. 



From anilmrn at yahoo.com  Mon Jan  1 20:33:49 2007
From: anilmrn at yahoo.com (anil maran)
Date: Mon, 1 Jan 2007 11:33:49 -0800 (PST)
Subject: [Tutor] Session from different app or domain
Message-ID: <20070101193349.42145.qmail@web55213.mail.re4.yahoo.com>

One app i m developing needs integrating with the
client site and get
their users, so I need to use their login to log the
users in and once
they are in they should use my application sort of
like Microsoft
Passport...

Here is the problem the example usage is in Django

and they are talking about a request object
    if 'session_key' in request.session and 'uid' in
request.session:
        fb.session_key =
request.session['session_key']

Anyone can tell me how I can access this in webpy
Isnt flup something that is set from webpy, how do we
use sessions that
are set by a different Application

This question has a wide range of implications for
eg., this can be
used to apply to newly opened yahoo mail api etc., So
please share your
insights. I m sharing the example code below..

Thanks



# -----------------------
# Web application example
# -----------------------

def simple_web_app(request, api_key, secret_key):
    fb = WebAppWidget(api_key, secret_key,
request.GET['auth_token'])
    fb.auth_getSession()

    friend_ids = fb.friends_get()
    info = fb.users_getInfo(friend_ids, ['name',
'pic'])

    print '<html><body>'
    for friend in info:
        print '<a href="%(pic)s">%(name)s</a>' %
friend
    print '</body></html>'

def web_app(request):
    """Get the user's friends and their pictures. This
example uses
       the Django web framework, but should be
adaptable to others."""

    # Get api_key and secret_key from a file
    fb_file = open('facebook_keys.txt').readlines()
    api_key = fb_file[0].strip()
    secret_key = fb_file[1].strip()
    fb = WebAppWidget(api_key, secret_key)

    # Use the data from the cookie if present
    if 'session_key' in request.session and 'uid' in
request.session:
        fb.session_key =
request.session['session_key']
        fb.uid = request.session['uid']
    else:

        try:
            fb.auth_token = request.GET['auth_token']
        except KeyError:
            # Send user to the WebAppWidget to login
            return
HttpResponseRedirect(fb.get_login_url())

        # getSession sets the session_key and uid
        # Store these in the cookie so we don't have
to get them again
        fb.auth_getSession()
        request.session['session_key'] =
fb.session_key
        request.session['uid'] = fb.uid

    try:
        friend_ids = fb.friends_get()
    except WebAppWidgetError, e:
        # Error 102 means the session has expired.
        # Delete the cookie and send the user to
WebAppWidget to login
        if e.info['code'] == u'102':
            del request.session['session_key']
            del request.session['uid']
            return
HttpResponseRedirect(fb.get_login_url())
        else:
            # Other WebAppWidget errors are possible
too. Don't ignore
them.
            raise

    info = fb.users_getInfo(friend_ids, ['name',
'pic'])
    # info is a list of dictionaries

    # you would never do this in an actual Django
application,
    # it's just an example of accessing the results.
    links = []
    for friend in info:
        html = '<a href="%(pic)s">%(name)s</a>' %
friend
        links.append(html)

    return render_to_response('template.html',
{'links': links}) 


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From rabidpoobear at gmail.com  Mon Jan  1 20:55:58 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 01 Jan 2007 13:55:58 -0600
Subject: [Tutor] display text in colors
In-Reply-To: <9213435.1167671067856.JavaMail.root@elwamui-mouette.atl.sa.earthlink.net>
References: <9213435.1167671067856.JavaMail.root@elwamui-mouette.atl.sa.earthlink.net>
Message-ID: <4599674E.3070008@gmail.com>

LandSurveyor wrote:
> I would like to direct a python script to display 'print' strings in various (chosen) colors; for example:
>
> print \
> """
> color this line blue   # in the printout display-be it screen or hardcopy
> color this line green  # in the printout display-be it screen or hardcopy
> """
> what I tried doing was:
> import os
> then the line...<os.system('\[\e[31;1m\]')> just before the print command (I borrowed this formatting from my $PS1 format.
>
> Nadda.  Didn't work.  What might I try?
>   
Uh, I think it's pretty important what operating system you're using here.
Could you let us know before we try to help further?
Thanks,
-Luke


From chiselchip at earthlink.net  Mon Jan  1 22:16:34 2007
From: chiselchip at earthlink.net (LandSurveyor)
Date: Mon, 1 Jan 2007 16:16:34 -0500 (GMT-05:00)
Subject: [Tutor] display text in colors
Message-ID: <14959517.1167686194996.JavaMail.root@elwamui-wigeon.atl.sa.earthlink.net>

Oh!...sorry.  My OS is Mandrake 10.1.
Coupla other little 'minor' details I sorta left out.  I had attempted to echo a random string on my command line by surrounding it with [again] the same color-code that works on my CLI prompt line ($PS1).  That was the color coding I had tried to inject into a likely(?) spot in my code script.  i.e., I have sort of approached this is a shell (rather than Python) issue, by trying to invoke an OS command (from inside my script) that-maybe-otherwise works.
BTW, I couldn't get anything to work on the command line either:

... at myprompt$ >>echo \[\e[31;1m\]"See if this goes to color red?"\[\e\0m\]

-----Original Message-----
>From: Luke Paireepinart <rabidpoobear at gmail.com>
>Sent: Jan 1, 2007 2:55 PM
>To: LandSurveyor <chiselchip at earthlink.net>
>Cc: tutor at python.org
>Subject: Re: [Tutor] display text in colors
>
>LandSurveyor wrote:
>> I would like to direct a python script to display 'print' strings in various (chosen) colors; for example:
>>
>> print \
>> """
>> color this line blue   # in the printout display-be it screen or hardcopy
>> color this line green  # in the printout display-be it screen or hardcopy
>> """
>> what I tried doing was:
>> import os
>> then the line...<os.system('\[\e[31;1m\]')> just before the print command (I borrowed this formatting from my $PS1 format.
>>
>> Nadda.  Didn't work.  What might I try?
>>   
>Uh, I think it's pretty important what operating system you're using here.
>Could you let us know before we try to help further?
>Thanks,
>-Luke
>


From bgailer at alum.rpi.edu  Mon Jan  1 23:11:39 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 01 Jan 2007 14:11:39 -0800
Subject: [Tutor] Starting python from a DOS prompt from any directory?
In-Reply-To: <enbloj$m59$1@sea.gmane.org>
References: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com><en7t1t$ojm$1@sea.gmane.org><F26FB35DD3F82E4FA091D483D36C610C02817887@MAILBE05.MAIL.LA.GOV><en9d8p$un$1@sea.gmane.org><6d87ecf40612311543l157b18e6x963d97df99a55295@mail.gmail.com>	<F26FB35DD3F82E4FA091D483D36C610C02817888@MAILBE05.MAIL.LA.GOV>
	<enbloj$m59$1@sea.gmane.org>
Message-ID: <4599871B.10606@alum.rpi.edu>

Alan Gauld wrote:
> "Steve Oldner" <Steven.Oldner at LA.GOV> wrote
>   
>> Alan, I work for a state government, so I'm not suppose to 
>> download PYTHON without submitting reasons and 
>> getting permissions.   
>>     
>
> Sure I understand that, but it looks from your post that 
> you have somehow managed to install Python. 
As I recall Steve said at the beginning that he ran Python from a 
network drive.
> If your 
> account has permissions to install any software then 
> you probably have permissions to set at least USER 
> level Environmenent Variables (You may not be able to 
> set them at SYSTEM level)
>
>   
>> I'm an applications programmer working on SAP 
>>     
>
> I know the kind of set up, we have similar teams of 
> folks working on Siebel and Oracle.
>
> Alan G.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454


From alan.gauld at btinternet.com  Tue Jan  2 00:06:33 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 1 Jan 2007 23:06:33 -0000
Subject: [Tutor] Starting python from a DOS prompt from any directory?
References: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com><en7t1t$ojm$1@sea.gmane.org><F26FB35DD3F82E4FA091D483D36C610C02817887@MAILBE05.MAIL.LA.GOV><en9d8p$un$1@sea.gmane.org><6d87ecf40612311543l157b18e6x963d97df99a55295@mail.gmail.com>	<F26FB35DD3F82E4FA091D483D36C610C02817888@MAILBE05.MAIL.LA.GOV><enbloj$m59$1@sea.gmane.org>
	<4599871B.10606@alum.rpi.edu>
Message-ID: <enc427$r0k$1@sea.gmane.org>

"Bob Gailer" <bgailer at alum.rpi.edu> wrote 

>> Sure I understand that, but it looks from your post that 
>> you have somehow managed to install Python. 
> As I recall Steve said at the beginning that he ran Python from a 
> network drive.

Nope, he said it was a networked PC but that Python was 
in his D: drive, which I assumed was local. But that raises an 
interesting proposition,. one that I've never tried. Is it possible 
under Windows to install Python from machine A onto 
a network drive and then run Python from machine B accessing 
that drive? In other words does the installer need to do any magic 
in the registry for Python to work or is it all just path setting 
and shortcuts?

Can anyone confirm or otherwise the possibility?

Curious,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at btinternet.com  Tue Jan  2 01:14:34 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 2 Jan 2007 00:14:34 -0000
Subject: [Tutor] Session from different app or domain
References: <20070101193349.42145.qmail@web55213.mail.re4.yahoo.com>
Message-ID: <enc81o$7so$1@sea.gmane.org>

"anil maran" <anilmrn at yahoo.com> wrote

> Here is the problem the example usage is in Django
> 
> and they are talking about a request object
>    if 'session_key' in request.session and 'uid' in
> request.session:
>        fb.session_key =
> request.session['session_key']
> 
> Anyone can tell me how I can access this in webpy
> Isnt flup something that is set from webpy, 

OK, I'm confused.

Can you clarify what is happening for me?
Are you using Django? Are you using webpy? Or both?
Also what is flup? I've never heard of it...

Also what is the 'this' that you want to access in webpy? 
Is it the request or the session? Or do you want to 
access Django code from webpy?

As I say, I'm confused about what you are using 
and what you want us to help you with?

Alan G.
Who is learning TurnoGears and knows next to 
nothing about webpy and only a little about Django...


From m.wilkinson at tideway.com  Tue Jan  2 10:22:25 2007
From: m.wilkinson at tideway.com (Mark Wilkinson)
Date: Tue, 2 Jan 2007 09:22:25 -0000
Subject: [Tutor] Starting python from a DOS prompt from any directory?
Message-ID: <B81183566FF73947875C3A207CD60AA602E2F770@LONEX01.tideway.com>


I think this will answer your question:
 
http://www.python.org/doc/faq/windows.html#how-do-i-run-a-python-program
-under-windows
 
Mark
This email and any attachment may contain confidential, privileged information for the sole use of the intended recipient. If you are not the intended recipient, do not disclose, reproduce, disseminate or otherwise use this communication. If you received this communication in error, please immediately notify the sender via email and delete the communication from your system.

From Steven.Oldner at LA.GOV  Tue Jan  2 13:02:50 2007
From: Steven.Oldner at LA.GOV (Steve Oldner)
Date: Tue, 2 Jan 2007 06:02:50 -0600
Subject: [Tutor] Starting python from a DOS prompt from any directory?
References: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com><en7t1t$ojm$1@sea.gmane.org><F26FB35DD3F82E4FA091D483D36C610C02817887@MAILBE05.MAIL.LA.GOV><en9d8p$un$1@sea.gmane.org><6d87ecf40612311543l157b18e6x963d97df99a55295@mail.gmail.com>	<F26FB35DD3F82E4FA091D483D36C610C02817888@MAILBE05.MAIL.LA.GOV>
	<enbloj$m59$1@sea.gmane.org> <4599871B.10606@alum.rpi.edu>
Message-ID: <F26FB35DD3F82E4FA091D483D36C610C0281788F@MAILBE05.MAIL.LA.GOV>

Sorry for the delay, and the confusion.
 
C and D are the local PC dir, where C has the network and mandatory programs installed.  D is my working DIR.  SO PYTHON is installed locally for me.   

________________________________

From: tutor-bounces at python.org on behalf of Bob Gailer
Sent: Mon 1/1/2007 4:11 PM
To: Alan Gauld
Cc: tutor at python.org
Subject: Re: [Tutor] Starting python from a DOS prompt from any directory?



Alan Gauld wrote:
> "Steve Oldner" <Steven.Oldner at LA.GOV> wrote
>  
>> Alan, I work for a state government, so I'm not suppose to
>> download PYTHON without submitting reasons and
>> getting permissions.  
>>    
>
> Sure I understand that, but it looks from your post that
> you have somehow managed to install Python.
As I recall Steve said at the beginning that he ran Python from a
network drive.
> If your
> account has permissions to install any software then
> you probably have permissions to set at least USER
> level Environmenent Variables (You may not be able to
> set them at SYSTEM level)
>
>  
>> I'm an applications programmer working on SAP
>>    
>
> I know the kind of set up, we have similar teams of
> folks working on Siebel and Oracle.
>
> Alan G.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>  


--
Bob Gailer
510-978-4454

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


From rdm at rcblue.com  Tue Jan  2 19:18:49 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 02 Jan 2007 10:18:49 -0800
Subject: [Tutor] Need help with rewriting script to use Decimal  module
Message-ID: <7.0.1.0.2.20070102101030.067d7a90@rcblue.com>

from decimal import Decimal as D

def bestFracForMinimumError(decimal, minimumError):
     denom = 0
     while True:
         denom += 1
         num = round(D(str(decimal)) * D(str(denom)))
         error = abs(str((str(D(num) / D(str(denom))) - 
D(str(decimal))) / str(D(str(decimal)) * d("100"))))
         if error <= D(minimumError):
             break
     return int(num), D(denom), error

dec = D(".34576598876876867756765765")

me = D(".0001")

print bestFracForMinimumError(dec, me)


Traceback (most recent call last):
   File "fracSimple2-c.py", line 17, in <module>
     print bestFracForMinimumError(dec, me)
   File "fracSimple2-c.py", line 8, in bestFracForMinimumError
     error = abs(str((str(D(num) / D(str(denom))) - D(str(decimal))) 
/ str(D(str(
decimal)) * d("100"))))
   File "E:\Python25\lib\decimal.py", line 578, in __new__
     "First convert the float to a string")
TypeError: Cannot convert float to Decimal.  First convert the float 
to a string

I don't understand this TypeError. Seems to me that I've converted 
EVERYTHING in that line 8 to a string.

Dick


From carloslara at web.de  Tue Jan  2 19:37:27 2007
From: carloslara at web.de (Carlos)
Date: Tue, 02 Jan 2007 19:37:27 +0100
Subject: [Tutor] Encoding and Decoding
In-Reply-To: <mailman.6438.1167730775.32030.tutor@python.org>
References: <mailman.6438.1167730775.32030.tutor@python.org>
Message-ID: <459AA667.30700@web.de>

Hello,

I have been having problems to solve a situation in which I need to 
encode and decode information, hope that someone can give me a hand. The 
solution for this problem has gone thru many iterations, but I recently 
found that the long (for me) is the only one.

As you might remember Im working with some elements, for example:

ELEMENTS = [{'Name': 'Access', 'Parent': 'Plot', 'Level': 1.0, 'Height': 
3.0, 'Width': 3.0, 'Depth': 3.0},
                            {'Name': 'Circulation_01', 'Parent': 
'Access', 'Level': 1.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0},
                            {'Name': 'Circulation_02', 'Parent': 
'Access', 'Level': 2.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0},
                            {'Name': 'Circulation_03', 'Parent': 
'Access', 'Level': 3.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0},
                            {'Name': 'Int_Circ_01', 'Parent': 
'Circulation_01', 'Level': 1.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0},
                            {'Name': 'Int_Circ_02', 'Parent': 
'Circulation_01', 'Level': 1.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0},
                            {'Name': 'Int_Circ_03', 'Parent': 
'Circulation_02', 'Level': 2.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0},
                            {'Name': 'Int_Circ_04', 'Parent': 
'Circulation_02', 'Level': 2.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0},
                            {'Name': 'Int_Circ_05', 'Parent': 
'Circulation_03', 'Level': 3.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0},
                            {'Name': 'Int_Circ_06', 'Parent': 
'Circulation_03', 'Level': 3.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0}
                         ]

The genetic algorithm that Im using (GA) generates solutions for a given 
problem, expressed in a list, this list is composed by integers. Every 
element in the list takes 8 integers, is a little messy but this is because

List [0] = Tens X position
List [1] = Units X position
List [2] = Decimals X position
List [3] = If < than 5 the number is negative, else is positive

Then if the result is List = [6, 1, 2, 3] the X position equals -612.3. 
This is the same for the Y position. If there are 10 elements the list 
is going to be 80 integers long and if there are 100 elements, well you 
get a very long list...

With this in mind my question would be, how can I keep track of this 
information? I mean how can I assign this List positions to each 
element? This is needed because this is going to be a long list and the 
GA needs to evaluate the position of each element with respect to the 
position of the other elements. So it needs to know that certain numbers 
are related to certain element and it needs to have access to the size, 
level, name and parent information... I hope that this is clear enough.

Thanks in advance,
Carlos







From kent37 at tds.net  Tue Jan  2 19:39:43 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 02 Jan 2007 13:39:43 -0500
Subject: [Tutor] Need help with rewriting script to use Decimal  module
In-Reply-To: <7.0.1.0.2.20070102101030.067d7a90@rcblue.com>
References: <7.0.1.0.2.20070102101030.067d7a90@rcblue.com>
Message-ID: <459AA6EF.7050909@tds.net>

Dick Moores wrote:
> from decimal import Decimal as D
> 
> def bestFracForMinimumError(decimal, minimumError):
>      denom = 0
>      while True:
>          denom += 1
>          num = round(D(str(decimal)) * D(str(denom)))
>          error = abs(str((str(D(num) / D(str(denom))) - 
This looks backwards        ^^^^^^^^^^

Don't you need D(str(num)) ? Then converting it back to a str before you 
call abs will not work.

Your old approach of
def D(num):
   return Decimal(str(num))

would probably make for more readable code and fewer errors.

I'm not sure this approach will work, though, if you are trying to get 
higher precision, I would think you would have to do all the 
calculations in Decimal, not going to floats for num. I admit I haven't 
thought it through, though. I think you can use Decimal.quantize() 
instead of round().

HTH
Kent

> D(str(decimal))) / str(D(str(decimal)) * d("100"))))
>          if error <= D(minimumError):
>              break
>      return int(num), D(denom), error
> 
> dec = D(".34576598876876867756765765")
> 
> me = D(".0001")
> 
> print bestFracForMinimumError(dec, me)
> 
> 
> Traceback (most recent call last):
>    File "fracSimple2-c.py", line 17, in <module>
>      print bestFracForMinimumError(dec, me)
>    File "fracSimple2-c.py", line 8, in bestFracForMinimumError
>      error = abs(str((str(D(num) / D(str(denom))) - D(str(decimal))) 
> / str(D(str(
> decimal)) * d("100"))))
>    File "E:\Python25\lib\decimal.py", line 578, in __new__
>      "First convert the float to a string")
> TypeError: Cannot convert float to Decimal.  First convert the float 
> to a string
> 
> I don't understand this TypeError. Seems to me that I've converted 
> EVERYTHING in that line 8 to a string.
> 
> Dick
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From kent37 at tds.net  Tue Jan  2 19:52:50 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 02 Jan 2007 13:52:50 -0500
Subject: [Tutor] Encoding and Decoding
In-Reply-To: <459AA667.30700@web.de>
References: <mailman.6438.1167730775.32030.tutor@python.org>
	<459AA667.30700@web.de>
Message-ID: <459AAA02.5080202@tds.net>

Carlos wrote:

> The genetic algorithm that Im using (GA) generates solutions for a given 
> problem, expressed in a list, this list is composed by integers. Every 
> element in the list takes 8 integers, is a little messy but this is because
> 
> List [0] = Tens X position
> List [1] = Units X position
> List [2] = Decimals X position
> List [3] = If < than 5 the number is negative, else is positive
> 
> Then if the result is List = [6, 1, 2, 3] the X position equals -612.3. 
> This is the same for the Y position. If there are 10 elements the list 
> is going to be 80 integers long and if there are 100 elements, well you 
> get a very long list...
> 
> With this in mind my question would be, how can I keep track of this 
> information? I mean how can I assign this List positions to each 
> element? This is needed because this is going to be a long list and the 
> GA needs to evaluate the position of each element with respect to the 
> position of the other elements. So it needs to know that certain numbers 
> are related to certain element and it needs to have access to the size, 
> level, name and parent information... I hope that this is clear enough.

I will assume there is a good reason for storing the coordinates in this 
form...

Do the numbers have to be all in a single list? I would start by 
breaking it up into lists of four, so if you have 10 elements you would 
have a list of 20 small lists. It might make sense to pair the x and y 
lists so you have a list of 10 lists of 2 lists of 4 numbers, e.g.
[ [ [6, 1, 2, 3], [7, 2, 8, 4] ], ...]

Another thing to consider is whether you might want to make a class to 
hold the coordinate values, then you could refer to x.tens, x.units, 
x.decimal, x.sign by name.

If you need a single list for the GA to work, one alternative would be 
to make converters between the nested representation and the flat one. 
Alternately you could wrap the list in a class which provides helpful 
accessors.

HTH
Kent


From carloslara at web.de  Tue Jan  2 20:12:13 2007
From: carloslara at web.de (Carlos)
Date: Tue, 02 Jan 2007 20:12:13 +0100
Subject: [Tutor] Encoding and Decoding
In-Reply-To: <459AAA02.5080202@tds.net>
References: <mailman.6438.1167730775.32030.tutor@python.org>
	<459AA667.30700@web.de> <459AAA02.5080202@tds.net>
Message-ID: <459AAE8D.3000803@web.de>

Hi Kent,

I have yet to get into OO, and the GA that I'm using was done in this 
way, so I can't mess with it that much. So for now yes, the list has to 
be a flat element containing all this info.

I have been reading about OO lately and a element class seems to be a 
good idea, I'm working on it now, but I still don't get OO very well. My 
initial idea is that a loop could iterate over the element list and 
create objects with the needed parameters and hooks to the list that 
link to the correct list locations.

Could you elaborate on the converters and the class that wraps the list???

Thanks




Kent Johnson wrote:
> I will assume there is a good reason for storing the coordinates in 
> this form...
>
> Do the numbers have to be all in a single list? I would start by 
> breaking it up into lists of four, so if you have 10 elements you 
> would have a list of 20 small lists. It might make sense to pair the x 
> and y lists so you have a list of 10 lists of 2 lists of 4 numbers, e.g.
> [ [ [6, 1, 2, 3], [7, 2, 8, 4] ], ...]
>
> Another thing to consider is whether you might want to make a class to 
> hold the coordinate values, then you could refer to x.tens, x.units, 
> x.decimal, x.sign by name.
>
> If you need a single list for the GA to work, one alternative would be 
> to make converters between the nested representation and the flat one. 
> Alternately you could wrap the list in a class which provides helpful 
> accessors.
>
> HTH
> Kent
>
>


From kent37 at tds.net  Tue Jan  2 20:31:47 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 02 Jan 2007 14:31:47 -0500
Subject: [Tutor] Encoding and Decoding
In-Reply-To: <459AAE8D.3000803@web.de>
References: <mailman.6438.1167730775.32030.tutor@python.org>	<459AA667.30700@web.de>
	<459AAA02.5080202@tds.net> <459AAE8D.3000803@web.de>
Message-ID: <459AB323.1020609@tds.net>

Carlos wrote:
> Hi Kent,
> 
> I have yet to get into OO, and the GA that I'm using was done in this 
> way, so I can't mess with it that much. So for now yes, the list has to 
> be a flat element containing all this info.
> 
> I have been reading about OO lately and a element class seems to be a 
> good idea, I'm working on it now, but I still don't get OO very well. My 
> initial idea is that a loop could iterate over the element list and 
> create objects with the needed parameters and hooks to the list that 
> link to the correct list locations.
> 
> Could you elaborate on the converters and the class that wraps the list???

OK, off the top of my head (not tested) here are some things to get you 
started.

You could write a function that would retrieve a coordinate value given 
an index number, for example:
def getCoord(data, ix):
   base = ix*4
   value = data[ix]*10 + data[ix+1] + data[ix+2]/10.0
   if data[ix+3] < 5:
     value = -value
   return value

Now if data is your big list, you can write getCoord(data, 5) to get the 
value stored at data[20] to data[23]. Similarly you could write a setter 
and maybe a getXY() function that returns a pair (x, y). So that is a 
place to start.

If you want to avoid passing the list around it might make sense to make 
a class to hold it. Then you would have something like
class Data(object):
   def __init__(self, lst):
     self.data = lst

   def getCoord(self, ix):
     base = ix*4
     value = self.data[ix]*10 + self.data[ix+1] + self.data[ix+2]/10.0
     if self.data[ix+3] < 5:
       value = -value
     return value

Now you can create a Data object from a list of values and ask it for 
values:
d = Data(<some list>)
d.getCoord(5)

I'm not sure this is much improvement over passing around the list, 
actually; you still have to pass around the Data object...it might just 
be a matter of taste.

HTH,
Kent

> 
> Thanks
> 
> 
> 
> 
> Kent Johnson wrote:
>> I will assume there is a good reason for storing the coordinates in 
>> this form...
>>
>> Do the numbers have to be all in a single list? I would start by 
>> breaking it up into lists of four, so if you have 10 elements you 
>> would have a list of 20 small lists. It might make sense to pair the x 
>> and y lists so you have a list of 10 lists of 2 lists of 4 numbers, e.g.
>> [ [ [6, 1, 2, 3], [7, 2, 8, 4] ], ...]
>>
>> Another thing to consider is whether you might want to make a class to 
>> hold the coordinate values, then you could refer to x.tens, x.units, 
>> x.decimal, x.sign by name.
>>
>> If you need a single list for the GA to work, one alternative would be 
>> to make converters between the nested representation and the flat one. 
>> Alternately you could wrap the list in a class which provides helpful 
>> accessors.
>>
>> HTH
>> Kent
>>
>>
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From moray at sdf.lonestar.org  Tue Jan  2 20:16:33 2007
From: moray at sdf.lonestar.org (Joe M)
Date: Tue, 2 Jan 2007 19:16:33 +0000 (UTC)
Subject: [Tutor] basic python question/getting values
Message-ID: <Pine.NEB.4.62.0701021857340.23688@sdf.lonestar.org>

I apologize in advanced as I know this is basic information, but I cannot 
seem to figure it.

I have a few scripts that will return a value ie here I am testing to see 
if a database is alive (script is called dbping.py):

def db_alive():
 	dbRunning = '0'
 	try:
 		con = pg.connect(dbname='xxx', host='localhost', user 
='xxx',port = xxx)
 	pass
 	except pg.InternalError:
 		dbRunning = '1'
 	return dbRunning

This should return a value of 1 if the db is not running else it will 
return a value of 0.

Ok, now I want to call this from another script and have it write 
to a file with the return value (and other values to be added later, but 
right now all I am interested in in getting the return values)

I tried this sort of thing but it doesn't work (I will be writing to a 
file later, but right now getting it to print the value of dbRunning would 
be nice)

import dbping
l = dbping.db_run(db_run.dbRunning)
print l

NameError: name 'db_run' is not defined

Thanks for any pointers

moray at sdf.lonestar.org
SDF Public Access UNIX System - http://sdf.lonestar.org

From jalilsan at gmail.com  Tue Jan  2 20:30:39 2007
From: jalilsan at gmail.com (Jalil)
Date: Tue, 2 Jan 2007 11:30:39 -0800
Subject: [Tutor] python cx_Oracle.LOB
Message-ID: <5850ed90701021130x4f8fa525tadba910cf8cdfa19@mail.gmail.com>

I am trying to fetch a CLOB datatype with with cx_Oracle and I can seem to
get it to work.



I was able to fetch the text from the db with sql commands  but i can fetch
in a python code.

I get this output.

[(<cx_Oracle.LOB object at 0xb7f23530>,)]

when I run my code.

any way to find out how to go around this?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070102/b9cd4d13/attachment.htm 

From kent37 at tds.net  Tue Jan  2 20:54:14 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 02 Jan 2007 14:54:14 -0500
Subject: [Tutor] basic python question/getting values
In-Reply-To: <Pine.NEB.4.62.0701021857340.23688@sdf.lonestar.org>
References: <Pine.NEB.4.62.0701021857340.23688@sdf.lonestar.org>
Message-ID: <459AB866.2080100@tds.net>

Joe M wrote:
> I have a few scripts that will return a value ie here I am testing to see 
> if a database is alive (script is called dbping.py):
> 
> def db_alive():
>  	dbRunning = '0'
>  	try:
>  		con = pg.connect(dbname='xxx', host='localhost', user 
> ='xxx',port = xxx)
>  	pass
>  	except pg.InternalError:
>  		dbRunning = '1'
>  	return dbRunning
> 
> This should return a value of 1 if the db is not running else it will 
> return a value of 0.
> 
> Ok, now I want to call this from another script and have it write 
> to a file with the return value (and other values to be added later, but 
> right now all I am interested in in getting the return values)
> 
> I tried this sort of thing but it doesn't work (I will be writing to a 
> file later, but right now getting it to print the value of dbRunning would 
> be nice)
> 
> import dbping
> l = dbping.db_run(db_run.dbRunning)
> print l
> 
> NameError: name 'db_run' is not defined

What is db_run? What happens if you try
l = dbping.db_alive()

??

Kent


From moray at sdf.lonestar.org  Tue Jan  2 20:53:01 2007
From: moray at sdf.lonestar.org (Joe M)
Date: Tue, 2 Jan 2007 19:53:01 +0000 (UTC)
Subject: [Tutor] basic python question/getting values
In-Reply-To: <b4e894c70701021138k2b533d32pe64f1a564b2738a7@mail.gmail.com>
References: <Pine.NEB.4.62.0701021857340.23688@sdf.lonestar.org>
	<b4e894c70701021138k2b533d32pe64f1a564b2738a7@mail.gmail.com>
Message-ID: <Pine.NEB.4.62.0701021951130.8836@sdf.lonestar.org>

Thanks. I appreciate the quick response. I am going to kick myself for 
this one ;)

On Tue, 2 Jan 2007, Asrarahmed Kadri wrote:

> Date: Tue, 2 Jan 2007 19:38:04 +0000
> From: Asrarahmed Kadri <ajkadri at googlemail.com>
> To: Joe M <moray at sdf.lonestar.org>
> Subject: Re: [Tutor] basic python question/getting values
> 
> Hey, the call should be:
> dbping.db_alive()
> and not dbping.db_run()
>
> HTH,
> Regards,
> Asrarahmed
>
>
> On 1/2/07, Joe M <moray at sdf.lonestar.org> wrote:
>> 
>> I apologize in advanced as I know this is basic information, but I cannot
>> seem to figure it.
>> 
>> I have a few scripts that will return a value ie here I am testing to see
>> if a database is alive (script is called dbping.py):
>> 
>> def db_alive():
>>         dbRunning = '0'
>>         try:
>>                 con = pg.connect(dbname='xxx', host='localhost', user
>> ='xxx',port = xxx)
>>         pass
>>         except pg.InternalError:
>>                 dbRunning = '1'
>>         return dbRunning
>> 
>> This should return a value of 1 if the db is not running else it will
>> return a value of 0.
>> 
>> Ok, now I want to call this from another script and have it write
>> to a file with the return value (and other values to be added later, but
>> right now all I am interested in in getting the return values)
>> 
>> I tried this sort of thing but it doesn't work (I will be writing to a
>> file later, but right now getting it to print the value of dbRunning would
>> be nice)
>> 
>> import dbping
>> l = dbping.db_run(db_run.dbRunning)
>> print l
>> 
>> NameError: name 'db_run' is not defined
>> 
>> Thanks for any pointers
>> 
>> moray at sdf.lonestar.org
>> SDF Public Access UNIX System - http://sdf.lonestar.org
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>> 
>
>
>
> -- 
> To HIM you shall return.
>

moray at sdf.lonestar.org
SDF Public Access UNIX System - http://sdf.lonestar.org

From carloslara at web.de  Tue Jan  2 21:07:55 2007
From: carloslara at web.de (Carlos)
Date: Tue, 02 Jan 2007 21:07:55 +0100
Subject: [Tutor] Encoding and Decoding
In-Reply-To: <459AB323.1020609@tds.net>
References: <mailman.6438.1167730775.32030.tutor@python.org>	<459AA667.30700@web.de>
	<459AAA02.5080202@tds.net> <459AAE8D.3000803@web.de>
	<459AB323.1020609@tds.net>
Message-ID: <459ABB9B.8020500@web.de>


Kent,

Will give this a try.

Thanks for your help,
Carlos


Kent Johnson wrote:
> OK, off the top of my head (not tested) here are some things to get 
> you started.
>
> You could write a function that would retrieve a coordinate value 
> given an index number, for example:
> def getCoord(data, ix):
>   base = ix*4
>   value = data[ix]*10 + data[ix+1] + data[ix+2]/10.0
>   if data[ix+3] < 5:
>     value = -value
>   return value
>
> Now if data is your big list, you can write getCoord(data, 5) to get 
> the value stored at data[20] to data[23]. Similarly you could write a 
> setter and maybe a getXY() function that returns a pair (x, y). So 
> that is a place to start.
>
> If you want to avoid passing the list around it might make sense to 
> make a class to hold it. Then you would have something like
> class Data(object):
>   def __init__(self, lst):
>     self.data = lst
>
>   def getCoord(self, ix):
>     base = ix*4
>     value = self.data[ix]*10 + self.data[ix+1] + self.data[ix+2]/10.0
>     if self.data[ix+3] < 5:
>       value = -value
>     return value
>
> Now you can create a Data object from a list of values and ask it for 
> values:
> d = Data(<some list>)
> d.getCoord(5)
>
> I'm not sure this is much improvement over passing around the list, 
> actually; you still have to pass around the Data object...it might 
> just be a matter of taste.
>
> HTH,
> Kent


From jason.massey at gmail.com  Tue Jan  2 21:54:53 2007
From: jason.massey at gmail.com (Jason Massey)
Date: Tue, 2 Jan 2007 14:54:53 -0600
Subject: [Tutor] python cx_Oracle.LOB
In-Reply-To: <5850ed90701021130x4f8fa525tadba910cf8cdfa19@mail.gmail.com>
References: <5850ed90701021130x4f8fa525tadba910cf8cdfa19@mail.gmail.com>
Message-ID: <7e3eab2c0701021254v3c619e9fh8cc5fe9b887d895c@mail.gmail.com>

An example of your code would help. According to the cx_oracle docs at
http://www.python.net/crew/atuining/cx_Oracle/html/index.html under the LOB
Objects heading:

6. LOB Objects

*NOTE*: This object is an extension the DB API. It is returned whenever
Oracle CLOB, BLOB and BFILE columns are fetched.

*NOTE*: Internally, Oracle uses LOB locators which are allocated based on
the cursor array size. Thus, it is important that the data in the LOB object
be manipulated before another internal fetch takes place. The safest way to
do this is to use the cursor as an iterator. In particular, do not use the
fetchall() method. The exception "LOB variable no longer valid after
subsequent fetch" will be raised if an attempt to access a LOB variable
after a subsequent fetch is detected.

 *fileexists*( ) Return a boolean indicating if the file referenced by the
BFILE type LOB exists.

 *getfilename*( ) Return a two-tuple consisting of the directory alias and
file name for a BFILE type LOB.

 *read*( [offset = 1, [amount]]) Return a portion (or all) of the data in
the LOB object.

 *setfilename*( dirAlias, name) Set the directory alias and name of the
BFILE type LOB.

 *size*( ) Returns the size of the data in the LOB object.

 *trim*( [newSize = 0]) Trim the LOB to the new size.

 *write*( data, [offset = 1]) Write the data to the LOB object at the given
offset. Note that if you want to make the LOB value smaller, you must use
the trim() function.
I'd try the read method on your object.

On 1/2/07, Jalil <jalilsan at gmail.com> wrote:
>
> I am trying to fetch a CLOB datatype with with cx_Oracle and I can seem to
> get it to work.
>
>
>
> I was able to fetch the text from the db with sql commands  but i can
> fetch in a python code.
>
> I get this output.
>
> [(<cx_Oracle.LOB object at 0xb7f23530>,)]
>
> when I run my code.
>
> any way to find out how to go around this?
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070102/55c1133d/attachment.html 

From jalilsan at gmail.com  Tue Jan  2 22:09:53 2007
From: jalilsan at gmail.com (Jalil)
Date: Tue, 2 Jan 2007 13:09:53 -0800
Subject: [Tutor] python cx_Oracle.LOB
In-Reply-To: <7e3eab2c0701021254v3c619e9fh8cc5fe9b887d895c@mail.gmail.com>
References: <5850ed90701021130x4f8fa525tadba910cf8cdfa19@mail.gmail.com>
	<7e3eab2c0701021254v3c619e9fh8cc5fe9b887d895c@mail.gmail.com>
Message-ID: <5850ed90701021309he1044fbm55591d73b574fd3d@mail.gmail.com>

Thanks Jason,
here is my code



import cx_Oracle

db = cx_Oracle.connect('xxxxxx','xxxxx','xxxx')
cursor=db.cursor()
#cursor.execute('set long 5000')
#sqlen="""set long 5000"""
#cursor.execute(sqlen)
sqtext="""select TExt from sq_updates where action_id= '851151'"""
cursor.execute(sqtext)
rettext = cursor.fetchmany()

print rettext



On 1/2/07, Jason Massey <jason.massey at gmail.com> wrote:
>
> An example of your code would help. According to the cx_oracle docs at
> http://www.python.net/crew/atuining/cx_Oracle/html/index.html under the
> LOB Objects heading:
>
> 6. LOB Objects
>
> *NOTE*: This object is an extension the DB API. It is returned whenever
> Oracle CLOB, BLOB and BFILE columns are fetched.
>
> *NOTE*: Internally, Oracle uses LOB locators which are allocated based on
> the cursor array size. Thus, it is important that the data in the LOB object
> be manipulated before another internal fetch takes place. The safest way to
> do this is to use the cursor as an iterator. In particular, do not use the
> fetchall() method. The exception "LOB variable no longer valid after
> subsequent fetch" will be raised if an attempt to access a LOB variable
> after a subsequent fetch is detected.
>
>  *fileexists*( ) Return a boolean indicating if the file referenced by the
> BFILE type LOB exists.
>
>  *getfilename*( ) Return a two-tuple consisting of the directory alias and
> file name for a BFILE type LOB.
>
>  *read*( [offset = 1, [amount]]) Return a portion (or all) of the data in
> the LOB object.
>
>  *setfilename*( dirAlias, name) Set the directory alias and name of the
> BFILE type LOB.
>
>  *size*( ) Returns the size of the data in the LOB object.
>
>  *trim*( [newSize = 0]) Trim the LOB to the new size.
>
>  *write*( data, [offset = 1]) Write the data to the LOB object at the
> given offset. Note that if you want to make the LOB value smaller, you must
> use the trim() function.
> I'd try the read method on your object.
>
> On 1/2/07, Jalil <jalilsan at gmail.com> wrote:
>
> > I am trying to fetch a CLOB datatype with with cx_Oracle and I can seem
> > to get it to work.
> >
> >
> >
> > I was able to fetch the text from the db with sql commands  but i can
> > fetch in a python code.
> >
> > I get this output.
> >
> > [(<cx_Oracle.LOB object at 0xb7f23530>,)]
> >
> > when I run my code.
> >
> > any way to find out how to go around this?
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070102/28b95486/attachment-0001.html 

From carroll at tjc.com  Tue Jan  2 22:17:17 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 2 Jan 2007 13:17:17 -0800 (PST)
Subject: [Tutor] Need help with rewriting script to use Decimal module
In-Reply-To: <7.0.1.0.2.20070101034429.0353de58@rcblue.com>
Message-ID: <Pine.LNX.4.44.0701021302460.16745-100000@violet.rahul.net>

On Mon, 1 Jan 2007, Dick Moores wrote:

> bestFracForMinimumError() is only a small part of a program I wrote 
> long ago, called frac.py 

Dick, if your goal is to have a routine to get the fraction with the least 
possible error (as opposed to learing how to use Decimal), have a look at 
this recipe from the Python Cookbook:

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

> dec = .345765988765560057657654654
> me = .0000000001
> num, denom, error = bestFracForMinimumError(dec, me)
> print "%f = %d/%d with %f per cent error" % (dec, num, denom, error)

The parameters are different from yours, but as I understand it, your 
equivalent is:

>>> dec = .345765988765560057657654654
>>> me = .0000000001
>>> max_denom = 1/me
>>> (num, denom) = farey(dec,max_denom)
>>> error = abs((num/denom) - dec) *100
>>> print "%f = %d/%d with %f per cent error" % (dec, num, denom, error)
0.345766 = 40258524/116432863 with 0.000000 per cent error
>>>


From Barry.Carroll at psc.com  Tue Jan  2 21:22:44 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Tue, 2 Jan 2007 12:22:44 -0800
Subject: [Tutor] basic python question/getting values
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A5A@eugsrv400.psc.pscnet.com>

Joe:

See below:

> -----Original Message-----
> Date: Tue, 2 Jan 2007 19:16:33 +0000 (UTC)
> From: Joe M <moray at sdf.lonestar.org>
> Subject: [Tutor] basic python question/getting values
> To: tutor at python.org
> Message-ID: <Pine.NEB.4.62.0701021857340.23688 at sdf.lonestar.org>
> Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed
> 
> I apologize in advanced as I know this is basic information, but I
cannot
> seem to figure it.
> 
> I have a few scripts that will return a value ie here I am testing to
see
> if a database is alive (script is called dbping.py):
> 
> def db_alive():
>  	dbRunning = '0'
>  	try:
>  		con = pg.connect(dbname='xxx', host='localhost', user
> ='xxx',port = xxx)
>  	pass
>  	except pg.InternalError:
>  		dbRunning = '1'
>  	return dbRunning
> 
<<snip>>
> 
> import dbping
> l = dbping.db_run(db_run.dbRunning) # 
> print l
> 
> NameError: name 'db_run' is not defined

You are not calling the function you defined. The name and number of
parameters are both wrong.  To match your function definition, your
assignment should be:

>>> l = dbping.db_alive()

Note, also, that the "pass" statement in dbping.db_alive will cause a
syntax error.  "pass" is only used when a code block is required but has
no executable statements.  For example:

>>> intval = 0
    .
    .
    .
    try:
        intval = int(strval)
    except ValueError:
        pass
        # strval is not a valid string representation of an integer.
        # intval remains 0.
        # Suppress the error and continue the program.  


> 
> Thanks for any pointers
> 
> moray at sdf.lonestar.org
> SDF Public Access UNIX System - http://sdf.lonestar.org
> 

HTH.

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




From carroll at tjc.com  Tue Jan  2 22:47:01 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 2 Jan 2007 13:47:01 -0800 (PST)
Subject: [Tutor] Need help with rewriting script to use Decimal module
In-Reply-To: <Pine.LNX.4.44.0701021302460.16745-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0701021333320.16745-100000@violet.rahul.net>

On Tue, 2 Jan 2007, Terry Carroll wrote:

> Dick, if your goal is to have a routine to get the fraction with the least 
> possible error (as opposed to learing how to use Decimal), have a look at 
> this recipe from the Python Cookbook:
> 
>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317

BTW, to get the higher precision in Decimal:

import decimal

def farey(v, lim):
  '''Named after James Farey, an English surveyor.
  No error checking on args -- lim = max denominator,
  results are (numerator, denominator), (1,0) is infinity
  '''
  if v < 0:
    n,d = farey(-v, lim)
    return int(-n),int(d)
  z = lim-lim	# get 0 of right type for denominator
  lower, upper = (z,z+1), (z+1,z)
  while 1:
    mediant = (lower[0] + upper[0]), (lower[1]+upper[1])
    if v * mediant[1] > mediant[0]:
        if lim < mediant[1]: return (int(upper[0]), int(upper[1]))
        lower = mediant
    elif v * mediant[1] == mediant[0]:
        if lim >= mediant[1]: return (int(mediant[0]), int(mediant[1]))
        if lower[1] < upper[1]: return (int(lower[0]), int(lower[1]))
        return (int(upper[0]), int(upper[1]))
    else:
        if lim < mediant[1]: return lower
        upper = mediant

dec = decimal.Decimal("0.345765988765560057657654654")
me = decimal.Decimal("0.0000000001")
max_denom = 1/me

(num, denom) = farey(dec,max_denom)
error = abs(decimal.Decimal(str(float(num)/denom)) - dec) *100
print "%s = %d/%d with %s per cent error" % (dec, num, denom, error)


Which gives:

0.345765988765560057657654654 = 878844001/2541730620 with 4.3994234234534600E-11 per cent error


From kmaheshw at science.uva.nl  Tue Jan  2 22:42:13 2007
From: kmaheshw at science.uva.nl (Ketan Maheshwari)
Date: Tue, 02 Jan 2007 22:42:13 +0100
Subject: [Tutor] simple animation
In-Reply-To: <mailman.6503.1167772195.32030.tutor@python.org>
References: <mailman.6503.1167772195.32030.tutor@python.org>
Message-ID: <459AD1B5.2010307@science.uva.nl>

Hi All

I want to create a simple animation on a 2D cartesian plane, wherein 
there are 2 identical circles drawn at an arbitrary distance with each 
other.
Now the idea is to move the circles randomly with a fixed step size and 
check the distance between their centers. this uses the formula
d=sqrt((x2-x1)**2+(y2-y1)**2). When this distance becomes same as 
2*radius, the circles are considered to be tangential.
Is it possible to show this scenario as an animation sequence and 
capturing the coordinates of the centers of the circles at each step and 
stopping the iteration when they get tangential.

Thanks.
k.

From chris.arndt at web.de  Tue Jan  2 23:28:46 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Tue, 02 Jan 2007 23:28:46 +0100
Subject: [Tutor] simple animation
In-Reply-To: <459AD1B5.2010307@science.uva.nl>
References: <mailman.6503.1167772195.32030.tutor@python.org>
	<459AD1B5.2010307@science.uva.nl>
Message-ID: <459ADC9E.7000409@web.de>

Ketan Maheshwari schrieb:
> Is it possible to show this scenario as an animation sequence and 
> capturing the coordinates of the centers of the circles at each step and 
> stopping the iteration when they get tangential.

Have a look at the PyGame library: http://pygame.org

Don't be put off be the name, it's actually rather a 2D/3D animation and
multimedia library than something specific to games. Have a look at the
tutorials on the site too:

http://pygame.org/wiki/tutorials

Chris

From kent37 at tds.net  Tue Jan  2 23:31:35 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 02 Jan 2007 17:31:35 -0500
Subject: [Tutor] simple animation
In-Reply-To: <459AD1B5.2010307@science.uva.nl>
References: <mailman.6503.1167772195.32030.tutor@python.org>
	<459AD1B5.2010307@science.uva.nl>
Message-ID: <459ADD47.9020503@tds.net>

Ketan Maheshwari wrote:
> Hi All
> 
> I want to create a simple animation on a 2D cartesian plane, wherein 
> there are 2 identical circles drawn at an arbitrary distance with each 
> other.

Here is a simple animation written in Tkinter that might get you started:

http://effbot.org/zone/tkinter-animation.htm

Kent

> Now the idea is to move the circles randomly with a fixed step size and 
> check the distance between their centers. this uses the formula
> d=sqrt((x2-x1)**2+(y2-y1)**2). When this distance becomes same as 
> 2*radius, the circles are considered to be tangential.
> Is it possible to show this scenario as an animation sequence and 
> capturing the coordinates of the centers of the circles at each step and 
> stopping the iteration when they get tangential.
> 
> Thanks.
> k.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From kmaheshw at science.uva.nl  Wed Jan  3 00:05:12 2007
From: kmaheshw at science.uva.nl (Ketan Maheshwari)
Date: Wed, 03 Jan 2007 00:05:12 +0100
Subject: [Tutor] simple animation
In-Reply-To: <459ADD47.9020503@tds.net>
References: <mailman.6503.1167772195.32030.tutor@python.org>
	<459AD1B5.2010307@science.uva.nl> <459ADD47.9020503@tds.net>
Message-ID: <459AE528.7080309@science.uva.nl>

That helps.
Thanks.

Kent Johnson wrote:
> Ketan Maheshwari wrote:
>> Hi All
>>
>> I want to create a simple animation on a 2D cartesian plane, wherein 
>> there are 2 identical circles drawn at an arbitrary distance with 
>> each other.
>
> Here is a simple animation written in Tkinter that might get you started:
>
> http://effbot.org/zone/tkinter-animation.htm
>
> Kent
>
>> Now the idea is to move the circles randomly with a fixed step size 
>> and check the distance between their centers. this uses the formula
>> d=sqrt((x2-x1)**2+(y2-y1)**2). When this distance becomes same as 
>> 2*radius, the circles are considered to be tangential.
>> Is it possible to show this scenario as an animation sequence and 
>> capturing the coordinates of the centers of the circles at each step 
>> and stopping the iteration when they get tangential.
>>
>> Thanks.
>> k.
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
>

From jalilsan at gmail.com  Wed Jan  3 00:56:08 2007
From: jalilsan at gmail.com (Jalil)
Date: Tue, 2 Jan 2007 15:56:08 -0800
Subject: [Tutor] mod_python
Message-ID: <5850ed90701021556k49d48a23y52d78b5a441a8ee4@mail.gmail.com>

I was just wondering if anyone know of a any good site with examples of
mod_python tutorial.
the mod_python manual assume isnt really that helpful.

thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070102/366e0f3f/attachment.htm 

From pyro9219 at gmail.com  Wed Jan  3 00:56:37 2007
From: pyro9219 at gmail.com (Chris Hengge)
Date: Tue, 2 Jan 2007 15:56:37 -0800
Subject: [Tutor] SPE - Stani's Python Editor ?
In-Reply-To: <7.0.1.0.2.20061231213332.06853e20@rcblue.com>
References: <45985A61.3000101@vladoportos.sk>
	<7.0.1.0.2.20061231213332.06853e20@rcblue.com>
Message-ID: <c25107380701021556yed22058ja4413fcae7e5cd0d@mail.gmail.com>

I've recently started playing with Eclipse and the two PyDev plugin's over
the holidays. I'm seriously liking it... but my likes are more closely
related to Visual Studio as an editor, so this is like the perfect
environment for me..

http://www.showmedo.com/videos/series?name=PyDevEclipseList

This link shows you two video's on how pydev works, and how to setup.

On 12/31/06, Dick Moores <rdm at rcblue.com> wrote:
>
>  At 04:48 PM 12/31/2006, Vladimir Strycek wrote:
>
> Hi all,
> some time ago i instaled SPE with python 2.4... it works very good...
> but yesterday my pc crash completly ( some dll went missing somehow :-)
> )... so  after format and  reinstalling of windows i begin to install
> all my programs back...
>
> When i come to python i download new 2.5 version and only version for
> win i could find is SPE-0.8.2.a-wx2.6.1.0-py24 which doesnt work... :-(
> newer version ist just rpm and i need exe for win... any idea if there
> will be exe or any more development in SPE cause homepage is not running
> etc...
>
> Or can you suggest similar IDE for python... ?
>
>
> I have SPE 0.8.3.c, which is for Python 2.5.  There is a mailing list for
> SPE users. See the archive at <https://lists.berlios.de/pipermail/python-spe-users/>.
> Stani was looking for another host for the website. His last post, of Wed
> Nov 29, says he has found one, and "Don't worry the SPE website will come
> back."
>
> In the meantime, if anyone wants a copy of the file I downloaded,
> SPE-0.8.3.c.win32-py2.5.exe, please contact me.
> "Program info
> Spe version 0.8.3.c
> Python version 2.5  (2.3 required)
> wxPython version 2.6.3.3.  (2.6.1.0. required)"
>
> The size of SPE-0.8.3.c.win32-py2.5.exe is 1,147 KB.
>
> Dick Moores
> rdm at rcblue.com
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070102/b8413acd/attachment-0001.html 

From simplebob at gmail.com  Wed Jan  3 03:14:16 2007
From: simplebob at gmail.com (Daniel McQuay)
Date: Tue, 2 Jan 2007 21:14:16 -0500
Subject: [Tutor] Starting python from a DOS prompt from any directory?
In-Reply-To: <enc427$r0k$1@sea.gmane.org>
References: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com>
	<en7t1t$ojm$1@sea.gmane.org>
	<F26FB35DD3F82E4FA091D483D36C610C02817887@MAILBE05.MAIL.LA.GOV>
	<en9d8p$un$1@sea.gmane.org>
	<6d87ecf40612311543l157b18e6x963d97df99a55295@mail.gmail.com>
	<F26FB35DD3F82E4FA091D483D36C610C02817888@MAILBE05.MAIL.LA.GOV>
	<enbloj$m59$1@sea.gmane.org> <4599871B.10606@alum.rpi.edu>
	<enc427$r0k$1@sea.gmane.org>
Message-ID: <6d87ecf40701021814v4e69bbd7r560f89de0cf617f4@mail.gmail.com>

On 1/1/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Bob Gailer" <bgailer at alum.rpi.edu> wrote
>
> >> Sure I understand that, but it looks from your post that
> >> you have somehow managed to install Python.
> > As I recall Steve said at the beginning that he ran Python from a
> > network drive.
>
> Nope, he said it was a networked PC but that Python was
> in his D: drive, which I assumed was local. But that raises an
> interesting proposition,. one that I've never tried. Is it possible
> under Windows to install Python from machine A onto
> a network drive and then run Python from machine B accessing
> that drive? In other words does the installer need to do any magic
> in the registry for Python to work or is it all just path setting
> and shortcuts?
>
> Can anyone confirm or otherwise the possibility?


i can try this under my networked drive tomorrow at school and if in fact
you can.

Curious,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

regards,

-- 
Daniel McQuay
boxster.homelinux.org
H: 814.825.0847
M: 814-341-9013
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070102/7aabba8a/attachment.html 

From rabidpoobear at gmail.com  Wed Jan  3 07:01:12 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 03 Jan 2007 00:01:12 -0600
Subject: [Tutor] mod_python
In-Reply-To: <5850ed90701021556k49d48a23y52d78b5a441a8ee4@mail.gmail.com>
References: <5850ed90701021556k49d48a23y52d78b5a441a8ee4@mail.gmail.com>
Message-ID: <459B46A8.4020803@gmail.com>

Jalil wrote:
> I was just wondering if anyone know of a any good site with examples 
> of mod_python tutorial.
> the mod_python manual assume isnt really that helpful.
I have been learning mod_python recently and I found the manual to be 
quite good...
what are you having problems with specifically?
>
> thanks
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From Mike.Hansen at atmel.com  Wed Jan  3 15:28:26 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Wed, 3 Jan 2007 07:28:26 -0700
Subject: [Tutor] SPE - Stani's Python Editor ?
Message-ID: <57B026980605A64F9B23484C5659E32E4C712C@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Chris Hengge
> Sent: Tuesday, January 02, 2007 4:57 PM
> To: Dick Moores
> Cc: tutor at python.org
> Subject: Re: [Tutor] SPE - Stani's Python Editor ?
> 
> I've recently started playing with Eclipse and the two PyDev 
> plugin's over the holidays. I'm seriously liking it... but my 
> likes are more closely related to Visual Studio as an editor, 
> so this is like the perfect environment for me.. 
> 
> http://www.showmedo.com/videos/series?name=PyDevEclipseList
> 
> This link shows you two video's on how pydev works, and how to setup. 
> 

I played with Eclipse a little bit. I got annoyed that the plugins would
nickel and dime you to death. Pydev is free, but the additional features
in Pydev Extensions cost $. I heard there was a plugin for vi emulation.
Unfortunately, it was another plugin that you had to pay for.

I decided to stick with VIM where the plugins are free. I recently
starting using VIM's snippets.emu plugin. It emulates TextMate's
snippets. TextMate is an editor for OS X that is getting a lot of
attention. There are people working on TextMate-like editors for Windows
and Linux.

Mike

  
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS

From cappy2112 at gmail.com  Wed Jan  3 19:30:13 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Wed, 3 Jan 2007 10:30:13 -0800
Subject: [Tutor] Tutor Digest, Vol 35, Issue 8
In-Reply-To: <mailman.59.1167822018.12911.tutor@python.org>
References: <mailman.59.1167822018.12911.tutor@python.org>
Message-ID: <8249c4ac0701031030g6efbc2f6l150e29e2c2f6eefb@mail.gmail.com>

Take a look at Movable Python.
It may not be exactly what you're looking for, but it may turn out to be a
resource to leverage from.

Message: 1
Date: Tue, 2 Jan 2007 21:14:16 -0500
From: "Daniel McQuay" <simplebob at gmail.com>
Subject: Re: [Tutor] Starting python from a DOS prompt from any
       directory?

> Nope, he said it was a networked PC but that Python was
> in his D: drive, which I assumed was local. But that raises an
> interesting proposition,. one that I've never tried. Is it possible
> under Windows to install Python from machine A onto
> a network drive and then run Python from machine B accessing
> that drive? In other words does the installer need to do any magic
> in the registry for Python to work or is it all just path setting
> and shortcuts?
>
> Can anyone confirm or otherwise the possibility?


i can try this under my networked drive tomorrow at school and if in fact
you can.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070103/b40ae736/attachment.htm 

From marshall.jiang at gmail.com  Wed Jan  3 20:39:55 2007
From: marshall.jiang at gmail.com (Shuai Jiang (Runiteking1))
Date: Wed, 3 Jan 2007 14:39:55 -0500
Subject: [Tutor] Question regarding parsing HTML with BeautifulSoup
Message-ID: <a678270c0701031139t499f040bj4fcd3bb8b94dbba1@mail.gmail.com>

Hello,

I'm working on a program that need to parse a financial document on the
internet
using BeautifulSoup. Because of the nature of the information, it is all
grouped
as a table. I needed to get 3 types of info and have succeeded quite well
using
BeautifulSoup, but encountered problems on the third one.

My question is that is there any easy way to parse an HTML tables column
easily using BeautifulSoup. I copied the table here and I need to extract
the EPS. The numbers are
every sixth one from the  <tr> tag ex 2.27, 1.86, 1.61...

Thanks!

Marshall
<table id="INCS" style="width:580px" class="f10y" cellspacing="0">
    <tr class="r1">
        <td align="left"
style="padding-left:5px;padding-right:5px;vertical-align:bottom">&nbsp;</td>
        <td align="right"
style="padding-left:5px;padding-right:5px;vertical-align:bottom">Sales</td>
        <td align="right"
style="padding-left:5px;padding-right:5px;vertical-align:bottom">EBIT</td>
        <td align="right"
style="padding-left:5px;padding-right:5px;vertical-align:bottom">Depreciation</td>
        <td align="right"
style="padding-left:5px;padding-right:5px;vertical-align:bottom">Total Net
Income</td>
        <td align="right"
style="padding-left:5px;padding-right:5px;vertical-align:bottom">EPS</td>
        <td align="right"
style="padding-left:5px;padding-right:5px;vertical-align:bottom">Tax Rate
(%)</td>
    </tr>

    <tr>
        <td align="left"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">02/06</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">30,848.0
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">1,721.0
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">456.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">1,140.0
</td>

        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">2.27</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">33.76</td>
    </tr>
    <tr>
        <td align="left"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">02/05</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">27,433.0
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">1,443.0
</td>

        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">459.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">934.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">1.86</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">35.27</td>
    </tr>
    <tr>
        <td align="left"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">02/04</td>

        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">24,548.0
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">1,296.0
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">385.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">800.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">1.61</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">38.27</td>

    </tr>
    <tr>
        <td align="left"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">03/03</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">20,943.0
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">1,014.0
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">310.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">622.0</td>

        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">1.27</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">38.66</td>
    </tr>
    <tr>
        <td align="left"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">03/02</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">17,711.0
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">926.0</td>

        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">245.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">570.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">1.18</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">38.44</td>
    </tr>
    <tr>
        <td align="left"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">03/01</td>

        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">15,189.0
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">649.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">165.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">401.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">0.84</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">38.21</td>

    </tr>
    <tr>
        <td align="left"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">02/00</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">12,494.02
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">562.57
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">109.54
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">347.07
</td>

        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">0.73</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">38.31</td>
    </tr>
    <tr>
        <td align="left"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">02/99</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">10,064.65
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">351.68
</td>

        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">73.63</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">216.28
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">0.46</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">38.5</td>
    </tr>
    <tr>
        <td align="left"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">02/98</td>

        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">8,337.76
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">133.4</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">71.58</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">81.94</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">0.2</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">38.58</td>

    </tr>
    <tr>
        <td align="left"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">03/97</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">7,770.68
</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">2.87</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">66.84</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">1.75</td>

        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">0.0</td>
        <td align="right"
style=";padding-left:5px;padding-right:5px;vertical-align:bottom">39.05</td>
    </tr>
</table>

-- 
I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as
equals.
    Sir Winston Churchill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070103/eae6be30/attachment-0001.html 

From rdm at rcblue.com  Wed Jan  3 20:51:11 2007
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 03 Jan 2007 11:51:11 -0800
Subject: [Tutor] Need help with rewriting script to use Decimal module
In-Reply-To: <459AA6EF.7050909@tds.net>
References: <7.0.1.0.2.20070102101030.067d7a90@rcblue.com>
	<459AA6EF.7050909@tds.net>
Message-ID: <7.0.1.0.2.20070103114221.066d23a0@rcblue.com>

At 10:39 AM 1/2/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>from decimal import Decimal as D
>>def bestFracForMinimumError(decimal, minimumError):
>>      denom = 0
>>      while True:
>>          denom += 1
>>          num = round(D(str(decimal)) * D(str(denom)))
>>          error = abs(str((str(D(num) / D(str(denom))) -
>This looks backwards        ^^^^^^^^^^

Thanks for catching that.


>Don't you need D(str(num)) ? Then converting it back to a str before 
>you call abs will not work.
>
>Your old approach of
>def D(num):
>   return Decimal(str(num))
>
>would probably make for more readable code and fewer errors.

Yes, I went back to it.

>I'm not sure this approach will work, though, if you are trying to 
>get higher precision, I would think you would have to do all the 
>calculations in Decimal, not going to floats for num. I admit I 
>haven't thought it through, though. I think you can use 
>Decimal.quantize() instead of round().

Thanks very much, Kent. You got me back on track.

Dick




From rdm at rcblue.com  Wed Jan  3 21:06:53 2007
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 03 Jan 2007 12:06:53 -0800
Subject: [Tutor] Need help with rewriting script to use Decimal  module
In-Reply-To: <Pine.LNX.4.44.0701021302460.16745-100000@violet.rahul.net>
References: <7.0.1.0.2.20070101034429.0353de58@rcblue.com>
	<Pine.LNX.4.44.0701021302460.16745-100000@violet.rahul.net>
Message-ID: <7.0.1.0.2.20070103120413.05aa4ae0@rcblue.com>

At 01:17 PM 1/2/2007, Terry Carroll wrote:
>On Mon, 1 Jan 2007, Dick Moores wrote:
>
> > bestFracForMinimumError() is only a small part of a program I wrote
> > long ago, called frac.py
>
>Dick, if your goal is to have a routine to get the fraction with the least
>possible error (as opposed to learing how to use Decimal), have a look at
>this recipe from the Python Cookbook:
>
>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317

Terry, that is truly ingenious. Is there an explication anywhere of 
exactly how it works?

Dick


From pyro9219 at gmail.com  Wed Jan  3 22:09:33 2007
From: pyro9219 at gmail.com (Chris Hengge)
Date: Wed, 3 Jan 2007 13:09:33 -0800
Subject: [Tutor] SPE - Stani's Python Editor ?
In-Reply-To: <57B026980605A64F9B23484C5659E32E4C712C@poccso.US.ad.atmel.com>
References: <57B026980605A64F9B23484C5659E32E4C712C@poccso.US.ad.atmel.com>
Message-ID: <c25107380701031309v16996980o8a3a3e17008579c8@mail.gmail.com>

Pydev Extensions are only about $40. Most of the plugin's are $50 or less if
not free... I'd personally much rather pay for the feature's I want, as I
want them, then be forced bloated software (Visual Studio) that will cost
hundreds to thousands of dollars, which will still require very expensive
add-ons, as well as forces you to live in the MS Languages (Which is fine if
you need that)

I guess I don't see a problem with helping out active projects, I normally
toss open source software that I use for any amount of time atleast one
"tip". In the end, its still a ton cheaper then Visual Studio or some of the
other options out there.

On 1/3/07, Mike Hansen <Mike.Hansen at atmel.com> wrote:
>
>
>
> > -----Original Message-----
> > From: tutor-bounces at python.org
> > [mailto:tutor-bounces at python.org] On Behalf Of Chris Hengge
> > Sent: Tuesday, January 02, 2007 4:57 PM
> > To: Dick Moores
> > Cc: tutor at python.org
> > Subject: Re: [Tutor] SPE - Stani's Python Editor ?
> >
> > I've recently started playing with Eclipse and the two PyDev
> > plugin's over the holidays. I'm seriously liking it... but my
> > likes are more closely related to Visual Studio as an editor,
> > so this is like the perfect environment for me..
> >
> > http://www.showmedo.com/videos/series?name=PyDevEclipseList
> >
> > This link shows you two video's on how pydev works, and how to setup.
> >
>
> I played with Eclipse a little bit. I got annoyed that the plugins would
> nickel and dime you to death. Pydev is free, but the additional features
> in Pydev Extensions cost $. I heard there was a plugin for vi emulation.
> Unfortunately, it was another plugin that you had to pay for.
>
> I decided to stick with VIM where the plugins are free. I recently
> starting using VIM's snippets.emu plugin. It emulates TextMate's
> snippets. TextMate is an editor for OS X that is getting a lot of
> attention. There are people working on TextMate-like editors for Windows
> and Linux.
>
> Mike
>
>
>
>
> -------------
>
>   NOTICE:  This e-mail transmission and any documents or files attached to
>   it contain information for the sole use of the above-identified
> individual or entity.
>
>   Its contents may be privileged, confidential, and exempt from disclosure
> under the law.
>   Any dissemination, distribution, or copying of this communication is
> strictly prohibited.
>
>   Please notify the sender immediately if you are not the intended
> recipient.
>
> FGNS
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070103/fd77f43e/attachment.htm 

From kmaheshw at science.uva.nl  Wed Jan  3 22:10:38 2007
From: kmaheshw at science.uva.nl (Ketan Maheshwari)
Date: Wed, 03 Jan 2007 22:10:38 +0100
Subject: [Tutor] how do i access object
In-Reply-To: <mailman.6649.1167853197.32030.tutor@python.org>
References: <mailman.6649.1167853197.32030.tutor@python.org>
Message-ID: <459C1BCE.3060608@science.uva.nl>

Hi All
I have this code from the web that I modified according to y 
requirements. It has a class called Circle. Then there are a few objects 
of this class created using a constructor. The constructor essentially 
creates the circles and the update mathod makes them move randomly. 
However, at each updation, I want to access each circle to know its 
coordinates. At the moment I am not able to do that. I am sure it should 
be easy to do. Could anyone help me please.

Thanks,
k.

Code follows:
******************code starts here***************************
from Tkinter import *
import time
import random
class Circle:
    def __init__(self, canvas, xy, ink, delta):
        self.canvas = canvas
        self.id = self.canvas.create_oval(
            -15, -15,
            15, 15,
            fill=ink
            )
       
        self.canvas.move(self.id, xy[0], xy[1])
        self.delta = delta
        self.start = self.move
     
    def __call__(self):
            return self.start # get things going
    def move(self):
        rand=random.randint(1,4)
       
        if rand==1:
            xy = self.canvas.coords(self.id)
            #print xy
            if xy[2] >= self.canvas.winfo_width():
                self.canvas.move(self.id,-self.delta,0)
            self.canvas.move(self.id,self.delta,0)
        elif rand==2:
            xy = self.canvas.coords(self.id)
            if xy[0] <= 0:
                self.canvas.move(self.id,self.delta,0)
            self.canvas.move(self.id,-self.delta,0)
        elif rand==3:
            xy = self.canvas.coords(self.id)
            if xy[1] <= 0:
                self.canvas.move(self.id,0,self.delta)
            self.canvas.move(self.id,0,-self.delta)
        else:
            xy = self.canvas.coords(self.id)
            if xy[3] >= self.canvas.winfo_height():
                self.canvas.move(self.id,0,-self.delta)
            self.canvas.move(self.id,0,self.delta)
        return self.move

       
   
root = Tk()
root.title("Circles")
root.resizable(0, 0)

frame = Frame(root, bd=5, relief=SUNKEN)
frame.pack()

canvas = Canvas(frame, width=200, height=200, bd=0, highlightthickness=0)
canvas.pack()

items = [
    Circle(canvas, (60, 70), "blue", 1),
    Circle(canvas, (100, 120), "green", 1),
    ]

root.update() # fix geometry

# loop over items

try:
    while 1:
        for i in range(len(items)):
            items[i] = items[i]()
            root.update_idletasks() # redraw
        root.update() # process events
        time.sleep(0.02)
except TclError:
    pass # to avoid errors when the window is closed

*************************************code ends 
here******************************

From carroll at tjc.com  Wed Jan  3 22:30:43 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 3 Jan 2007 13:30:43 -0800 (PST)
Subject: [Tutor] Need help with rewriting script to use Decimal  module
In-Reply-To: <7.0.1.0.2.20070103120413.05aa4ae0@rcblue.com>
Message-ID: <Pine.LNX.4.44.0701031255350.15662-100000@violet.rahul.net>

On Wed, 3 Jan 2007, Dick Moores wrote:

> At 01:17 PM 1/2/2007, Terry Carroll wrote:
>
> >  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317
> 
> Terry, that is truly ingenious. Is there an explication anywhere of 
> exactly how it works?

There is in the printed copy of the Python Cookbook.  I happened to have 
read it last week, which is the only reason I knew about it.  I don't have 
the book handy, but here's what I remember of it.

It's based on the concept of the Farey sequence of fractions.  I may 
explain it imperfectly, but it's basically the sequence of fractions with 
integer denominators and numerators, each reduced to the lowest common 
denominator, and then arranged in numerically ascending order.  The 
sequence has an order N, where N is the highest integer used in the 
denominator.

It's easier to show an example.  Here's the Farey sequence for order 4; 
I'll include a decimal approximation to show the basis for the ordering:

 0/1,   1/4,   1/3,   1/2,   2/3,   3/4,   1/1

 0.0    0.25   0.33  0.50    0.67   0.75   1.00


It's been observed (by a guy named Farey, hence the name) that, for any
subsequence of three consecutive fractions in the sequence, if expressed
as A/B, C/D, E/F; then C/D = (A+E)/(B+F).

For example, in the above seqence, take the three-fraction subsequence 
{1/2, 2/3, 3/4}.  In this,  A=1, B=2, C=2, D=3, E=3, F=4, so:

  (A+E)/(B+F) = (1+3)/(2+4) = 4/6 = 2/3 = C/D.

The inner fraction (C/D) is called the mediant.

If I understand the Python algorithm correctly, it takes advantage of this
process by essentially constructing a Farey sequence of order 1 (which is
essentially {0/1, 1/1}, or {0, 1}), and then calculating the mediant
between those two points, thereby constructing a subsequence of order 2;
then another mediant between that mediant and one of its neighbors (which
neighbor is chose by considering whether the decimal fraction you seek to
approximate is greater than or less than the mediant), and then doing this
continuously, calculating subsquences of orders 3, 4, etc, until it
reaches the desired precision.

I just checked, and (big surprise) Wikipedia has an article on the Farey
sequence:

http://en.wikipedia.org/wiki/Farey_number

There's apparently more to it than I described above.  They give the same 
formula I use, but where I use A, B, C, D, E, F, they use A, B, P, Q, C, 
D, respectively.


From dyoo at hkn.eecs.berkeley.edu  Wed Jan  3 22:41:12 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 3 Jan 2007 13:41:12 -0800 (PST)
Subject: [Tutor] Need help with rewriting script to use Decimal  module
In-Reply-To: <7.0.1.0.2.20070103120413.05aa4ae0@rcblue.com>
References: <7.0.1.0.2.20070101034429.0353de58@rcblue.com>
	<Pine.LNX.4.44.0701021302460.16745-100000@violet.rahul.net>
	<7.0.1.0.2.20070103120413.05aa4ae0@rcblue.com>
Message-ID: <Pine.LNX.4.64.0701031237520.22454@hkn.eecs.berkeley.edu>



>> Dick, if your goal is to have a routine to get the fraction with the least
>> possible error (as opposed to learing how to use Decimal), have a look at
>> this recipe from the Python Cookbook:
>>
>>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317
>
> Terry, that is truly ingenious. Is there an explication anywhere of
> exactly how it works?


Hi Dick,

On a first glance, it looks like it's doing a binary search on the Farey 
series on some order.  (Actually, it's not, but we'll get to that later in 
this post.) Farey sequences have an entry on Wikipedia:

     http://en.wikipedia.org/wiki/Farey_number

Look at the terms of F_8, for example.  If you take two points with some 
other point between them, say 1/5 and 2/7, notice that:

   1     3       2
   -  <  --  <   -
   5     12      7

If we just do the funny thing by adding the numerators and denominators 
--- by taking the "mediant" --- we end up with another term in the Farey 
sequence.  This is very cute.


Wait.  Actually, what the algorithm is doing doesn't appear to be 
searching through a particular Farey sequence of order n.  Instead, what 
it's doing is much simpler: it appears to be just taking advanatage of the 
in-betweenness property of "mediants".

     http://en.wikipedia.org/wiki/Mediant_%28mathematics%29

Oh well, that still works.  The algorithm seems to be misnamed, though: I 
think it should really be described as "inexact to rational via mediant 
approximation."


The trick that the algorithm is really a binary-search, using the 
definition of "mediant" to find "midpoints".  Whenever we see something 
like:

####################################################################
while we haven't found the answer:
     We know that the answer's somewhere between the lower and upper
     bounds.  (precondition)

     midpoint = some calculation combining the lower and upper bounds

     if the midpoint is too big:
         move the upper bound
     elif the midpoint is too small:
         move the lower bound
     else
         we've found the answer

     At the end of this, we guarantee our answer's still between
     the lower and upper bounds.  (postcondition)
####################################################################

then we should suspect a binary search.  In the case of the algorithm in 
the Cookbook, we can see that it follows this structure very closely.

Concretely, when they say:

     if v * mediant[1] > mediant[0]: ...

we can do simple equational reasoning to see that this is really 
saying:

     if v > (mediant[0] / mediant[1]): ...

aka: "if the value we're looking for is bigger than the mediant, move the 
lower bound up."  The mediant is being represented by a 2-tuple 
(numerator, denominator), so with that, you should be able to read the 
case analysis off more easily.


Best of wishes!

From lavendula6654 at yahoo.com  Thu Jan  4 01:07:52 2007
From: lavendula6654 at yahoo.com (Elaine)
Date: Wed, 3 Jan 2007 16:07:52 -0800 (PST)
Subject: [Tutor] Python class at Foothill College
Message-ID: <377578.5567.qm@web31714.mail.mud.yahoo.com>

If you would like to learn Python, Foothill College is
offering a course starting Wed. evening, 10 January,
at the Middlefield campus on the corner of San Antonio
and Middlefield Road in south Palo Alto. The course is
designed for students who are already familiar with
some type of programming. Here is the course
description:

CIS 68K  "INTRODUCTION TO PYTHON PROGRAMMING"  5 Units
This course will introduce students to the Python
language and environment. Python is a portable,
interpreted, object-oriented programming language that
is often compared to Perl, Java, Scheme and Tcl. The
language has an elegant syntax, dynamic typing, and a
small number of powerful, high-level data types. It
also has modules, classes, and exceptions. Meets
Wednesday evenings, 6:00 - 9:40, 10 January - 28
March.

If you would like to sign up for the class, please
register beforehand by going to:
http://www.foothill.fhda.edu/reg/index.php

If you have questions, you can contact the instructor
at:
haightElaine at foothill.edu


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From alan.gauld at btinternet.com  Thu Jan  4 02:41:45 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 4 Jan 2007 01:41:45 -0000
Subject: [Tutor] how do i access object
References: <mailman.6649.1167853197.32030.tutor@python.org>
	<459C1BCE.3060608@science.uva.nl>
Message-ID: <enhlt9$ec8$1@sea.gmane.org>


"Ketan Maheshwari" <kmaheshw at science.uva.nl> wrote

> of this class created using a constructor. The constructor 
> essentially
> creates the circles and the update mathod makes them move randomly.
> However, at each updation, I want to access each circle to know its
> coordinates. At the moment I am not able to do that.

The circles are stored in a list called items.

You can iterate over the items printing out their centres:

for circ in items:
    print circ.getCentres()

Where getCentres is a mrethod you will need to write
and add to Circle! :-)

> class Circle:
>    def __init__(self, canvas, xy, ink, delta):
>    def __call__(self):
>    def move(self):
>
> root = Tk()
...
> canvas = Canvas(frame, width=200, height=200, bd=0, 
> highlightthickness=0)
> canvas.pack()
>
> items = [
>    Circle(canvas, (60, 70), "blue", 1),
>    Circle(canvas, (100, 120), "green", 1),
>    ]
>
...

>        for i in range(len(items)):
>            items[i] = items[i]()

As is done here except it would be prettier done as

for i in items:

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From kent37 at tds.net  Thu Jan  4 02:49:56 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 03 Jan 2007 20:49:56 -0500
Subject: [Tutor] how do i access object
In-Reply-To: <459C1BCE.3060608@science.uva.nl>
References: <mailman.6649.1167853197.32030.tutor@python.org>
	<459C1BCE.3060608@science.uva.nl>
Message-ID: <459C5D44.8090809@tds.net>

Ketan Maheshwari wrote:
> Hi All
> I have this code from the web that I modified according to y 
> requirements. It has a class called Circle. Then there are a few objects 
> of this class created using a constructor. The constructor essentially 
> creates the circles and the update mathod makes them move randomly. 
> However, at each updation, I want to access each circle to know its 
> coordinates. At the moment I am not able to do that. I am sure it should 
> be easy to do. Could anyone help me please.

The line
   xy = self.canvas.coords(self.id)
reads the bounding box of the circle. The returned value is a list 
containing the coordinates of the bounding box of the circle (x0, y0, 
x1, y1) - in other words the coordinates of the left, top, right and 
bottom of the circle.

This might help a bit:
http://infohost.nmt.edu/tcc/help/pubs/tkinter/canvas-concepts.html

Kent

> 
> Thanks,
> k.
> 
> Code follows:
> ******************code starts here***************************
> from Tkinter import *
> import time
> import random
> class Circle:
>     def __init__(self, canvas, xy, ink, delta):
>         self.canvas = canvas
>         self.id = self.canvas.create_oval(
>             -15, -15,
>             15, 15,
>             fill=ink
>             )
>        
>         self.canvas.move(self.id, xy[0], xy[1])
>         self.delta = delta
>         self.start = self.move
>      
>     def __call__(self):
>             return self.start # get things going
>     def move(self):
>         rand=random.randint(1,4)
>        
>         if rand==1:
>             xy = self.canvas.coords(self.id)
>             #print xy
>             if xy[2] >= self.canvas.winfo_width():
>                 self.canvas.move(self.id,-self.delta,0)
>             self.canvas.move(self.id,self.delta,0)
>         elif rand==2:
>             xy = self.canvas.coords(self.id)
>             if xy[0] <= 0:
>                 self.canvas.move(self.id,self.delta,0)
>             self.canvas.move(self.id,-self.delta,0)
>         elif rand==3:
>             xy = self.canvas.coords(self.id)
>             if xy[1] <= 0:
>                 self.canvas.move(self.id,0,self.delta)
>             self.canvas.move(self.id,0,-self.delta)
>         else:
>             xy = self.canvas.coords(self.id)
>             if xy[3] >= self.canvas.winfo_height():
>                 self.canvas.move(self.id,0,-self.delta)
>             self.canvas.move(self.id,0,self.delta)
>         return self.move
> 
>        
>    
> root = Tk()
> root.title("Circles")
> root.resizable(0, 0)
> 
> frame = Frame(root, bd=5, relief=SUNKEN)
> frame.pack()
> 
> canvas = Canvas(frame, width=200, height=200, bd=0, highlightthickness=0)
> canvas.pack()
> 
> items = [
>     Circle(canvas, (60, 70), "blue", 1),
>     Circle(canvas, (100, 120), "green", 1),
>     ]
> 
> root.update() # fix geometry
> 
> # loop over items
> 
> try:
>     while 1:
>         for i in range(len(items)):
>             items[i] = items[i]()
>             root.update_idletasks() # redraw
>         root.update() # process events
>         time.sleep(0.02)
> except TclError:
>     pass # to avoid errors when the window is closed
> 
> *************************************code ends 
> here******************************
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From kent37 at tds.net  Thu Jan  4 03:14:15 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 03 Jan 2007 21:14:15 -0500
Subject: [Tutor] Question regarding parsing HTML with BeautifulSoup
In-Reply-To: <a678270c0701031139t499f040bj4fcd3bb8b94dbba1@mail.gmail.com>
References: <a678270c0701031139t499f040bj4fcd3bb8b94dbba1@mail.gmail.com>
Message-ID: <459C62F7.2090400@tds.net>

Shuai Jiang (Runiteking1) wrote:
> Hello,
> 
> I'm working on a program that need to parse a financial document on the 
> internet
> using BeautifulSoup. Because of the nature of the information, it is all 
> grouped
> as a table. I needed to get 3 types of info and have succeeded quite 
> well using
> BeautifulSoup, but encountered problems on the third one.
> 
> My question is that is there any easy way to parse an HTML tables column
> easily using BeautifulSoup. I copied the table here and I need to 
> extract the EPS. The numbers are
> every sixth one from the  <tr> tag ex 2.27, 1.86, 1.61...

Here is one way, found with a little experimenting at the command prompt:

In [1]: data = '''<table id="INCS" style="width:580px" class="f10y" 
cellspacing="0">
<snip the rest of your data>
    ...: </table>'''
In [3]: from BeautifulSoup import BeautifulSoup as BS

In [4]: soup=BS(data)

In [11]: for tr in soup.table.findAll('tr'):
    ....:     print tr.contents[11].string
    ....:
    ....:
EPS
2.27
  1.86
1.61
  1.27
1.18
  0.84
0.73
  0.46
0.2
  0.0

Kent



From cappy2112 at gmail.com  Thu Jan  4 03:57:12 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Wed, 3 Jan 2007 18:57:12 -0800
Subject: [Tutor] Embedding strings in a python script
Message-ID: <8249c4ac0701031857i5ee219c9n8d89ca00e2b5c88a@mail.gmail.com>

I have a number of text files which need to be checked into CVS.
Each file needs a special text header/footer in order that CVS can track
changes and version numbers.

Python to the rescue.

I've written a small python program which will write the header/footer to
all files in the current directory.

In order to do this, I need to add this string in my python program.

cvs_header='''
#######################################
#
# $Header:$
#
# $Revision:$
# $Author:$
# $Date:$
#
'''

It works just fine.


However, the program which I wrote also needs to be kept under version
control.
When I make changes to that program, I noticed that the header above gets
modified by cvs, because it contains key variables which are recognized by
cvs.

This is unacceptable.

So I took this string out of my program, wrote it to a pickle file, and now
the pickle file is read at runtime, and the program will write the empty
header to the target files.
I can check the pickle files into cvs as binary files, and the header
strings will not be modified.

I now have 3 pickle files I need to distribute with the program, which is a
minor nuisance. Even using py2exe on Windows, these 3 files cannot be
embedded within the exe itself.

What I'd like to know, is there a way I can embed/endcode the cvs string
above in the python script, so that when that script is modified and checked
into cvs, that the cvs header string above will not be modified by cvs?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070103/5300f306/attachment.htm 

From john at fouhy.net  Thu Jan  4 04:13:51 2007
From: john at fouhy.net (John Fouhy)
Date: Thu, 4 Jan 2007 16:13:51 +1300
Subject: [Tutor] Embedding strings in a python script
In-Reply-To: <8249c4ac0701031857i5ee219c9n8d89ca00e2b5c88a@mail.gmail.com>
References: <8249c4ac0701031857i5ee219c9n8d89ca00e2b5c88a@mail.gmail.com>
Message-ID: <5e58f2e40701031913v58717f34tf03ba7701a4071a5@mail.gmail.com>

On 04/01/07, Tony Cappellini <cappy2112 at gmail.com> wrote:
> What I'd like to know, is there a way I can embed/endcode the cvs string
> above in the python script, so that when that script is modified and checked
> into cvs, that the cvs header string above will not be modified by cvs?

What about this:

cvs_header='''
#######################################
#
# @Header:@
#
# @Revision:@
# @Author:@
# @Date:@
#
'''.replace('@', '$')

?

-- 
John.

From nephish at gmail.com  Thu Jan  4 05:16:40 2007
From: nephish at gmail.com (shawn bright)
Date: Wed, 3 Jan 2007 22:16:40 -0600
Subject: [Tutor] how to know if a file exists
Message-ID: <384c93600701032016o4186b9d0hcbc29bd76c54b8fc@mail.gmail.com>

hello there,
i am writing an app for linux. what command would be easiest to test and see
if a certain file exist ?
i was going to do something like this
try:
    file = open('/path/to/file', 'rb')
    return True
except:
    return False

but i thought that there would be an easier way.
thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070103/f434460b/attachment.html 

From rabidpoobear at gmail.com  Thu Jan  4 05:19:24 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 03 Jan 2007 22:19:24 -0600
Subject: [Tutor] how to know if a file exists
In-Reply-To: <384c93600701032016o4186b9d0hcbc29bd76c54b8fc@mail.gmail.com>
References: <384c93600701032016o4186b9d0hcbc29bd76c54b8fc@mail.gmail.com>
Message-ID: <459C804C.8030905@gmail.com>

shawn bright wrote:
> hello there,
> i am writing an app for linux. what command would be easiest to test 
> and see if a certain file exist ?
> i was going to do something like this
> try:
>     file = open('/path/to/file', 'rb')
>     return True
> except:
>     return False
You should except IOError here, just to be clear and such.
>
> but i thought that there would be an easier way.
The os module has some function for checking if files exist, I think.
Or you could do
if targetfile not in os.listdir(directory): return False
else: return True

But your original solution is okay.
HTH,
-Luke

From andre.roberge at gmail.com  Thu Jan  4 05:26:57 2007
From: andre.roberge at gmail.com (Andre Roberge)
Date: Thu, 4 Jan 2007 00:26:57 -0400
Subject: [Tutor] how to know if a file exists
In-Reply-To: <459C804C.8030905@gmail.com>
References: <384c93600701032016o4186b9d0hcbc29bd76c54b8fc@mail.gmail.com>
	<459C804C.8030905@gmail.com>
Message-ID: <7528bcdd0701032026r4c073684n434096a9fec1cb27@mail.gmail.com>

On 1/4/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
>
> shawn bright wrote:
> > hello there,
> > i am writing an app for linux. what command would be easiest to test
> > and see if a certain file exist ?
> > i was going to do something like this
> > try:
> >     file = open('/path/to/file', 'rb')
> >     return True
> > except:
> >     return False
> You should except IOError here, just to be clear and such.
> >
> > but i thought that there would be an easier way.
> The os module has some function for checking if files exist, I think.


Yes, check out access():
http://docs.python.org/lib/os-file-dir.html

 Andr?

Or you could do
> if targetfile not in os.listdir(directory): return False
> else: return True
>
> But your original solution is okay.
> HTH,
> -Luke
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/6ebb083c/attachment.htm 

From nephish at gmail.com  Thu Jan  4 05:29:39 2007
From: nephish at gmail.com (shawn bright)
Date: Wed, 3 Jan 2007 22:29:39 -0600
Subject: [Tutor] how to know if a file exists
In-Reply-To: <7528bcdd0701032026r4c073684n434096a9fec1cb27@mail.gmail.com>
References: <384c93600701032016o4186b9d0hcbc29bd76c54b8fc@mail.gmail.com>
	<459C804C.8030905@gmail.com>
	<7528bcdd0701032026r4c073684n434096a9fec1cb27@mail.gmail.com>
Message-ID: <384c93600701032029r4b25b254wd5191b87ff79eeda@mail.gmail.com>

thanks, luke, Andre.
appreciate it a lot

shawn

On 1/3/07, Andre Roberge <andre.roberge at gmail.com> wrote:
>
>
>
> On 1/4/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> >
> > shawn bright wrote:
> > > hello there,
> > > i am writing an app for linux. what command would be easiest to test
> > > and see if a certain file exist ?
> > > i was going to do something like this
> > > try:
> > >     file = open('/path/to/file', 'rb')
> > >     return True
> > > except:
> > >     return False
> > You should except IOError here, just to be clear and such.
> > >
> > > but i thought that there would be an easier way.
> > The os module has some function for checking if files exist, I think.
>
>
> Yes, check out access():
> http://docs.python.org/lib/os-file-dir.html
>
>  Andr?
>
> Or you could do
> > if targetfile not in os.listdir(directory): return False
> > else: return True
> >
> > But your original solution is okay.
> > HTH,
> > -Luke
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070103/4be0f1e5/attachment.html 

From dyoo at hkn.eecs.berkeley.edu  Thu Jan  4 06:20:45 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 3 Jan 2007 21:20:45 -0800 (PST)
Subject: [Tutor] how to know if a file exists
In-Reply-To: <7528bcdd0701032026r4c073684n434096a9fec1cb27@mail.gmail.com>
References: <384c93600701032016o4186b9d0hcbc29bd76c54b8fc@mail.gmail.com>
	<459C804C.8030905@gmail.com>
	<7528bcdd0701032026r4c073684n434096a9fec1cb27@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0701032117310.16914@hkn.eecs.berkeley.edu>



On Thu, 4 Jan 2007, Andre Roberge wrote:

>> > i am writing an app for linux. what command would be easiest to test
>> > and see if a certain file exist ?
>> > i was going to do something like this
>> > try:
>> >     file = open('/path/to/file', 'rb')
>> >     return True
>> > except:
>> >     return False
>> You should except IOError here, just to be clear and such.
>> >
>> > but i thought that there would be an easier way.
>> The os module has some function for checking if files exist, I think.
>
> Yes, check out access():
> http://docs.python.org/lib/os-file-dir.html

Hi Andrey,

os.path.exists() may also be useful here:

     http://www.python.org/doc/lib/module-os.path.html#l2h-2163

From janos.juhasz at VELUX.com  Thu Jan  4 07:19:33 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Thu, 4 Jan 2007 07:19:33 +0100
Subject: [Tutor] Find and test a device by  MAC address
In-Reply-To: <mailman.6699.1167884818.32030.tutor@python.org>
Message-ID: <OFA2BDDEDF.70A115E5-ONC1257259.00222277-C1257259.0022BFA3@velux.com>

Dear All,

I got a device that uses DHCP on my network, I know just the MAC address 
of it.
Is it possible to find out (not from the DHCP server), what IP address is 
given for it ?

I just mean something like
ping_by_MAC 00-19-E7-5C-D4-28



Yours sincerely, 
______________________________
Janos Juhasz 


From cappy2112 at gmail.com  Thu Jan  4 07:43:11 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Wed, 3 Jan 2007 22:43:11 -0800
Subject: [Tutor] Embedding strings in a python script
Message-ID: <8249c4ac0701032243h6b6eb693iaabafa1dd60de5cb@mail.gmail.com>

Message: 5
Date: Thu, 4 Jan 2007 16:13:51 +1300
From: "John Fouhy" <john at fouhy.net>
Subject: Re: [Tutor] Embedding strings in a python script
To: tutor-python <tutor at python.org>
Message-ID:
       <5e58f2e40701031913v58717f34tf03ba7701a4071a5 at mail.gmail.com>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

On 04/01/07, Tony Cappellini <cappy2112 at gmail.com> wrote:
> What I'd like to know, is there a way I can embed/endcode the cvs string
> above in the python script, so that when that script is modified and
checked
> into cvs, that the cvs header string above will not be modified by cvs?

What about this:

cvs_header='''
#######################################
#
# @Header:@

I will give that a try. I don't know if cvs keys off of the word, the $, or
the word surround by any two symbols.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070103/4e0cd797/attachment.html 

From rdm at rcblue.com  Thu Jan  4 08:50:13 2007
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 03 Jan 2007 23:50:13 -0800
Subject: [Tutor] Need help with rewriting script to use Decimal  module
In-Reply-To: <Pine.LNX.4.44.0701021302460.16745-100000@violet.rahul.net>
References: <7.0.1.0.2.20070101034429.0353de58@rcblue.com>
	<Pine.LNX.4.44.0701021302460.16745-100000@violet.rahul.net>
Message-ID: <7.0.1.0.2.20070103234257.06dcc0c0@rcblue.com>

At 01:17 PM 1/2/2007, Terry Carroll wrote:
>On Mon, 1 Jan 2007, Dick Moores wrote:
>
> > bestFracForMinimumError() is only a small part of a program I wrote
> > long ago, called frac.py
>
>Dick, if your goal is to have a routine to get the fraction with the least
>possible error (as opposed to learing how to use Decimal), have a look at
>this recipe from the Python Cookbook:
>
>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317

Terry, I just noticed that farey(0.36, 10) returns (1, 3), a pretty 
big miss, IMO. The correct fraction with smallest error and maximum 
denominator of 10 is 3/8, which I'm proud to say my klunky frac.py 
(<http://www.rcblue.com/Python/fracForWeb.py>) produces.

Be that as it may, farey() is an amazing program. I appreciate the 
fast replies from you and Danny to my plea for explication. I'm still 
working through them.

Dick






From lumbricus at gmx.net  Thu Jan  4 09:23:19 2007
From: lumbricus at gmx.net (lumbricus at gmx.net)
Date: Thu, 04 Jan 2007 09:23:19 +0100
Subject: [Tutor] Find and test a device by  MAC address
Message-ID: <20070104082319.260950@gmx.net>

Quick and dirty:
As root:
>>> from scapy import *
>>> arping("192.168.0.1/24") # or whatever fits to your network
and then filter the answers; or build your own arp packets with ARP().




-- 
Freedom, Freedom, Freedom, Oi!
   -- Zoidberg


Der GMX SmartSurfer hilft bis zu 70% Ihrer Onlinekosten zu sparen! 
Ideal f?r Modem und ISDN: http://www.gmx.net/de/go/smartsurfer

From vikramumanathshenoy at gmail.com  Thu Jan  4 10:15:25 2007
From: vikramumanathshenoy at gmail.com (Vikram Shenoy)
Date: Thu, 4 Jan 2007 14:45:25 +0530
Subject: [Tutor] how to know if a file exists
Message-ID: <1ac2c0030701040115w2e372badt455755e6ee3c56d2@mail.gmail.com>

Hi,

import os

if os.path.exists('/path/to/file'):
     # File exists
else:
     # File doesn't exist

It works for files as well as directories.

Regards,
Vikram U Shenoy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/ae5963c9/attachment.htm 

From kent37 at tds.net  Thu Jan  4 12:03:34 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 04 Jan 2007 06:03:34 -0500
Subject: [Tutor] Embedding strings in a python script
In-Reply-To: <8249c4ac0701031857i5ee219c9n8d89ca00e2b5c88a@mail.gmail.com>
References: <8249c4ac0701031857i5ee219c9n8d89ca00e2b5c88a@mail.gmail.com>
Message-ID: <459CDF06.1070600@tds.net>

Tony Cappellini wrote:
> What I'd like to know, is there a way I can embed/endcode the cvs string 
> above in the python script, so that when that script is modified and 
> checked into cvs, that the cvs header string above will not be modified 
> by cvs?

Try using \x24 instead of $:

cvs_header='''
#######################################
#
# \x24Header:\x24
#
# \x24Revision:\x24
# \x24Author:\x24
# \x24Date:\x24
#

Kent


From kent37 at tds.net  Thu Jan  4 12:05:27 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 04 Jan 2007 06:05:27 -0500
Subject: [Tutor] how to know if a file exists
In-Reply-To: <384c93600701032016o4186b9d0hcbc29bd76c54b8fc@mail.gmail.com>
References: <384c93600701032016o4186b9d0hcbc29bd76c54b8fc@mail.gmail.com>
Message-ID: <459CDF77.5080707@tds.net>

shawn bright wrote:
> hello there,
> i am writing an app for linux. what command would be easiest to test and 
> see if a certain file exist ?

os.path.exists() or os.path.isfile()

Kent


From deep_ans at yahoo.com  Thu Jan  4 12:22:52 2007
From: deep_ans at yahoo.com (deepak shingan)
Date: Thu, 4 Jan 2007 03:22:52 -0800 (PST)
Subject: [Tutor] Any Good book for python
Message-ID: <20070104112252.90399.qmail@web51702.mail.yahoo.com>

Hi Folks, 

I am new in Python area and want to know Python concepts with more deatils. 
Please suggest some good books on python.


Thanks in Advance
-Deepak

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/e785883c/attachment.html 

From python at kapitalisten.no  Thu Jan  4 12:58:33 2007
From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=)
Date: Thu, 4 Jan 2007 12:58:33 +0100 (CET)
Subject: [Tutor] Patches
Message-ID: <18923.193.71.38.142.1167911913.squirrel@mail.sporck.net>

Hello.

I need to access SMTP with SSL and found this patch:
https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1567274&group_id=5470

But, I cannot find anything with Google or in the Python documentation
about how to apply a patch.

Ok, one slight modification. I did find something:

5.2   How do I apply a patch?

For the general case, to apply a patch go to the directory that the patch
was created from (usually /dist/src/) and run:

patch -p0 < name_of_the_patch.diff

The -p option specifies the number of directory separators ("/" in the
case of UNIX) to remove from the paths of the files in the patch. -p0
leaves the paths alone.

from http://www.python.org/dev/faq/#how-do-i-apply-a-patch

But, that didn't tell me anything. I am using Windows, and tried both to
enter that command in the CMD-window, as well as in the Python-IDLE. No
avail.

Is patch a program I have to download somewhere? Or can only patches be
used in Linux?

Thanks in advance.


-- 
This email has been scanned for viruses & spam by Domenebutikken - www.domenebutikken.no
Denne e-posten er sjekket for virus & spam av Domenebutikken - www.domenebutikken.no


From arunkumarpg at gmail.com  Thu Jan  4 13:46:37 2007
From: arunkumarpg at gmail.com (Arun Kumar PG)
Date: Thu, 4 Jan 2007 18:16:37 +0530
Subject: [Tutor] Any Good book for python
In-Reply-To: <20070104112252.90399.qmail@web51702.mail.yahoo.com>
References: <20070104112252.90399.qmail@web51702.mail.yahoo.com>
Message-ID: <3cffff920701040446tbe0258di161a19b8f38d154e@mail.gmail.com>

"Python in a nutshell" is a good one. Also Python docs are the all time
favorite.

On 1/4/07, deepak shingan <deep_ans at yahoo.com> wrote:
>
> Hi Folks,
>
> I am new in Python area and want to know Python concepts with more
> deatils.
> Please suggest some good books on python.
>
>
> Thanks in Advance
> -Deepak
>
>
>   **
>
>
>
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam? Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/cf5b3afa/attachment.htm 

From hiran.v at gmail.com  Thu Jan  4 13:55:21 2007
From: hiran.v at gmail.com (Hiran Venugopalan)
Date: Thu, 4 Jan 2007 05:55:21 -0700
Subject: [Tutor] Any Good book for python
In-Reply-To: <3cffff920701040446tbe0258di161a19b8f38d154e@mail.gmail.com>
References: <20070104112252.90399.qmail@web51702.mail.yahoo.com>
	<3cffff920701040446tbe0258di161a19b8f38d154e@mail.gmail.com>
Message-ID: <1b6e7c770701040455w1e24b1a5y426ce2cff4533b7f@mail.gmail.com>

"Byte of python" by Swaroop [swaroopch.info]  is a simple book for
starters,but never a alltime help book.If you are just a starter like me,you
can learn the ideas on python on looking to that and which will surely help
you to learn python in deep.
Its there at http://swaroopch.info/text/Byte_of_Python:Main_Page

Learning python is a standard "good"  book.Link
http://www.oreilly.com/catalog/lpython2/




-- 
Believing in freedom ....

????? ???????????? | Hiran Venugopalan
http://hiran.movingrepublic.org
# 09846951870
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/090d50c1/attachment.html 

From kent37 at tds.net  Thu Jan  4 14:18:14 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 04 Jan 2007 08:18:14 -0500
Subject: [Tutor] Patches
In-Reply-To: <18923.193.71.38.142.1167911913.squirrel@mail.sporck.net>
References: <18923.193.71.38.142.1167911913.squirrel@mail.sporck.net>
Message-ID: <459CFE96.8020805@tds.net>

?yvind wrote:
> Hello.
> 
> I need to access SMTP with SSL and found this patch:
> https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1567274&group_id=5470
> 
> But, I cannot find anything with Google or in the Python documentation
> about how to apply a patch.
> 
> Is patch a program I have to download somewhere? Or can only patches be
> used in Linux?

There is a patch program for windows here:
http://gnuwin32.sourceforge.net/packages/patch.htm

The patch you reference modifies two files, a .tex file and a .py file. 
The .tex file is the source for the module documentation, you probably 
won't have that, so you may have to edit it out of the patch file.

Kent


From kmaheshw at science.uva.nl  Thu Jan  4 14:51:09 2007
From: kmaheshw at science.uva.nl (Ketan Maheshwari)
Date: Thu, 04 Jan 2007 14:51:09 +0100
Subject: [Tutor] how do i access object
In-Reply-To: <459C5D44.8090809@tds.net>
References: <mailman.6649.1167853197.32030.tutor@python.org>
	<459C1BCE.3060608@science.uva.nl> <459C5D44.8090809@tds.net>
Message-ID: <459D064D.5050200@science.uva.nl>

Hi
As suggested by Alan, I wrote a method getcenter as follows
***
def getcenter(self):
        xy=self.canvas.coords(self.id)
        xcenter=(xy[2]-xy[0])/2
        ycenter=(xy[3]-xy[1])/2
        return xcenter, ycenter
***
However, when I call this method from the instance of Circle class I get 
error:
call ...
print items[1].getcenter()
error ...
AttributeError: 'function' object has no attribute 'getcenter'

What is happening here?

Thanks
ketan.

PS> full code follows ...

from Tkinter import *
import time
import random
class Circle:

    def __init__(self, canvas, xy, ink, delta):
        self.canvas = canvas
        self.id = self.canvas.create_oval(
            -15, -15,
            15, 15,
            fill=ink
            )
       
        self.canvas.move(self.id, xy[0], xy[1])
        self.delta = delta
        self.start = self.move
       
       
    def __call__(self):
            return self.start # get things going
    def move(self):
        rand=random.randint(1,4)
       
        if rand==1:
            xy = self.canvas.coords(self.id)
            #print xy
            if xy[2] >= self.canvas.winfo_width():
                self.canvas.move(self.id,-self.delta,0)
            self.canvas.move(self.id,self.delta,0)
        elif rand==2:
            xy = self.canvas.coords(self.id)
            if xy[0] <= 0:
                self.canvas.move(self.id,self.delta,0)
            self.canvas.move(self.id,-self.delta,0)
        elif rand==3:
            xy = self.canvas.coords(self.id)
            if xy[1] <= 0:
                self.canvas.move(self.id,0,self.delta)
            self.canvas.move(self.id,0,-self.delta)
        else:
            xy = self.canvas.coords(self.id)
            if xy[3] >= self.canvas.winfo_height():
                self.canvas.move(self.id,0,-self.delta)
            self.canvas.move(self.id,0,self.delta)
        return self.move
   
    def getcenter(self):
        xy=self.canvas.coords(self.id)
        xcenter=(xy[2]-xy[0])/2
        ycenter=(xy[3]-xy[1])/2
        return xcenter, ycenter
       
   
root = Tk()
root.title("Circles")
root.resizable(0, 0)

frame = Frame(root, bd=5, relief=SUNKEN)
frame.pack()

canvas = Canvas(frame, width=200, height=200, bd=0, highlightthickness=0)
canvas.pack()

items = [
    Circle(canvas, (60, 70), "blue", 1),
    Circle(canvas, (100, 120), "green", 1),
    ]

root.update() # fix geometry

# loop over items

try:
    while 1:
        for i in range(len(items)):
            items[i] = items[i]()
            root.update_idletasks() # redraw
        root.update() # process events
        print items[1].getcenter()
        time.sleep(0.02)
except TclError:
    pass # to avoid errors when the window is closed


From stvsmth at gmail.com  Thu Jan  4 15:17:59 2007
From: stvsmth at gmail.com (stv)
Date: Thu, 4 Jan 2007 07:17:59 -0700
Subject: [Tutor] Any Good book for python
In-Reply-To: <20070104112252.90399.qmail@web51702.mail.yahoo.com>
References: <20070104112252.90399.qmail@web51702.mail.yahoo.com>
Message-ID: <9493d0340701040617s448fa20cibd8acc538a84a681@mail.gmail.com>

> I am new in Python area and want to know Python concepts with more deatils.
> Please suggest some good books on python.

Beginning Python, by Hetland is excellent for almost any level (I
think someone who has really mastered one language, and is currently
working as a programmer, can simply read Guido's tutorial & use the
online docs).

Hetland doesn't talk down to beginner, non-programmer types, nor does
he hide hard stuff; he makes it accessible. It also talks about how to
program in general, how to attack problems, test, have fun.It's well
indexed and organized, so it's a good reference for the noob, but as
yo gain experience with Python you will migrate to the on-line docs. I
have to say, however, that in the first weeks I used the book as a
reference more than I used the on-line docs.

Diving into Python, by Pilgrim has a lot of respect. It's available on-line
  http://diveintopython.org/index.html

It is a Python book for "experienced programmers." Which, I assume,
means experienced non-Python programmers.

I learn via immersion research & doing, I've read a lot of computer
books, and Hetland's is really quite good. I'll read Pilgrim's book in
the near future.

In general (with the notable exception of the Plone book) I've found
the Apress materials excellent. (Both books happen to be Apress, no
I'm not affiliated in any way).

--stv

From nephish at gmail.com  Thu Jan  4 15:59:43 2007
From: nephish at gmail.com (shawn bright)
Date: Thu, 4 Jan 2007 08:59:43 -0600
Subject: [Tutor] how to stop a thread
Message-ID: <384c93600701040659u6942a668w4f2964b6ba87429c@mail.gmail.com>

hello there all,

i have a python reference book that got me started knowing how to use
threads, i can declare one as a class, and start it like this

class SomeThread(threading.Thread):


run_process = SomeThread()
run_process.start()

but how do i kill it ? This part is not in my book. Basically the thread
works, and runs in a while loop. Is there a way to destroy the instance of
it after creation ?

thanks all

shawn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/febafc4c/attachment.htm 

From kent37 at tds.net  Thu Jan  4 16:08:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 04 Jan 2007 10:08:05 -0500
Subject: [Tutor] how to stop a thread
In-Reply-To: <384c93600701040659u6942a668w4f2964b6ba87429c@mail.gmail.com>
References: <384c93600701040659u6942a668w4f2964b6ba87429c@mail.gmail.com>
Message-ID: <459D1855.5040902@tds.net>

shawn bright wrote:
> hello there all,
> 
> i have a python reference book that got me started knowing how to use 
> threads, i can declare one as a class, and start it like this
> 
> class SomeThread(threading.Thread):
> 
> 
> run_process = SomeThread()
> run_process.start()
> 
> but how do i kill it ? This part is not in my book. Basically the thread 
> works, and runs in a while loop. Is there a way to destroy the instance 
> of it after creation ?

A thread dies when it's run() method exits, so you have to contrive a 
way to make run() exit. The usual way is to set a flag that the thread 
checks. Here is an example using a threading.Event as a flag:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448

Kent


From rdm at rcblue.com  Thu Jan  4 16:15:18 2007
From: rdm at rcblue.com (Dick Moores)
Date: Thu, 04 Jan 2007 07:15:18 -0800
Subject: [Tutor] farey() often gives incorrect result
Message-ID: <7.0.1.0.2.20070104063103.07c96008@rcblue.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/c8b17793/attachment.html 

From andrew.arobert at gmail.com  Thu Jan  4 16:22:44 2007
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Thu, 4 Jan 2007 10:22:44 -0500
Subject: [Tutor] Testing the status of NFS mounts
Message-ID: <fd85eb130701040722n41d0cb80if9d2bd885b26bc24@mail.gmail.com>

Hi everyone,

We have several NFS mounts that are in use.

Occasionally, the NFS mounts seem to go out to lunch.

The mounts appear active but are no longer functional.

Is there a Python module specific to NFS that I might use to periodically
check its status?

I imagine I could make a script to attempt a write on the share and clean up
after itself but I am hoping for a more elegant solution.

Any insight anyone can provide on this would be greatly  appreciated.

-- 
Thank you,
Andrew Robert

Senior MQ Engineer
Information Technologies
Massachussetts Financial Services
Phone: 617-954-5882
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/80c82d82/attachment.htm 

From nephish at gmail.com  Thu Jan  4 16:25:27 2007
From: nephish at gmail.com (shawn bright)
Date: Thu, 4 Jan 2007 09:25:27 -0600
Subject: [Tutor] how to stop a thread
In-Reply-To: <459D1855.5040902@tds.net>
References: <384c93600701040659u6942a668w4f2964b6ba87429c@mail.gmail.com>
	<459D1855.5040902@tds.net>
Message-ID: <384c93600701040725r7557bf4fpdee806a06b8361c3@mail.gmail.com>

i can do that, will use my config file,
thanks much
and thanks for the link.


shawn

On 1/4/07, Kent Johnson <kent37 at tds.net> wrote:
>
> shawn bright wrote:
> > hello there all,
> >
> > i have a python reference book that got me started knowing how to use
> > threads, i can declare one as a class, and start it like this
> >
> > class SomeThread(threading.Thread):
> >
> >
> > run_process = SomeThread()
> > run_process.start()
> >
> > but how do i kill it ? This part is not in my book. Basically the thread
> > works, and runs in a while loop. Is there a way to destroy the instance
> > of it after creation ?
>
> A thread dies when it's run() method exits, so you have to contrive a
> way to make run() exit. The usual way is to set a flag that the thread
> checks. Here is an example using a threading.Event as a flag:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/3b688f06/attachment.html 

From kent37 at tds.net  Thu Jan  4 16:38:28 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 04 Jan 2007 10:38:28 -0500
Subject: [Tutor] Testing the status of NFS mounts
In-Reply-To: <fd85eb130701040722n41d0cb80if9d2bd885b26bc24@mail.gmail.com>
References: <fd85eb130701040722n41d0cb80if9d2bd885b26bc24@mail.gmail.com>
Message-ID: <459D1F74.5020400@tds.net>

Andrew Robert wrote:
> Hi everyone,
> 
> We have several NFS mounts that are in use.
> 
> Occasionally, the NFS mounts seem to go out to lunch.
> 
> The mounts appear active but are no longer functional.
> 
> Is there a Python module specific to NFS that I might use to 
> periodically check its status?
> 
> I imagine I could make a script to attempt a write on the share and 
> clean up after itself but I am hoping for a more elegant solution.
> 
> Any insight anyone can provide on this would be greatly  appreciated.

If the share is mounted on the test machine, seems to me a simple 
os.path.isdir(<path to NFS root>) might do the trick. Otherwise, a quick 
Google turns up
http://www.citi.umich.edu/projects/nfsv4/pynfs/

HTH
Kent


From zebra05 at gmail.com  Thu Jan  4 17:11:30 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Thu, 4 Jan 2007 18:11:30 +0200
Subject: [Tutor] python web dev
Message-ID: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>

hi pythonistas!

this is my first post. please could you tell me which is the best
lightweight python web framework? also, which is the best templating
language for python? (which can handle other data formats in addition to
text). so far im lured by Cheetah, although i havent done any web dev with
python yet.

i absolutely love python syntax, but web dev in python is murky water. it
seems unneccesarily hard, even compared to php and asp.net

thanks,

Shortash
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/0a2cc6c2/attachment.htm 

From carroll at tjc.com  Thu Jan  4 17:20:41 2007
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 4 Jan 2007 08:20:41 -0800 (PST)
Subject: [Tutor] Need help with rewriting script to use Decimal  module
In-Reply-To: <7.0.1.0.2.20070103234257.06dcc0c0@rcblue.com>
Message-ID: <Pine.LNX.4.44.0701040815360.10441-100000@violet.rahul.net>

On Wed, 3 Jan 2007, Dick Moores wrote:

> Terry, I just noticed that farey(0.36, 10) returns (1, 3), a pretty 
> big miss, IMO. The correct fraction with smallest error and maximum 
> denominator of 10 is 3/8, which I'm proud to say my klunky frac.py 
> (<http://www.rcblue.com/Python/fracForWeb.py>) produces.

Dick, good catch.  Consider adding a comment to the Cookbook page pointing
out that the method sometimes does not produce the incorrect answer, 
including for that input.

I note that the web page for the recipe says only that its produces "a 
rational," not necessarily the closest rational, but the description in 
the book says it's the closest:

  You have a number v (of almost any type) and need to find a rational
  number (in reduced form) that is as close to v as possible but with a 
  denominator no larger than a prescribed value. (Recipe 18.13)



From simon at brunningonline.net  Thu Jan  4 17:25:11 2007
From: simon at brunningonline.net (Simon Brunning)
Date: Thu, 4 Jan 2007 16:25:11 +0000
Subject: [Tutor] python web dev
In-Reply-To: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
References: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
Message-ID: <8c7f10c60701040825q53ec7ffp90ebf89b16a7863c@mail.gmail.com>

On 1/4/07, OkaMthembo <zebra05 at gmail.com> wrote:
> this is my first post.

Welcome!

> please could you tell me which is the best
> lightweight python web framework?

Best? That's a potentially contensious one. But I can tell you that if
you were to look at either Django or TurboGears you wouldn't be going
too far wrong. (I use Django, but I know that both are good.)

> also, which is the best templating
> language for python? (which can handle other data formats in addition to
> text). so far im lured by Cheetah, although i havent done any web dev with
> python yet.

Cheetah's good, but if you go with Django, it has its own which is
pretty good too. (I use both at times.)

-- 
Cheers,
Simon B
simon at brunningonline.net
http://www.brunningonline.net/simon/blog/

From Mike.Hansen at atmel.com  Thu Jan  4 17:39:58 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 4 Jan 2007 09:39:58 -0700
Subject: [Tutor] python web dev
Message-ID: <57B026980605A64F9B23484C5659E32E4C7277@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces+mike.hansen=atmel.com at python.org 
> [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On 
> Behalf Of OkaMthembo
> Sent: Thursday, January 04, 2007 9:12 AM
> To: tutor at python.org
> Subject: [Tutor] python web dev
> 
> hi pythonistas!
> 
> this is my first post. please could you tell me which is the 
> best lightweight python web framework? also, which is the 
> best templating language for python? (which can handle other 
> data formats in addition to text). so far im lured by 
> Cheetah, although i havent done any web dev with python yet. 
> 
> i absolutely love python syntax, but web dev in python is 
> murky water. it seems unneccesarily hard, even compared to 
> php and asp.net
> 
> thanks,
> 
> Shortash

I'm using Cheetah on a current project. I really like it. I like that
you can compile the template and then use it as a module to populate it.

I want to check out Django next.

Mike
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS

From Mike.Hansen at atmel.com  Thu Jan  4 17:42:36 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 4 Jan 2007 09:42:36 -0700
Subject: [Tutor] SPE - Stani's Python Editor ?
Message-ID: <57B026980605A64F9B23484C5659E32E4C7279@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: OkaMthembo [mailto:zebra05 at gmail.com] 
> Sent: Thursday, January 04, 2007 9:18 AM
> To: Mike Hansen
> Subject: Re: [Tutor] SPE - Stani's Python Editor ?
> 
> have you tried Komodo from ActiveState or Wingware? might be 
> great, comeercial though.
> 
> 

I convinced my company to purchase Komodo. I use it off an on. I mostly
gravitate toward VIM. I'm looking forward to the next version of Komodo
since it will have vi keybindings. The nice thing about Komodo is that
you can use it for other languages like Perl and Ruby where I believe
that Wingware is Python only.

Mike
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS

From chris.arndt at web.de  Thu Jan  4 17:50:22 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Thu, 04 Jan 2007 17:50:22 +0100
Subject: [Tutor] python web dev
In-Reply-To: <8c7f10c60701040825q53ec7ffp90ebf89b16a7863c@mail.gmail.com>
References: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
	<8c7f10c60701040825q53ec7ffp90ebf89b16a7863c@mail.gmail.com>
Message-ID: <459D304E.8040505@web.de>

Simon Brunning schrieb:
> On 1/4/07, OkaMthembo <zebra05 at gmail.com> wrote:
>> also, which is the best templating
>> language for python? (which can handle other data formats in addition to
>> text). so far im lured by Cheetah, although i havent done any web dev with
>> python yet.
> 
> Cheetah's good, but if you go with Django, it has its own which is
> pretty good too. (I use both at times.)

There is now also Jinja [1], which is similar to the template language Django
uses, but can be used stand-alone. I haven't used it yet, but judging from the
docs it looks very promising.

I use Cheetah a lot, but I must say that it has a few quirks/bugs when used in
its standard configuration, and development could be a little faster. But I
much prefer it to XML-based template languages like Kid [2] or Genshi [3] though.

You can use both Cheetah and Jinja with TurboGears [4], though the coolest part
of TG, the widget system, currently only works well with Kid (but this is about
to change soon).

HTH, Chris

[1] http://wsgiarea.pocoo.org/jinja/
[2] http://www.kid-templating.org/
[3] http://genshi.edgewall.org/
[4] http://turbogears.org/

From rdm at rcblue.com  Thu Jan  4 17:57:35 2007
From: rdm at rcblue.com (Dick Moores)
Date: Thu, 04 Jan 2007 08:57:35 -0800
Subject: [Tutor] Need help with rewriting script to use Decimal module
In-Reply-To: <Pine.LNX.4.44.0701040815360.10441-100000@violet.rahul.net>
References: <7.0.1.0.2.20070103234257.06dcc0c0@rcblue.com>
	<Pine.LNX.4.44.0701040815360.10441-100000@violet.rahul.net>
Message-ID: <7.0.1.0.2.20070104085652.07d63ef0@rcblue.com>

At 08:20 AM 1/4/2007, Terry Carroll wrote:
>On Wed, 3 Jan 2007, Dick Moores wrote:
>
> > Terry, I just noticed that farey(0.36, 10) returns (1, 3), a pretty
> > big miss, IMO. The correct fraction with smallest error and maximum
> > denominator of 10 is 3/8, which I'm proud to say my klunky frac.py
> > (<http://www.rcblue.com/Python/fracForWeb.py>) produces.
>
>Dick, good catch.  Consider adding a comment to the Cookbook page pointing
>out that the method sometimes does not produce the incorrect answer,
>including for that input.

Done.

Dick




From chris.arndt at web.de  Thu Jan  4 18:19:35 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Thu, 04 Jan 2007 18:19:35 +0100
Subject: [Tutor] python web dev
In-Reply-To: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
References: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
Message-ID: <459D3727.6080907@web.de>

OkaMthembo schrieb:
> this is my first post. please could you tell me which is the best
> lightweight python web framework?

"Web framework" and "lightweight" don't really go well together. There are so
many things about web programming that you don't realise you need when you
start, but *will* come across eventually that a framework that addresses all
these, will not be lightweight any more.

If you are referring to the learning curve, Django is probably better suited
then TurboGears. If you have strong opinions about how certain things should be
solved, I'd go with TurboGears, because it's parts are not so tightly coupled
as Django's and can be replaced more easily.

The usual advice is: go through the tutorials that are available on the
homepages of both projects and then decide for your self. If the tutorials seem
to confusing, do a general (advanced) Python tutorial first.

I can't say much about other Python web frameworks, unfortunately.

> i absolutely love python syntax, but web dev in python is murky water.
> it seems unneccesarily hard, even compared to php and asp.net
> <http://asp.net>

Web development requires that you know about a lot of things. PHP just leaves
you to discover most of these (and build solutions for them) on your own. Which
is why so many PHP programs are crap ;-)

Chris

From noufal at airtelbroadband.in  Thu Jan  4 17:45:25 2007
From: noufal at airtelbroadband.in (Noufal Ibrahim)
Date: Thu, 04 Jan 2007 22:15:25 +0530
Subject: [Tutor] python web dev
In-Reply-To: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
References: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
Message-ID: <459D2F25.30703@airtelbroadband.in>

OkaMthembo wrote:
> hi pythonistas!
> 
> this is my first post. please could you tell me which is the best
> lightweight python web framework? also, which is the best templating
> language for python? (which can handle other data formats in addition to
> text). so far im lured by Cheetah, although i havent done any web dev
> with python yet.

I use clearsilver for templating and like it quite a bit.
I've tried Turbogears and kid (which comes with it is very nice too).

-- 
~noufal

From kent37 at tds.net  Thu Jan  4 19:18:16 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 04 Jan 2007 13:18:16 -0500
Subject: [Tutor] python web dev
In-Reply-To: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
References: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
Message-ID: <459D44E8.2060801@tds.net>

OkaMthembo wrote:
> hi pythonistas!
> 
> this is my first post. please could you tell me which is the best 
> lightweight python web framework? also, which is the best templating 
> language for python? (which can handle other data formats in addition to 
> text). so far im lured by Cheetah, although i havent done any web dev 
> with python yet.

What do you mean by lightweight? In addition to Django and TurboGears, 
which seem to be the current front-runners, you might want to look at 
web.py and Karrigell which might be considered more lightweight.

Kent


From cappy2112 at gmail.com  Thu Jan  4 21:36:54 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Thu, 4 Jan 2007 12:36:54 -0800
Subject: [Tutor] Assigning a variable stored in a dictionary
Message-ID: <8249c4ac0701041236v7ece07e9m47ae0574a39930d9@mail.gmail.com>

I can't see the forest through the trees.

I have stored 3 global variables in a dictionary, and associated each
variable with a filename.
Ideally, I want to read the contents of the text files, and store the
contents in the global variables. The globals will be used by another
function.
However, when I do the assignment to varname = fh.readlines(), a new
variable is created, and the reference to the global variable is
overwritten, because the contents of the files are strings, and strings are
immutable.

I see the problem, but not a good solution.


var1=""
var2=""
var3=""

def initGlobals():

    global var1, var2, var3

    fileDict = {'var1.txt':var1, 'var2.txt':var2, 'var3.txt':var3}

    for fn, varname in fileDict.iteritems():
        try:
            try:
                fh=open(fn, 'r')
                #id(varname) # at this point, this id matches the id of the
global variable
                varname = fh.readlines() # this creates a new variable, but
I want to store the file contents in the global var
                #id(varname)                  # this is a new id, the global
var is not updated
                fh.close()
            except IOError:
                print "\nFATAL ERROR occurred reading %s\n" % fn
        finally:
            fh.close()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/1bf1c90f/attachment.htm 

From kent37 at tds.net  Thu Jan  4 21:54:11 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 04 Jan 2007 15:54:11 -0500
Subject: [Tutor] Assigning a variable stored in a dictionary
In-Reply-To: <8249c4ac0701041236v7ece07e9m47ae0574a39930d9@mail.gmail.com>
References: <8249c4ac0701041236v7ece07e9m47ae0574a39930d9@mail.gmail.com>
Message-ID: <459D6973.5020804@tds.net>

Tony Cappellini wrote:
> 
> I can't see the forest through the trees.
> 
> I have stored 3 global variables in a dictionary, and associated each 
> variable with a filename.
> Ideally, I want to read the contents of the text files, and store the 
> contents in the global variables. The globals will be used by another 
> function.
> However, when I do the assignment to varname = fh.readlines(), a new 
> variable is created, and the reference to the global variable is 
> overwritten, because the contents of the files are strings, and strings 
> are immutable.
> 
> I see the problem, but not a good solution.
> 
> 
> var1=""
> var2=""
> var3=""
> 
> def initGlobals():
>   
>     global var1, var2, var3
> 
>     fileDict = {'var1.txt ':var1, 'var2.txt':var2, 'var3.txt':var3}
> 
>     for fn, varname in fileDict.iteritems():
>         try:
>             try:
>                 fh=open(fn, 'r')
>                 #id(varname) # at this point, this id matches the id of 
> the global variable
>                 varname = fh.readlines() # this creates a new variable, 
> but I want to store the file contents in the global var
>                 #id(varname)                  # this is a new id, the 
> global var is not updated
>                 fh.close()
>             except IOError:
>                 print "\nFATAL ERROR occurred reading %s\n" % fn
>         finally:
>             fh.close()

You have a fundamental misunderstanding of the nature of variables and 
names in Python. This may help:
http://effbot.org/zone/python-objects.htm

Python variables are *not* containers for values, they are references to 
values. They are names for values. Some people like to think of a Python 
name as a sticky note that gets put on the value, giving it a name. I 
like to think of a name as pointing to a value.

The values of your fileDict are just references to the empty string, 
they don't have any association at all with the global variables you 
want to change; they just happen to have the same value.

The easiest solution is to just use the dict to store the file names and 
data, forget about the global variables:

fileData = {}
for name in 'var1.txt', 'var2.txt', 'var3.txt':
	f = open(name)
	fileData[name] = f.readlines()
	f.close()

At this point you have a dict whose keys are the three file names and 
whose associated values are the contents of the files.

Kent


From dseto200 at pacbell.net  Thu Jan  4 23:08:29 2007
From: dseto200 at pacbell.net (David)
Date: Thu, 4 Jan 2007 14:08:29 -0800
Subject: [Tutor] coin toss program without using the for/range loop
Message-ID: <000001c7304c$de339a40$7301a8c0@davidxp>

How to write the coin toss program without using the for/range loop program.

Program flips a coin 100 times and then tells you the number of heads and
tails.

 

I can only solve it using the for/range loop

 

Import random

  Heads=0

  For 1 in range (100):

  Heads+=random.randrange(2)

 

print "Hit heads"+" "+str(heads)+" "+"times"+" " + "hit tails" + "
"+str(100-heads)+" " + "times"

 

I don't see how you solve this program just using the while loop program and
if/else statement.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/8ca7ecfd/attachment.html 

From kent37 at tds.net  Fri Jan  5 01:12:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 04 Jan 2007 19:12:05 -0500
Subject: [Tutor] coin toss program without using the for/range loop
In-Reply-To: <000001c7304c$de339a40$7301a8c0@davidxp>
References: <000001c7304c$de339a40$7301a8c0@davidxp>
Message-ID: <459D97D5.7050800@tds.net>

David wrote:
> How to write the coin toss program without using the for/range loop program.
> 
> Program flips a coin 100 times and then tells you the number of heads 
> and tails.
> 
>  
> 
> I can only solve it using the for/range loop
> 
>  
> 
> Import random
> 
>   Heads=0
> 
>   For 1 in range (100):
> 
>   Heads+=random.randrange(2)
> 
>  
> 
> print ?Hit heads?+? ?+str(heads)+? ?+?times?+? ? + ?hit tails? + ? 
> ?+str(100-heads)+? ? + ?times?
> 
>  
> 
> I don?t see how you solve this program just using the while loop program 
> and if/else statement.

This sounds a lot like homework so I won't give you the whole answer, 
but you can write a for loop using while and a counter variable.

Kent


From rabidpoobear at gmail.com  Fri Jan  5 01:41:57 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 04 Jan 2007 18:41:57 -0600
Subject: [Tutor] coin toss program without using the for/range loop
In-Reply-To: <459D97D5.7050800@tds.net>
References: <000001c7304c$de339a40$7301a8c0@davidxp> <459D97D5.7050800@tds.net>
Message-ID: <459D9ED5.2010209@gmail.com>

Kent Johnson wrote:
> David wrote:
>   
>> How to write the coin toss program without using the for/range loop program.
>>
>> Program flips a coin 100 times and then tells you the number of heads 
>> and tails.
>>
>>  
>>
>> I can only solve it using the for/range loop
>>
>>  
>>
>> Import random
>>
>>   Heads=0
>>
>>   For 1 in range (100):
>>
>>   Heads+=random.randrange(2)
>>
>>  
>>
>> print ?Hit heads?+? ?+str(heads)+? ?+?times?+? ? + ?hit tails? + ? 
>> ?+str(100-heads)+? ? + ?times?
>>
>>  
>>
>> I don?t see how you solve this program just using the while loop program 
>> and if/else statement.
>>     
>
> This sounds a lot like homework so I won't give you the whole answer, 
> but you can write a for loop using while and a counter variable.
>
>   
In fact, in most languages a for loop and a while loop are very similar:

for(int i =0; i < 100; i++)
{
    //do something
}
is the same as
int i = 0
while (i < 100)
{
    // do something
    i++;
}

The difference in Python comes from the fact that the 'for' loop 
iterates over a list of objects,
rather than incrementing a variable.
If you're using a for-range loop in Python you're using it in the 
old-style that C and C++ programs use (other languages too)
in which case you could easily use a while loop as well.
But if you're indexing into a specific list,
it becomes much more clear why we use python's 'for',
to index directly into that list without having to deal with an index 
variable.

for x in some_list:
    // do something with x

rather than

index = 0
while index < len(some_list):
    x = some_list[index]
    // do something with x
    index += 1

HTH,
-Luke
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From chris.arndt at web.de  Fri Jan  5 01:50:36 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 05 Jan 2007 01:50:36 +0100
Subject: [Tutor] coin toss program without using the for/range loop
In-Reply-To: <459D97D5.7050800@tds.net>
References: <000001c7304c$de339a40$7301a8c0@davidxp> <459D97D5.7050800@tds.net>
Message-ID: <459DA0DC.2030907@web.de>

Kent Johnson schrieb:
> David wrote:
>> print ?Hit heads?+? ?+str(heads)+? ?+?times?+? ? + ?hit tails? + ? 
>> ?+str(100-heads)+? ? + ?times?
> 
> This sounds a lot like homework [...]

An if you want to get extra marks for pythonicity  ;-), read about string
formatting here:

http://www.python.org/doc/current/lib/typesseq-strings.html

Chris

From marshall.jiang at gmail.com  Fri Jan  5 02:58:36 2007
From: marshall.jiang at gmail.com (Shuai Jiang (Runiteking1))
Date: Thu, 4 Jan 2007 20:58:36 -0500
Subject: [Tutor] Question regarding parsing HTML with BeautifulSoup
In-Reply-To: <459C62F7.2090400@tds.net>
References: <a678270c0701031139t499f040bj4fcd3bb8b94dbba1@mail.gmail.com>
	<459C62F7.2090400@tds.net>
Message-ID: <a678270c0701041758q7d7ba54bg605e4af5d2272e4@mail.gmail.com>

Hi,

Wow, thats much more elegant than the idea I thought of.

Thank you very much Kent!

Marshall

On 1/3/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Shuai Jiang (Runiteking1) wrote:
> > Hello,
> >
> > I'm working on a program that need to parse a financial document on the
> > internet
> > using BeautifulSoup. Because of the nature of the information, it is all
> > grouped
> > as a table. I needed to get 3 types of info and have succeeded quite
> > well using
> > BeautifulSoup, but encountered problems on the third one.
> >
> > My question is that is there any easy way to parse an HTML tables column
> > easily using BeautifulSoup. I copied the table here and I need to
> > extract the EPS. The numbers are
> > every sixth one from the  <tr> tag ex 2.27, 1.86, 1.61...
>
> Here is one way, found with a little experimenting at the command prompt:
>
> In [1]: data = '''<table id="INCS" style="width:580px" class="f10y"
> cellspacing="0">
> <snip the rest of your data>
>     ...: </table>'''
> In [3]: from BeautifulSoup import BeautifulSoup as BS
>
> In [4]: soup=BS(data)
>
> In [11]: for tr in soup.table.findAll('tr'):
>     ....:     print tr.contents[11].string
>     ....:
>     ....:
> EPS
> 2.27
>   1.86
> 1.61
>   1.27
> 1.18
>   0.84
> 0.73
>   0.46
> 0.2
>   0.0
>
> Kent
>
>
>


-- 
I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as
equals.
    Sir Winston Churchill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070104/09d685fb/attachment.htm 

From shanmuha at gmail.com  Fri Jan  5 07:18:50 2007
From: shanmuha at gmail.com (Shanmuhanathan T)
Date: Fri, 5 Jan 2007 11:48:50 +0530
Subject: [Tutor] SPE - Stani's Python Editor ?
In-Reply-To: <57B026980605A64F9B23484C5659E32E4C7279@poccso.US.ad.atmel.com>
References: <57B026980605A64F9B23484C5659E32E4C7279@poccso.US.ad.atmel.com>
Message-ID: <9871e7140701042218yefda759l8e614a51c58f7a2d@mail.gmail.com>

I found eclipse+pydev to be as good as/better than komodo or wingware.
also eclipse has other plugins which makes it a powerful IDEs for
php/ruby/perl etc.

Regards,
Shanmu.

On 1/4/07, Mike Hansen <Mike.Hansen at atmel.com> wrote:
>
>
>
> > -----Original Message-----
> > From: OkaMthembo [mailto:zebra05 at gmail.com]
> > Sent: Thursday, January 04, 2007 9:18 AM
> > To: Mike Hansen
> > Subject: Re: [Tutor] SPE - Stani's Python Editor ?
> >
> > have you tried Komodo from ActiveState or Wingware? might be
> > great, comeercial though.
> >
> >
>
> I convinced my company to purchase Komodo. I use it off an on. I mostly
> gravitate toward VIM. I'm looking forward to the next version of Komodo
> since it will have vi keybindings. The nice thing about Komodo is that
> you can use it for other languages like Perl and Ruby where I believe
> that Wingware is Python only.
>
> Mike
>
>
> -------------
>
>   NOTICE:  This e-mail transmission and any documents or files attached to
>   it contain information for the sole use of the above-identified
> individual or entity.
>
>   Its contents may be privileged, confidential, and exempt from disclosure
> under the law.
>   Any dissemination, distribution, or copying of this communication is
> strictly prohibited.
>
>   Please notify the sender immediately if you are not the intended
> recipient.
>
> FGNS
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070105/f922f725/attachment.htm 

From carroll at tjc.com  Fri Jan  5 08:21:26 2007
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 4 Jan 2007 23:21:26 -0800 (PST)
Subject: [Tutor] Need help with rewriting script to use Decimal  module
In-Reply-To: <7.0.1.0.2.20070103234257.06dcc0c0@rcblue.com>
Message-ID: <Pine.LNX.4.44.0701042304480.30388-100000@violet.rahul.net>

On Wed, 3 Jan 2007, Dick Moores wrote:

> Be that as it may, farey() is an amazing program. 

Not to beat this subject to death, but the comment at the bottom of 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317 about 
continued fractions piqued my interest.  I'm no mathematician, but I 
encountered continued fractions a long time ago and was fascinated by 
them.  So I read the URL pointed to, 
http://mathworld.wolfram.com/ContinuedFraction.html , and came up with the 
following:

#####################################################

def cf(x, tol=0.0001, Trace=False):
    """
    Calculate rational approximation of x to within tolerance of tol;
    returns a tuple consisting of numerator and denominator p/q
    Trace=True causes iterated results to be shown
    """
    a, r, p, q = [], [], [], []
    Done = False
    n = 0
    if Trace: print "x:%f tol:%f" % (x, tol)
    while not Done:
        a.append(None)
        r.append(None)
        p.append(None)
        q.append(None)
        if n == 0: r[n] = x
        else: r[n] = 1/(r[n-1]-a[n-1])
        a[n] = int(r[n])
        if n == 0:
            p[n] = a[0]
            q[n] = 1
        elif n ==1:
            p[n] = a[n]*p[n-1] + 1
            q[n] = a[n]
        else:
            p[n] = a[n]*p[n-1] + p[n-2]
            q[n] = a[n]*q[n-1] + q[n-2]
        if Trace:
            print "n:%d a:%d p:%d q:%d approx:%f" % \
                  (n, a[n], p[n], q[n], float(p[n])/q[n])
        if abs(float(p[n])/q[n] - x) < tol:
            Done = True
        num = p[n]; denom = q[n]
        n += 1
    return (num, denom)

#####################################################

Here's a result for pi:

>>> print cf(3.14159265357989,0.0000001, Trace=True)
x:3.141593 tol:0.000000
n:0 a:3 p:3 q:1 approx:3.000000
n:1 a:7 p:22 q:7 approx:3.142857
n:2 a:15 p:333 q:106 approx:3.141509
n:3 a:1 p:355 q:113 approx:3.141593
n:4 a:292 p:103993 q:33102 approx:3.141593
(103993, 33102)

i.e., the first 5 approximations it came up with were 3/1, 22/7, 333/106, 
355/113 and a whopping 103993/33102.

For the 0.36 example you used earlier:

>>> print cf(0.36, .01, Trace= True)
x:0.360000 tol:0.010000
n:0 a:0 p:0 q:1 approx:0.000000
n:1 a:2 p:1 q:2 approx:0.500000
n:2 a:1 p:1 q:3 approx:0.333333
n:3 a:3 p:4 q:11 approx:0.363636
(4, 11)
>>>

it went right from 1/3 to 4/11 (0.363636), skipping the 3/8 (0.375) option 
from the farey series.  

But this continued fraction algorithm is ill-suited to answer the question
"what's the closest fraction with a denominator < N", because it doesn't
try to find that, it jumps further ahead with each iteration.

Anyway, I thought you might find it interesting based on our discussion.

(Yeah, I know, I didn't choose the formats well on those print 
statements.)


From pytutor.20.247ob at spamgourmet.com  Fri Jan  5 10:31:58 2007
From: pytutor.20.247ob at spamgourmet.com (pytutor.20.247ob at spamgourmet.com)
Date: Fri, 5 Jan 2007 09:31:58 +0000 (GMT)
Subject: [Tutor] Best way to call a prog that requires root access in linux
Message-ID: <281624.69177.qm@web23412.mail.ird.yahoo.com>

Hi all,

I've had a dig around on the forums about this and it was suggested to
use 'sudo'.
Well I have done this, I need to call tcpdump so I can sniff the
traffic and find the url's, I've modified my sudoers file so that for
this exe only I need no password.
This seems to be the best way since the program only runs the tcpdump
command as root (which incidently has a switch that allows you to drop
root privs once it's started) I want to distribute the program once
it's finished so it means explaining this (sudo bit) in the install
instructions.

Is this a good / bad way to achieve this? 

BTW I use Ubuntu which uses sudo by default however anyone might use
it.

Thanks in advance,

Wayne.

Send instant messages to your online friends http://uk.messenger.yahoo.com 

From alan.gauld at btinternet.com  Fri Jan  5 10:16:41 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Fri, 5 Jan 2007 09:16:41 +0000 (GMT)
Subject: [Tutor] Fwd: Reg http request object
Message-ID: <532449.48122.qm@web86104.mail.ird.yahoo.com>

Forwarding to the group in the hope someone 
may know the answer. 

--- anil maran <anilmrn at yahoo.com> wrote:

> Date: Thu, 4 Jan 2007 16:57:01 -0800 (PST)
> From: anil maran <anilmrn at yahoo.com>
> Subject: Reg http request object
> To: Alan Gauld <alan.gauld at btinternet.com>
> 
> Hi Alan
>  I m using webpy
>  The code was written for Django
>  facebook uses Request  http object and I need to get it and
> use it for processing the content after the user logs into
> facebook. This is part of facebook dev program.
>  
>  http://webpy.org/svn/trunk/web/
>  
> So I need to get my hands on the HTTP request object in
> facebook.. do help me out
> 
> Thanks
> 
> 
> > Here is the problem the example usage is in Django
> >
> > and they are talking about a request object
> >    if 'session_key' in request.session and 'uid' in
> > request.session:
> >        fb.session_key =
> > request.session['session_key']
> >
> > Anyone can tell me how I can access this in webpy
> > Isnt flup something that is set from webpy,
> 
> 
> OK, I\'m confused.
> 
> Can you clarify what is happening for me?
> Are you using Django? Are you using webpy? Or both?
> Also what is flup? I\'ve never heard of it...
> 
> Also what is the \'this\' that you want to access in webpy?
> Is it the request or the session? Or do you want to
> access Django code from webpy?
> 
> As I say, I\'m confused about what you are using
> and what you want us to help you with?
> 
> Alan G.
> Who is learning TurnoGears and knows next to
> nothing about webpy and only a little about Django...
> 
> ",1] ); D(["mb","- Show quoted text -
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> ",0] ); D(["ce"]);  //-->OK, I'm confused.
> 
> Can you clarify what is happening for me?
> Are you using Django? Are you using webpy? Or both?
> Also what is flup? I've never heard of it...
> 
> Also what is the 'this' that you want to access in webpy?
> Is it the request or the session? Or do you want to
> access Django code from webpy?
> 
> As I say, I'm confused about what you are using
> and what you want us to help you with?
> 
> Alan G.
> Who is learning TurnoGears and knows next to
> nothing about webpy and only a little about Django...
>  
>  __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection
> around 
> http://mail.yahoo.com 



		
___________________________________________________________ 
Yahoo! Messenger - with free PC-PC calling and photo sharing. http://uk.messenger.yahoo.com

From kent37 at tds.net  Fri Jan  5 12:01:42 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 05 Jan 2007 06:01:42 -0500
Subject: [Tutor] Fwd: Reg http request object
In-Reply-To: <532449.48122.qm@web86104.mail.ird.yahoo.com>
References: <532449.48122.qm@web86104.mail.ird.yahoo.com>
Message-ID: <459E3016.3040306@tds.net>

Anil,

I'm also confused about what you are trying to do. Are you writing a 
client application that talks to a web application? A web application 
that talks to a different web application? A new part of an existing web 
application? What are you using web.py for? What does facebook have to 
do with it? You have to give a clearer description of what you need.

The request object is a server-side object that will be specific to the 
web framework in use - the Django request object will most likely be 
different from the web.py request object. Also the way sessions are 
maintained will differ between frameworks. They will contain similar 
information but differ in the specifics.

Kent

ALAN GAULD wrote:
> Forwarding to the group in the hope someone 
> may know the answer. 
> 
> --- anil maran <anilmrn at yahoo.com> wrote:
> 
>> Date: Thu, 4 Jan 2007 16:57:01 -0800 (PST)
>> From: anil maran <anilmrn at yahoo.com>
>> Subject: Reg http request object
>> To: Alan Gauld <alan.gauld at btinternet.com>
>>
>> Hi Alan
>>  I m using webpy
>>  The code was written for Django
>>  facebook uses Request  http object and I need to get it and
>> use it for processing the content after the user logs into
>> facebook. This is part of facebook dev program.
>>  
>>  http://webpy.org/svn/trunk/web/
>>  
>> So I need to get my hands on the HTTP request object in
>> facebook.. do help me out
>>
>> Thanks
>>
>>
>>> Here is the problem the example usage is in Django
>>>
>>> and they are talking about a request object
>>>    if 'session_key' in request.session and 'uid' in
>>> request.session:
>>>        fb.session_key =
>>> request.session['session_key']
>>>
>>> Anyone can tell me how I can access this in webpy
>>> Isnt flup something that is set from webpy,
>>
>> OK, I\'m confused.
>>
>> Can you clarify what is happening for me?
>> Are you using Django? Are you using webpy? Or both?
>> Also what is flup? I\'ve never heard of it...
>>
>> Also what is the \'this\' that you want to access in webpy?
>> Is it the request or the session? Or do you want to
>> access Django code from webpy?
>>
>> As I say, I\'m confused about what you are using
>> and what you want us to help you with?
>>
>> Alan G.
>> Who is learning TurnoGears and knows next to
>> nothing about webpy and only a little about Django...
>>
>> ",1] ); D(["mb","- Show quoted text -
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>> ",0] ); D(["ce"]);  //-->OK, I'm confused.
>>
>> Can you clarify what is happening for me?
>> Are you using Django? Are you using webpy? Or both?
>> Also what is flup? I've never heard of it...
>>
>> Also what is the 'this' that you want to access in webpy?
>> Is it the request or the session? Or do you want to
>> access Django code from webpy?
>>
>> As I say, I'm confused about what you are using
>> and what you want us to help you with?
>>
>> Alan G.
>> Who is learning TurnoGears and knows next to
>> nothing about webpy and only a little about Django...
>>  
>>  __________________________________________________
>> Do You Yahoo!?
>> Tired of spam?  Yahoo! Mail has the best spam protection
>> around 
>> http://mail.yahoo.com 
> 
> 
> 
> 		
> ___________________________________________________________ 
> Yahoo! Messenger - with free PC-PC calling and photo sharing. http://uk.messenger.yahoo.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From janos.juhasz at VELUX.com  Fri Jan  5 13:19:16 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Fri, 5 Jan 2007 13:19:16 +0100
Subject: [Tutor] Find and test a device by  MAC address
In-Reply-To: <mailman.45.1167908411.8133.tutor@python.org>
Message-ID: <OF2A141844.3B260DE4-ONC125725A.003BA0A5-C125725A.0043ADCD@velux.com>

Dear Lumbricus,

> From: lumbricus at gmx.net
> Subject: Re: [Tutor] Find and test a device by  MAC address
> To: tutor at python.org
> Message-ID: <20070104082319.260950 at gmx.net>
> Content-Type: text/plain; charset="iso-8859-1"

> Quick and dirty:
> As root:
> >>> from scapy import *
> >>> arping("192.168.0.1/24") # or whatever fits to your network
> and then filter the answers; or build your own arp packets with ARP().

I have an XP, so I made a simple ping for the topmost IP address, 
that is the broadcast address in my subnet and I run an arp -a.

Thanks for the hint for scapy.

http://www.secdev.org/projects/scapy/ seems to be very very cool.

Some months earlier someone tried to collect how many application made in 
pure python.
The list should be extended with scapy as a pure python application.

Thanks Lumbricus.

Yours sincerely, 
______________________________
Janos Juhasz 


From alan.gauld at btinternet.com  Fri Jan  5 16:44:54 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 5 Jan 2007 15:44:54 -0000
Subject: [Tutor] Best way to call a prog that requires root access in
	linux
References: <281624.69177.qm@web23412.mail.ird.yahoo.com>
Message-ID: <enlrm7$p59$1@sea.gmane.org>


<pytutor.20.247ob at spamgourmet.com> wrote

> I've had a dig around on the forums about this and it was suggested 
> to
> use 'sudo'.

sudo is the best way to run applications with a different access 
level.

Since this is an OS thing usinbg sudo is the right solution IMHO.
If you ever want to port your code to XP or VMS or whatever you
would need to rewrite the security model if you tried to do it
in the application. Much better to handle the issue in the OS.

Thats my view at least...


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From jorgen.maillist at gmail.com  Fri Jan  5 16:44:59 2007
From: jorgen.maillist at gmail.com (Jorgen Bodde)
Date: Fri, 5 Jan 2007 16:44:59 +0100
Subject: [Tutor] Load DLL / library and run a thread from it
Message-ID: <11e49df10701050744o38fe5cfdo25f6205b86d5c432@mail.gmail.com>

Hi Guys,

I want to make a C++ DLL that spawns a thread, and wrap this with
Python so that a thread still runs inside the DLL, but I can access
methods to communicate with it, and preferrably receive callbacks from
it.

I searched the net for examples explaining concepts like this, but I
am lost. Is this possible or is it that trivial that nobody seems to
explain it?

The C++ DLL will not run any python code, it is a simulation engine
from which I want to make the status available in wxPython.

Regards,
- Jorgen

From chris.arndt at web.de  Fri Jan  5 16:50:20 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 05 Jan 2007 16:50:20 +0100
Subject: [Tutor] Best way to call a prog that requires root access in
	linux
In-Reply-To: <281624.69177.qm@web23412.mail.ird.yahoo.com>
References: <281624.69177.qm@web23412.mail.ird.yahoo.com>
Message-ID: <459E73BC.6010303@web.de>

pytutor.20.247ob at spamgourmet.com schrieb:
> I want to distribute the program once
> it's finished so it means explaining this (sudo bit) in the install
> instructions.
> 
> Is this a good / bad way to achieve this? 

Yes, the user should be always made aware, if he is to run something as root.
Requiring him to configure sudo is a good way to do this.

Just make sure your program fails with a meaningful error message, if sudo
isn't set up properly.

Chris

From zebra05 at gmail.com  Fri Jan  5 16:57:54 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Fri, 5 Jan 2007 17:57:54 +0200
Subject: [Tutor] python web dev
In-Reply-To: <8c7f10c60701040825q53ec7ffp90ebf89b16a7863c@mail.gmail.com>
References: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
	<8c7f10c60701040825q53ec7ffp90ebf89b16a7863c@mail.gmail.com>
Message-ID: <c7c6f3bc0701050757u66edaed2vbbf59792fc6049b5@mail.gmail.com>

Thanks Gents,

You do all make sense to me. My dilemma really, is that im from a .NET
background where i write business logic in C#  and write my own stored
procs, etc...with the "cosmetic" design fully seperated from it all. so i
think id feel more confortable with a framework thatd provide a basic MVC
architecture and leave me to roll my own SQL etc, not one that will generate
half a project for me. ive taken another look at Cheetah and i think i like
it the most thus far.

My other issue is: has anybody run a python web app under lighttpd? and if
so, where can i get the Windows lighttpd build? the link to
kevinworthington.com on the official site is dead, and ive not had a
response from the lighttpd webmaster.

happy coding...

Shortash



On 1/4/07, Simon Brunning <simon at brunningonline.net> wrote:
>
> On 1/4/07, OkaMthembo <zebra05 at gmail.com> wrote:
> > this is my first post.
>
> Welcome!
>
> > please could you tell me which is the best
> > lightweight python web framework?
>
> Best? That's a potentially contensious one. But I can tell you that if
> you were to look at either Django or TurboGears you wouldn't be going
> too far wrong. (I use Django, but I know that both are good.)
>
> > also, which is the best templating
> > language for python? (which can handle other data formats in addition to
> > text). so far im lured by Cheetah, although i havent done any web dev
> with
> > python yet.
>
> Cheetah's good, but if you go with Django, it has its own which is
> pretty good too. (I use both at times.)
>
> --
> Cheers,
> Simon B
> simon at brunningonline.net
> http://www.brunningonline.net/simon/blog/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070105/1fdbd42a/attachment.htm 

From maellis002 at yahoo.com  Fri Jan  5 17:04:23 2007
From: maellis002 at yahoo.com (Mike Ellis)
Date: Fri, 5 Jan 2007 08:04:23 -0800 (PST)
Subject: [Tutor] Python gui for file input
Message-ID: <900982.83522.qm@web58012.mail.re3.yahoo.com>

Hi all,

I am looking to create a simple gui interface to a small script.  The script requires the user to input a directory.  I would like to allow the user to browse the windows file system for the desired directory rather than type in the full path by hand.  This would operate in much the same way as any program when you select File>Open.  Is this possible to do with python?  Can anyone point me in the proper direction to find more info on this or perhaps an example script using a similar feature?

Thanks for your help,
Michael

 __________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070105/b7b233fe/attachment.html 

From jason.massey at gmail.com  Fri Jan  5 17:21:47 2007
From: jason.massey at gmail.com (Jason Massey)
Date: Fri, 5 Jan 2007 10:21:47 -0600
Subject: [Tutor] Python gui for file input
In-Reply-To: <900982.83522.qm@web58012.mail.re3.yahoo.com>
References: <900982.83522.qm@web58012.mail.re3.yahoo.com>
Message-ID: <7e3eab2c0701050821i45e22404teece83e18f4b4e52@mail.gmail.com>

The simplest way would be to use TkInter which is distributed with Python.

Check out the cookbook recipe at:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438123 for a bunch
of examples.


jason

On 1/5/07, Mike Ellis <maellis002 at yahoo.com> wrote:
>
> Hi all,
>
> I am looking to create a simple gui interface to a small script.  The
> script requires the user to input a directory.  I would like to allow the
> user to browse the windows file system for the desired directory rather than
> type in the full path by hand.  This would operate in much the same way as
> any program when you select File>Open.  Is this possible to do with python?
> Can anyone point me in the proper direction to find more info on this or
> perhaps an example script using a similar feature?
>
> Thanks for your help,
> Michael
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam? Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070105/e6451341/attachment-0001.htm 

From kent37 at tds.net  Fri Jan  5 17:39:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 05 Jan 2007 11:39:06 -0500
Subject: [Tutor] python web dev
In-Reply-To: <c7c6f3bc0701050757u66edaed2vbbf59792fc6049b5@mail.gmail.com>
References: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>	<8c7f10c60701040825q53ec7ffp90ebf89b16a7863c@mail.gmail.com>
	<c7c6f3bc0701050757u66edaed2vbbf59792fc6049b5@mail.gmail.com>
Message-ID: <459E7F2A.7090000@tds.net>

OkaMthembo wrote:
> Thanks Gents,
> 
> You do all make sense to me. My dilemma really, is that im from a .NET 
> background where i write business logic in C#  and write my own stored 
> procs, etc...with the "cosmetic" design fully seperated from it all. so 
> i think id feel more confortable with a framework thatd provide a basic 
> MVC architecture and leave me to roll my own SQL etc, not one that will 
> generate half a project for me. ive taken another look at Cheetah and i 
> think i like it the most thus far.

Cheetah is only a template language, it doesn't give you any mechanism 
for receiving and responding to HTTP requests. You still need some web 
infrastructure. web.py and pylons both work with Cheetah; I think 
TurboGears will also. Or you could use a bare web server such as 
CherryPy or Karrigell with Cheetah.

You might want to take a look at Pylons, it is perhaps the most 
"pluggable" of the major frameworks. You also might be interested in 
SQLAlchemy which provides a higher-level of access to your database than 
plain DB-API but doesn't hide the SQL from you.

> 
> My other issue is: has anybody run a python web app under lighttpd? and 
> if so, where can i get the Windows lighttpd build? the link to 
> kevinworthington.com <http://kevinworthington.com> on the official site 
> is dead, and ive not had a response from the lighttpd webmaster.

Any WSGI-compatible web app will run under lighttpd using flup as a 
FastCGI connector. web.py, Pylons, TurboGears and Django all give 
instructions for this in their docs.

Kent


From kent37 at tds.net  Fri Jan  5 17:41:53 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 05 Jan 2007 11:41:53 -0500
Subject: [Tutor] Python gui for file input
In-Reply-To: <7e3eab2c0701050821i45e22404teece83e18f4b4e52@mail.gmail.com>
References: <900982.83522.qm@web58012.mail.re3.yahoo.com>
	<7e3eab2c0701050821i45e22404teece83e18f4b4e52@mail.gmail.com>
Message-ID: <459E7FD1.8030600@tds.net>

Jason Massey wrote:
> The simplest way would be to use TkInter which is distributed with Python. 
> 
> Check out the cookbook recipe at: 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438123 
> <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438123> for a 
> bunch of examples.

You might also be interested in EasyGUI which wraps up these and several 
other simple dialog boxes.
http://www.ferg.org/easygui/

Kent


From ajkadri at googlemail.com  Fri Jan  5 17:55:23 2007
From: ajkadri at googlemail.com (Asrarahmed Kadri)
Date: Fri, 5 Jan 2007 16:55:23 +0000
Subject: [Tutor] Does python produces bytecode??
Message-ID: <b4e894c70701050855y790af633o5efd68db164cb659@mail.gmail.com>

Hi Folks,

Just a bit curious about how python runs the program?

I do know that it does not compile the code; its an interpreted language.

Do we have something like Python virtual machine ??

Please hlep me to understand these things.


Regards,
Asrarahmed
-- 
To HIM you shall return.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070105/a0b33925/attachment.htm 

From kent37 at tds.net  Fri Jan  5 18:15:44 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 05 Jan 2007 12:15:44 -0500
Subject: [Tutor] Does python produces bytecode??
In-Reply-To: <b4e894c70701050855y790af633o5efd68db164cb659@mail.gmail.com>
References: <b4e894c70701050855y790af633o5efd68db164cb659@mail.gmail.com>
Message-ID: <459E87C0.1090607@tds.net>

Asrarahmed Kadri wrote:
> 
> Hi Folks,
>  
> Just a bit curious about how python runs the program?
>  
> I do know that it does not compile the code; its an interpreted language.
>  
> Do we have something like Python virtual machine ??
>  
> Please hlep me to understand these things.

Yes, Python has a bytecode compiler and a virtual machine (bytecode 
interpreter). The compiler is invoked automatically when needed so it is 
not really apparent to a casual user.

The dis module in the standard library lets you see the bytecode 
representation of a function or other code. The docs for this module 
include a listing of all the bytecode instructions.

If you want to dig into the details you have to look at the C source 
code for Python. This page gives a high-level guide:
http://effbot.org/pyfaq/where-do-i-start-if-i-want-to-learn-about-the-cpython-implementation.htm

Kent


From nephish at gmail.com  Fri Jan  5 18:18:17 2007
From: nephish at gmail.com (shawn bright)
Date: Fri, 5 Jan 2007 11:18:17 -0600
Subject: [Tutor] need help with sending email
Message-ID: <384c93600701050918r533d7193k7580925064a9637b@mail.gmail.com>

lo there all.

i am in a tight spot because i need to send an email that it mime encoded
plain-text ( not html or anything )
no attachements, no images, just text from a string. like message = 'some
message'
all the tutorials i find out there, and the cookbook recipies are for
sending multipart messages, attachments, etc..
this needs to be simple, but needs to be able to reach a large variety of
cell phone text message receivers.

anyone know of a good tutorial or recipe out there ?

thanks,
shawn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070105/1ed4e084/attachment.html 

From Mike.Hansen at atmel.com  Fri Jan  5 18:29:05 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Fri, 5 Jan 2007 10:29:05 -0700
Subject: [Tutor] need help with sending email
Message-ID: <57B026980605A64F9B23484C5659E32E4C73B1@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of shawn bright
> Sent: Friday, January 05, 2007 10:18 AM
> To: tutor-python
> Subject: [Tutor] need help with sending email
> 
> lo there all.
> 
> i am in a tight spot because i need to send an email that it 
> mime encoded plain-text ( not html or anything )
> no attachements, no images, just text from a string. like 
> message = 'some message' 
> all the tutorials i find out there, and the cookbook recipies 
> are for sending multipart messages, attachments, etc..
> this needs to be simple, but needs to be able to reach a 
> large variety of cell phone text message receivers. 
> 
> anyone know of a good tutorial or recipe out there ?
> 
> thanks,
> shawn
> 
>
This might help:

http://effbot.org/librarybook/smtplib.htm 

Also, the docs on smtplib:

http://docs.python.org/lib/module-smtplib.html

Mike
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS

From nephish at gmail.com  Fri Jan  5 18:34:45 2007
From: nephish at gmail.com (shawn bright)
Date: Fri, 5 Jan 2007 11:34:45 -0600
Subject: [Tutor] need help with sending email
In-Reply-To: <57B026980605A64F9B23484C5659E32E4C73B1@poccso.US.ad.atmel.com>
References: <57B026980605A64F9B23484C5659E32E4C73B1@poccso.US.ad.atmel.com>
Message-ID: <384c93600701050934rfaaa42fk70054895c123307f@mail.gmail.com>

right, thanks, Mike.
i can send an email fine. Some of the providers we are trying to reach will
reject anything that is not content type: text-plain

thats what i need to know how to add.

thanks again
shawn

On 1/5/07, Mike Hansen <Mike.Hansen at atmel.com> wrote:
>
>
>
> > -----Original Message-----
> > From: tutor-bounces at python.org
> > [mailto:tutor-bounces at python.org] On Behalf Of shawn bright
> > Sent: Friday, January 05, 2007 10:18 AM
> > To: tutor-python
> > Subject: [Tutor] need help with sending email
> >
> > lo there all.
> >
> > i am in a tight spot because i need to send an email that it
> > mime encoded plain-text ( not html or anything )
> > no attachements, no images, just text from a string. like
> > message = 'some message'
> > all the tutorials i find out there, and the cookbook recipies
> > are for sending multipart messages, attachments, etc..
> > this needs to be simple, but needs to be able to reach a
> > large variety of cell phone text message receivers.
> >
> > anyone know of a good tutorial or recipe out there ?
> >
> > thanks,
> > shawn
> >
> >
> This might help:
>
> http://effbot.org/librarybook/smtplib.htm
>
> Also, the docs on smtplib:
>
> http://docs.python.org/lib/module-smtplib.html
>
> Mike
>
>
> -------------
>
>   NOTICE:  This e-mail transmission and any documents or files attached to
>   it contain information for the sole use of the above-identified
> individual or entity.
>
>   Its contents may be privileged, confidential, and exempt from disclosure
> under the law.
>   Any dissemination, distribution, or copying of this communication is
> strictly prohibited.
>
>   Please notify the sender immediately if you are not the intended
> recipient.
>
> FGNS
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070105/54d06d80/attachment.htm 

From kent37 at tds.net  Fri Jan  5 19:12:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 05 Jan 2007 13:12:05 -0500
Subject: [Tutor] Load DLL / library and run a thread from it
In-Reply-To: <11e49df10701050744o38fe5cfdo25f6205b86d5c432@mail.gmail.com>
References: <11e49df10701050744o38fe5cfdo25f6205b86d5c432@mail.gmail.com>
Message-ID: <459E94F5.4070302@tds.net>

Jorgen Bodde wrote:
> Hi Guys,
> 
> I want to make a C++ DLL that spawns a thread, and wrap this with
> Python so that a thread still runs inside the DLL, but I can access
> methods to communicate with it, and preferrably receive callbacks from
> it.
> 
> I searched the net for examples explaining concepts like this, but I
> am lost. Is this possible or is it that trivial that nobody seems to
> explain it?

These might help:
http://effbot.org/pyfaq/how-do-i-interface-to-c-objects-from-python.htm
http://effbot.org/pyfaq/writing-c-is-hard-are-there-any-alternatives.htm

Kent


From kent37 at tds.net  Fri Jan  5 19:53:28 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 05 Jan 2007 13:53:28 -0500
Subject: [Tutor] need help with sending email
In-Reply-To: <384c93600701050934rfaaa42fk70054895c123307f@mail.gmail.com>
References: <57B026980605A64F9B23484C5659E32E4C73B1@poccso.US.ad.atmel.com>
	<384c93600701050934rfaaa42fk70054895c123307f@mail.gmail.com>
Message-ID: <459E9EA8.7040701@tds.net>

shawn bright wrote:
> right, thanks, Mike.
> i can send an email fine. Some of the providers we are trying to reach 
> will reject anything that is not content type: text-plain
> 
> thats what i need to know how to add.

The first example on this page seems to do what you want:
http://docs.python.org/lib/node162.html

Kent


From chris.arndt at web.de  Fri Jan  5 20:01:08 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 05 Jan 2007 20:01:08 +0100
Subject: [Tutor] python web dev
In-Reply-To: <c7c6f3bc0701050757u66edaed2vbbf59792fc6049b5@mail.gmail.com>
References: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>	<8c7f10c60701040825q53ec7ffp90ebf89b16a7863c@mail.gmail.com>
	<c7c6f3bc0701050757u66edaed2vbbf59792fc6049b5@mail.gmail.com>
Message-ID: <459EA074.6010004@web.de>

OkaMthembo schrieb:> i think id feel more confortable with a framework thatd
provide a basic
> MVC architecture and leave me to roll my own SQL etc, not one that will
> generate half a project for me.

With TurboGears you're not bound to SQLObject or SQLAlchemy. You can roll your
own database access layer if you want or use a third-party one. You just define
your DAO or functions in model.py. Of course you can't use CatWalk (model
admin, support SQLObject only anyway) and "tg-admin sql" (command line database
admin tool) then.

Chris

From chris.arndt at web.de  Fri Jan  5 20:11:11 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 05 Jan 2007 20:11:11 +0100
Subject: [Tutor] need help with sending email
In-Reply-To: <384c93600701050918r533d7193k7580925064a9637b@mail.gmail.com>
References: <384c93600701050918r533d7193k7580925064a9637b@mail.gmail.com>
Message-ID: <459EA2CF.2080101@web.de>

shawn bright schrieb:
> lo there all.
> 
> i am in a tight spot because i need to send an email that it mime
> encoded plain-text ( not html or anything )
> 
> anyone know of a good tutorial or recipe out there ?

Simplified example from http://www.python.org/doc/current/lib/node162.html:

# Import the email modules we'll need
from email.MIMEText import MIMEText

# Create a text/plain message
msg = MIMEText("Hello World!")

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'This is a test message'
msg['From'] = 'me'
msg['To'] = 'you'

# Print string repreentation of message
print msg.as_string()


Outputs:

Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: This is a test message
From: me
To: you

Hello World!

From wescpy at gmail.com  Fri Jan  5 20:18:15 2007
From: wescpy at gmail.com (wesley chun)
Date: Fri, 5 Jan 2007 11:18:15 -0800
Subject: [Tutor] python web dev
In-Reply-To: <c7c6f3bc0701050757u66edaed2vbbf59792fc6049b5@mail.gmail.com>
References: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
	<8c7f10c60701040825q53ec7ffp90ebf89b16a7863c@mail.gmail.com>
	<c7c6f3bc0701050757u66edaed2vbbf59792fc6049b5@mail.gmail.com>
Message-ID: <78b3a9580701051118u70dc321cs1ab9547e9d089402@mail.gmail.com>

> has anybody run a python web app under lighttpd?

i currently use this at work (on linux/centOS)... we're using FastCGI
with ligHTTPD via the WSGI-compliant fcgi.py module which can be found
all over, but the main source comes in the FLUP pkg found at
http://www.saddi.com/software/flup/

good luck!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From alan.gauld at btinternet.com  Fri Jan  5 21:02:20 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 5 Jan 2007 20:02:20 -0000
Subject: [Tutor] Python gui for file input
References: <900982.83522.qm@web58012.mail.re3.yahoo.com>
Message-ID: <enmaos$iig$1@sea.gmane.org>


"Mike Ellis" <maellis002 at yahoo.com> wrote in

> I am looking to create a simple gui interface to a small script.
> The script requires the user to input a directory.

You don't need to write an interface just use the standard
one. Of course if you want to display the result/output in
a GUI then you neeed to do some work. But if you are
happy with a console interace, or a silent application,
then its just a case of using the common dialogs:

>>> import Tkinter as tk>>> import tkFileDialog as fd>>> t = 
>>> tk.Tk()>>> t.withdraw()  # hides the Tk root window''>>> d = 
>>> fd.askdirectory() # display the dir dialog>>> print 
>>> dD:/Development>>> dir(fd)['Dialog', 'Directory', 'Open', 
>>> 'SaveAs', '_Dialog', '__builtins__', '__doc__','__file__', 
>>> '__name__', 'askdirectory', 'askopenfile', 'askopenfilename', 
>>> 'askoenfilenames', 'askopenfiles', 'asksaveasfile', 
>>> 'asksaveasfilename']>>>As you see there are a number of other 
>>> dialogs too. Try googling on their names to find example usage. I 
>>> don't know why this isn't documented in the standard library 
>>> docs!HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From cappy2112 at gmail.com  Fri Jan  5 21:50:51 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Fri, 5 Jan 2007 12:50:51 -0800
Subject: [Tutor] Tutor Digest, Vol 35, Issue 18
In-Reply-To: <mailman.6935.1168014109.32030.tutor@python.org>
References: <mailman.6935.1168014109.32030.tutor@python.org>
Message-ID: <8249c4ac0701051250p272b8d3bt8e17b82fbd4b857d@mail.gmail.com>

Message: 7
Date: Fri, 5 Jan 2007 08:04:23 -0800 (PST)
From: Mike Ellis <maellis002 at yahoo.com>
Subject: [Tutor] Python gui for file input
To: tutor at python.org
Message-ID: <900982.83522.qm at web58012.mail.re3.yahoo.com>
Content-Type: text/plain; charset="iso-8859-1"

Hi all,

I am looking to create a simple gui interface to a small script.  The script
requires the user to input a directory.  I would like to allow the user to
browse the windows file system for the desired directory rather than type in
the full path by hand.  This would operate in much the same way as any
program when you select File>Open.  Is this possible to do with python?  Can
anyone point me in the proper direction to find more info on this or perhaps
an example script using a similar feature?

Thanks for your help,
Michael

If you're looking for a simple cross-paltform solution, EasyDialogs is by
far the easiest.
http://www.averdevelopment.com/python/EasyDialogs.html

You don't have to learn anything about any GUI framework. This will invoke
the native file open browser for Windows/Linux.
2-3 lines of code max.

It will
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070105/420fd7a7/attachment.htm 

From nephish at gmail.com  Sat Jan  6 00:25:19 2007
From: nephish at gmail.com (shawn bright)
Date: Fri, 5 Jan 2007 17:25:19 -0600
Subject: [Tutor] need help with sending email
In-Reply-To: <459EA2CF.2080101@web.de>
References: <384c93600701050918r533d7193k7580925064a9637b@mail.gmail.com>
	<459EA2CF.2080101@web.de>
Message-ID: <384c93600701051525q6753cdbdoc7fd4465f57f0508@mail.gmail.com>

this is really cool. working too,
we have one provider now that it does not work with, but i think its them
this time.
thanks for your help on this

shawn

On 1/5/07, Christopher Arndt <chris.arndt at web.de> wrote:
>
> shawn bright schrieb:
> > lo there all.
> >
> > i am in a tight spot because i need to send an email that it mime
> > encoded plain-text ( not html or anything )
> >
> > anyone know of a good tutorial or recipe out there ?
>
> Simplified example from http://www.python.org/doc/current/lib/node162.html
> :
>
> # Import the email modules we'll need
> from email.MIMEText import MIMEText
>
> # Create a text/plain message
> msg = MIMEText("Hello World!")
>
> # me == the sender's email address
> # you == the recipient's email address
> msg['Subject'] = 'This is a test message'
> msg['From'] = 'me'
> msg['To'] = 'you'
>
> # Print string repreentation of message
> print msg.as_string()
>
>
> Outputs:
>
> Content-Type: text/plain; charset="us-ascii"
> MIME-Version: 1.0
> Content-Transfer-Encoding: 7bit
> Subject: This is a test message
> From: me
> To: you
>
> Hello World!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070105/9bc37538/attachment.htm 

From raistlen117 at msn.com  Sat Jan  6 00:43:56 2007
From: raistlen117 at msn.com (Raven Of Night Raven Of Night)
Date: Fri, 05 Jan 2007 15:43:56 -0800
Subject: [Tutor] python dictionaries
Message-ID: <BAY108-F34D4353E7ACCA79224BAC6E8BF0@phx.gbl>

Hi, there was this two step program I was working on but i can only complete 
the first step.

- - Write a Who's Your Daddy? program that lets the user enter the name of 
the male and produces the name of his father. Allow the user to add, 
replace, and delete father son pairs. The program should also allow the user 
to get a list of all son, fathers, or father son pairs.

I made a dictionary:
family = { "Wane Wilright" : "Dan Wilright",
           "Michal Zheng" : "Tsu Zheng",
           "Art Core" : "Vandalee Core",
           "John Wane" : "Calvin Wane" }

and was able to complete the rest of the program.


Then I was asked to improve the program:
- - Improve the Who's Your Daddy program by adding a choice that lets the 
user enter a name and get back a grandfather. Your program should still use 
one dictionary of son-father pairs. Make sure to include several generatios 
in your dictionary so that a match can be found.

I don't understand, dictionarys only allow two elements so how can you 
include several generations in the dictinoary... could you perhaps put a 
dictinoary inside a dictionary? I don't understand how you would do the 
second part.

_________________________________________________________________
The MSN Entertainment Guide to Golden Globes is here.  Get all the scoop. 
http://tv.msn.com/tv/globes2007/?icid=nctagline2


From adam.jtm30 at gmail.com  Sat Jan  6 01:02:22 2007
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Sat, 6 Jan 2007 00:02:22 +0000
Subject: [Tutor] python dictionaries
In-Reply-To: <BAY108-F34D4353E7ACCA79224BAC6E8BF0@phx.gbl>
References: <BAY108-F34D4353E7ACCA79224BAC6E8BF0@phx.gbl>
Message-ID: <be4fbf920701051602t2ff3fb74m30eb7b9d58426683@mail.gmail.com>

On 05/01/07, Raven Of Night Raven Of Night <raistlen117 at msn.com> wrote:
>
> Hi, there was this two step program I was working on but i can only
> complete
> the first step.
>
> - - Write a Who's Your Daddy? program that lets the user enter the name of
> the male and produces the name of his father. Allow the user to add,
> replace, and delete father son pairs. The program should also allow the
> user
> to get a list of all son, fathers, or father son pairs.
>
> I made a dictionary:
> family = { "Wane Wilright" : "Dan Wilright",
>            "Michal Zheng" : "Tsu Zheng",
>            "Art Core" : "Vandalee Core",
>            "John Wane" : "Calvin Wane" }
>
> and was able to complete the rest of the program.
>
>
> Then I was asked to improve the program:
> - - Improve the Who's Your Daddy program by adding a choice that lets the
> user enter a name and get back a grandfather. Your program should still
> use
> one dictionary of son-father pairs. Make sure to include several
> generatios
> in your dictionary so that a match can be found.
>
> I don't understand, dictionarys only allow two elements so how can you
> include several generations in the dictinoary... could you perhaps put a
> dictinoary inside a dictionary? I don't understand how you would do the
> second part.


Hopefully this will make sense to you as I don't want to give the whole game
away.
A grandfather is just a father's father. If you don't get it still then I'll
make it a bit
more obvious.
HTH,
Adam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070106/df0a537b/attachment.html 

From alan.gauld at btinternet.com  Sat Jan  6 01:25:57 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 6 Jan 2007 00:25:57 -0000
Subject: [Tutor] python dictionaries
References: <BAY108-F34D4353E7ACCA79224BAC6E8BF0@phx.gbl>
Message-ID: <enmq75$d35$1@sea.gmane.org>


"Raven Of Night Raven Of Night" <raistlen117 at msn.com> wrote

> I don't understand, dictionarys only allow two elements so how can 
> you
> include several generations in the dictinoary...

Grandfather -> Father -> Son

can be expressed as two pairs:

Grandfather -> Father
Father -> Son

Now you can put it in your dictionary.

You only need to figure out how to join the pairs back into
a triple again...

> could you perhaps put a dictinoary inside a dictionary?

You can, but you don;t need to. And, assuming its a homework,
I don't think thats what you are expected to do here.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Sat Jan  6 01:29:12 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 6 Jan 2007 00:29:12 -0000
Subject: [Tutor] Python gui for file input
References: <900982.83522.qm@web58012.mail.re3.yahoo.com>
	<enmaos$iig$1@sea.gmane.org>
Message-ID: <enmqd8$dhk$1@sea.gmane.org>

Apologies for the wird formatting, looks like the news reader
got confused by Pythons chevrons and thought it was a thread!
Hopefully spacing will fix it...

"Alan Gauld" <alan.gauld at btinternet.com> wrote

>>> import Tkinter as tk

>>> import tkFileDialog as fd

>>> t = >>>> tk.Tk()

>>> t.withdraw()  # hides the Tk root window''

>>> d = fd.askdirectory() # display the dir dialog

>>> print  d
D:/Development

>>> dir(fd)
['Dialog', 'Directory', 'Open', 'SaveAs', '_Dialog', '__builtins__',
'__doc__','__file__',  '__name__', 'askdirectory', 'askopenfile',
'askopenfilename',  'askoenfilenames', 'askopenfiles', 
'asksaveasfile',
 'asksaveasfilename']




From Barry.Carroll at psc.com  Sat Jan  6 01:49:08 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Fri, 5 Jan 2007 16:49:08 -0800
Subject: [Tutor] python dictionaries
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A65@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> Message: 7
> Date: Fri, 05 Jan 2007 15:43:56 -0800
> From: "Raven Of Night Raven Of Night" <raistlen117 at msn.com>
> Subject: [Tutor] python dictionaries
> To: tutor at python.org
> Message-ID: <BAY108-F34D4353E7ACCA79224BAC6E8BF0 at phx.gbl>
> Content-Type: text/plain; format=flowed
> 
> Hi, there was this two step program I was working on but i can only
> complete
> the first step.
> 
> - - Write a Who's Your Daddy? program that lets the user enter the
name of
> the male and produces the name of his father. Allow the user to add,
> replace, and delete father son pairs. The program should also allow
the
> user
> to get a list of all son, fathers, or father son pairs.
> 
> I made a dictionary:
> family = { "Wane Wilright" : "Dan Wilright",
>            "Michal Zheng" : "Tsu Zheng",
>            "Art Core" : "Vandalee Core",
>            "John Wane" : "Calvin Wane" }
> 
> and was able to complete the rest of the program.
> 
> 
> Then I was asked to improve the program:
> - - Improve the Who's Your Daddy program by adding a choice that lets
the
> user enter a name and get back a grandfather. Your program should
still
> use
> one dictionary of son-father pairs. Make sure to include several
> generatios
> in your dictionary so that a match can be found.
> 
> I don't understand, dictionarys only allow two elements so how can you
> include several generations in the dictinoary... could you perhaps put
a
> dictinoary inside a dictionary? I don't understand how you would do
the
> second part.
> 
> _________________________________________________________________
> The MSN Entertainment Guide to Golden Globes is here.  Get all the
scoop.
> http://tv.msn.com/tv/globes2007/?icid=nctagline2
> 
> 
> 
> ------------------------------
> 
> Message: 8
> Date: Sat, 6 Jan 2007 00:02:22 +0000
> From: "Adam Bark" <adam.jtm30 at gmail.com>
> Subject: Re: [Tutor] python dictionaries
> To: "Raven Of Night Raven Of Night" <raistlen117 at msn.com>
> Cc: tutor at python.org
> Message-ID:
> 	<be4fbf920701051602t2ff3fb74m30eb7b9d58426683 at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> On 05/01/07, Raven Of Night Raven Of Night <raistlen117 at msn.com>
wrote:
> >
> > Hi, there was this two step program I was working on but i can only
> > complete
> > the first step.
> >
> > - - Write a Who's Your Daddy? program that lets the user enter the
name
> of
> > the male and produces the name of his father. Allow the user to add,
> > replace, and delete father son pairs. The program should also allow
the
> > user
> > to get a list of all son, fathers, or father son pairs.
> >
> > I made a dictionary:
> > family = { "Wane Wilright" : "Dan Wilright",
> >            "Michal Zheng" : "Tsu Zheng",
> >            "Art Core" : "Vandalee Core",
> >            "John Wane" : "Calvin Wane" }
> >
> > and was able to complete the rest of the program.
> >
> >
> > Then I was asked to improve the program:
> > - - Improve the Who's Your Daddy program by adding a choice that
lets
> the
> > user enter a name and get back a grandfather. Your program should
still
> > use
> > one dictionary of son-father pairs. Make sure to include several
> > generatios
> > in your dictionary so that a match can be found.
> >
> > I don't understand, dictionarys only allow two elements so how can
you
> > include several generations in the dictinoary... could you perhaps
put a
> > dictinoary inside a dictionary? I don't understand how you would do
the
> > second part.
> 
> 
> Hopefully this will make sense to you as I don't want to give the
whole
> game
> away.
> A grandfather is just a father's father. If you don't get it still
then
> I'll
> make it a bit
> more obvious.
> HTH,
> Adam.
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
>
http://mail.python.org/pipermail/tutor/attachments/20070106/df0a537b/att
ac
> hment.htm

Think of it this way:

	My name is Barry.
	My father's name is Jim.
	Jim's father's name is Walt (***my grandfather***).

How can you use your dictionary to emulate that?

Good luck.

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




From rabidpoobear at gmail.com  Sun Jan  7 05:23:59 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sat, 06 Jan 2007 22:23:59 -0600
Subject: [Tutor] Tutor Digest, Vol 35, Issue 18
In-Reply-To: <8249c4ac0701051250p272b8d3bt8e17b82fbd4b857d@mail.gmail.com>
References: <mailman.6935.1168014109.32030.tutor@python.org>
	<8249c4ac0701051250p272b8d3bt8e17b82fbd4b857d@mail.gmail.com>
Message-ID: <45A075DF.3070000@gmail.com>

Tony Cappellini wrote:
> Message: 7
> Date: Fri, 5 Jan 2007 08:04:23 -0800 (PST)
> From: Mike Ellis <maellis002 at yahoo.com <mailto:maellis002 at yahoo.com>>
> Subject: [Tutor] Python gui for file input
> To: tutor at python.org <mailto:tutor at python.org>
> Message-ID: < 900982.83522.qm at web58012.mail.re3.yahoo.com 
> <mailto:900982.83522.qm at web58012.mail.re3.yahoo.com>>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hi all,
>
> I am looking to create a simple gui interface to a small script.  The 
> script requires the user to input a directory.  I would like to allow 
> the user to browse the windows file system for the desired directory 
> rather than type in the full path by hand.  This would operate in much 
> the same way as any program when you select File>Open.  Is this 
> possible to do with python?  Can anyone point me in the proper 
> direction to find more info on this or perhaps an example script using 
> a similar feature?
>
> Thanks for your help,
> Michael
>
> If you're looking for a simple cross-paltform solution, EasyDialogs is 
> by far the easiest.
> http://www.averdevelopment.com/python/EasyDialogs.html
>
> You don't have to learn anything about any GUI framework. This will 
> invoke the native file open browser for Windows/Linux.
> 2-3 lines of code max.
>
> It will
>   
What does 'It will' mean?
Is this an incomplete thought?
A response to a response?
Or part of the original response?
  is it a question or a statement?
This is what all those '>' that your mail client puts before the replies 
are for.
I can't follow what's happening here.
Not that it really matters, but I was curious why the e-mail was 
formatted this way.
Sorry for being a stickler,
-Luke

From rabidpoobear at gmail.com  Sun Jan  7 05:25:59 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sat, 06 Jan 2007 22:25:59 -0600
Subject: [Tutor] need help with sending email
In-Reply-To: <384c93600701051525q6753cdbdoc7fd4465f57f0508@mail.gmail.com>
References: <384c93600701050918r533d7193k7580925064a9637b@mail.gmail.com>	<459EA2CF.2080101@web.de>
	<384c93600701051525q6753cdbdoc7fd4465f57f0508@mail.gmail.com>
Message-ID: <45A07657.8030103@gmail.com>

shawn bright wrote:
> this is really cool. working too,
> we have one provider now that it does not work with, but i think its 
> them this time.
> thanks for your help on this
Just wondering -
do you guys buy SMS messages or is there some way to communicate with 
text message users for free?
Thanks,
-Luke

From chris.arndt at web.de  Sat Jan  6 18:03:00 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Sat, 06 Jan 2007 18:03:00 +0100
Subject: [Tutor] need help with sending email
In-Reply-To: <45A07657.8030103@gmail.com>
References: <384c93600701050918r533d7193k7580925064a9637b@mail.gmail.com>	<459EA2CF.2080101@web.de>	<384c93600701051525q6753cdbdoc7fd4465f57f0508@mail.gmail.com>
	<45A07657.8030103@gmail.com>
Message-ID: <459FD644.9070805@web.de>

Luke Paireepinart schrieb:
> Just wondering -
> do you guys buy SMS messages or is there some way to communicate with 
> text message users for free?

There are some providers that give you a certain amount of SMS per month for
free, even if you only have a prepaid SIM card. O2 Ireland is an example. But I
guess the terms of service would forbid to use the web interfaces programmatically.

But I guess Shawn was talking about another way: most mobile phone providers
have an Email-to-SMS gateway where the receiver pays for emails to his
address/phone and therefore needs to activate it.

Chris

From alan.gauld at btinternet.com  Sat Jan  6 18:56:45 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 6 Jan 2007 17:56:45 -0000
Subject: [Tutor] need help with sending email
References: <384c93600701050918r533d7193k7580925064a9637b@mail.gmail.com>	<459EA2CF.2080101@web.de><384c93600701051525q6753cdbdoc7fd4465f57f0508@mail.gmail.com>
	<45A07657.8030103@gmail.com>
Message-ID: <enonpe$h2s$1@sea.gmane.org>

"Luke Paireepinart" <rabidpoobear at gmail.com> wrote

> do you guys buy SMS messages or is there some way to communicate 
> with
> text message users for free?

Just to blow my own companies trumpet for once, if you sign
up to our new Web21C SDK you get a certain number of SMS
messages/month for free as part of the sign up deal (which is
also free).

The SDK is in C# :-(
Although it should be possible to use it from IronPython with
relatively little work.

They are working on a Java version which will work from Jython,
and I think is due "shortly".

http://sdk.bt.com

This project is the first of several SDK initiatives to make the
new VoIP core network available to developers to create the
next generation of communication applications.

This page lists whats available:
http://sdk.bt.com/Services/tabid/40/Default.aspx

Hope its of interest to someone...


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From rdm at rcblue.com  Sat Jan  6 19:40:40 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 06 Jan 2007 10:40:40 -0800
Subject: [Tutor] Need help with rewriting script to use Decimal module
In-Reply-To: <Pine.LNX.4.44.0701042304480.30388-100000@violet.rahul.net>
References: <7.0.1.0.2.20070103234257.06dcc0c0@rcblue.com>
	<Pine.LNX.4.44.0701042304480.30388-100000@violet.rahul.net>
Message-ID: <7.0.1.0.2.20070106100628.05c2fa78@rcblue.com>

At 11:21 PM 1/4/2007, Terry Carroll wrote:
>On Wed, 3 Jan 2007, Dick Moores wrote:
>
> > Be that as it may, farey() is an amazing program.
>
>Not to beat this subject to death, but the comment at the bottom of
>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317 about
>continued fractions piqued my interest.  I'm no mathematician, but I
>encountered continued fractions a long time ago and was fascinated by
>them.  So I read the URL pointed to,
>http://mathworld.wolfram.com/ContinuedFraction.html , and came up with the
>following:
>
>#####################################################
>
>def cf(x, tol=0.0001, Trace=False):
>     """
>     Calculate rational approximation of x to within tolerance of tol;
>     returns a tuple consisting of numerator and denominator p/q
>     Trace=True causes iterated results to be shown
>     """
>     a, r, p, q = [], [], [], []
>     Done = False
>     n = 0
>     if Trace: print "x:%f tol:%f" % (x, tol)
>     while not Done:
>         a.append(None)
>         r.append(None)
>         p.append(None)
>         q.append(None)
>         if n == 0: r[n] = x
>         else: r[n] = 1/(r[n-1]-a[n-1])
>         a[n] = int(r[n])
>         if n == 0:
>             p[n] = a[0]
>             q[n] = 1
>         elif n ==1:
>             p[n] = a[n]*p[n-1] + 1
>             q[n] = a[n]
>         else:
>             p[n] = a[n]*p[n-1] + p[n-2]
>             q[n] = a[n]*q[n-1] + q[n-2]
>         if Trace:
>             print "n:%d a:%d p:%d q:%d approx:%f" % \
>                   (n, a[n], p[n], q[n], float(p[n])/q[n])
>         if abs(float(p[n])/q[n] - x) < tol:
>             Done = True
>         num = p[n]; denom = q[n]
>         n += 1
>     return (num, denom)
>
>#####################################################
>
>Here's a result for pi:
>
> >>> print cf(3.14159265357989,0.0000001, Trace=True)
>x:3.141593 tol:0.000000
>n:0 a:3 p:3 q:1 approx:3.000000
>n:1 a:7 p:22 q:7 approx:3.142857
>n:2 a:15 p:333 q:106 approx:3.141509
>n:3 a:1 p:355 q:113 approx:3.141593
>n:4 a:292 p:103993 q:33102 approx:3.141593
>(103993, 33102)
>
>i.e., the first 5 approximations it came up with were 3/1, 22/7, 333/106,
>355/113 and a whopping 103993/33102.
>
>For the 0.36 example you used earlier:
>
> >>> print cf(0.36, .01, Trace= True)
>x:0.360000 tol:0.010000
>n:0 a:0 p:0 q:1 approx:0.000000
>n:1 a:2 p:1 q:2 approx:0.500000
>n:2 a:1 p:1 q:3 approx:0.333333
>n:3 a:3 p:4 q:11 approx:0.363636
>(4, 11)
> >>>
>
>it went right from 1/3 to 4/11 (0.363636), skipping the 3/8 (0.375) option
>from the farey series.
>
>But this continued fraction algorithm is ill-suited to answer the question
>"what's the closest fraction with a denominator < N", because it doesn't
>try to find that, it jumps further ahead with each iteration.
>
>Anyway, I thought you might find it interesting based on our discussion.

Terry,

Well, I have to admit I don't understand your code at all. But I see it works.

I modified one of my functions of frac.py, and came up with

===============================================
from __future__ import division
import time, psyco

psyco.full()

def d(number):
     import decimal
     decimal.getcontext().prec = 16
     return decimal.Decimal(str(number))

def bestFracForMinimumError(decimal, minimumError):
     denom = 0
     smallestError = 10
     count = 0
     while True:
         denom += 1
         num = int(round(d(decimal) * d(denom)))
         error = abs((((d(num)) / d(denom)) - d(decimal)) / 
d(decimal)) * d(100)
         if d(error) <= d(smallestError):
             count += 1
             smallestError = d(error)
             q = d(num)/d(denom)
             print "%d/%d = %s has error of %s per cent" % (num, 
denom, q, smallestError)
         if d(smallestError) <= d(minimumError):
             print "count is", count
             break

=====================================================================

You can see the results of both
bestFracForMinimumError(3.14159265357989, 0.00000002)

(BTW your pi is a bit off but I used yours, instead of math.pi, which 
is 3.1415926535897931 . Also, I needed 0.00000002 in order to produce 
your 103993/33102)

and

bestFracForMinimumError(.36, .01)

at <http://www.rcblue.com/Python/PartOfReplyToTerryOnTutorList.txt>

Dick



From rdm at rcblue.com  Sat Jan  6 20:04:44 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 06 Jan 2007 11:04:44 -0800
Subject: [Tutor] Need help with rewriting script to use Decimal  module
In-Reply-To: <7.0.1.0.2.20070106100628.05c2fa78@rcblue.com>
References: <7.0.1.0.2.20070103234257.06dcc0c0@rcblue.com>
	<Pine.LNX.4.44.0701042304480.30388-100000@violet.rahul.net>
	<7.0.1.0.2.20070106100628.05c2fa78@rcblue.com>
Message-ID: <7.0.1.0.2.20070106110050.0a9416c8@rcblue.com>

At 10:40 AM 1/6/2007, Dick Moores wrote:
>At 11:21 PM 1/4/2007, Terry Carroll wrote:
> >On Wed, 3 Jan 2007, Dick Moores wrote:
> >
> > > Be that as it may, farey() is an amazing program.
> >
> >Not to beat this subject to death, but the comment at the bottom of
> >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317 about
> >continued fractions piqued my interest.  I'm no mathematician, but I
> >encountered continued fractions a long time ago and was fascinated by
> >them.  So I read the URL pointed to,
> >http://mathworld.wolfram.com/ContinuedFraction.html , and came up with the
> >following:
> >
> >#####################################################
> >
> >def cf(x, tol=0.0001, Trace=False):
> >     """
> >     Calculate rational approximation of x to within tolerance of tol;
> >     returns a tuple consisting of numerator and denominator p/q
> >     Trace=True causes iterated results to be shown
> >     """
> >     a, r, p, q = [], [], [], []
> >     Done = False
> >     n = 0
> >     if Trace: print "x:%f tol:%f" % (x, tol)
> >     while not Done:
> >         a.append(None)
> >         r.append(None)
> >         p.append(None)
> >         q.append(None)
> >         if n == 0: r[n] = x
> >         else: r[n] = 1/(r[n-1]-a[n-1])
> >         a[n] = int(r[n])
> >         if n == 0:
> >             p[n] = a[0]
> >             q[n] = 1
> >         elif n ==1:
> >             p[n] = a[n]*p[n-1] + 1
> >             q[n] = a[n]
> >         else:
> >             p[n] = a[n]*p[n-1] + p[n-2]
> >             q[n] = a[n]*q[n-1] + q[n-2]
> >         if Trace:
> >             print "n:%d a:%d p:%d q:%d approx:%f" % \
> >                   (n, a[n], p[n], q[n], float(p[n])/q[n])
> >         if abs(float(p[n])/q[n] - x) < tol:
> >             Done = True
> >         num = p[n]; denom = q[n]
> >         n += 1
> >     return (num, denom)
> >
> >#####################################################
> >
> >Here's a result for pi:
> >
> > >>> print cf(3.14159265357989,0.0000001, Trace=True)
> >x:3.141593 tol:0.000000
> >n:0 a:3 p:3 q:1 approx:3.000000
> >n:1 a:7 p:22 q:7 approx:3.142857
> >n:2 a:15 p:333 q:106 approx:3.141509
> >n:3 a:1 p:355 q:113 approx:3.141593
> >n:4 a:292 p:103993 q:33102 approx:3.141593
> >(103993, 33102)
> >
> >i.e., the first 5 approximations it came up with were 3/1, 22/7, 333/106,
> >355/113 and a whopping 103993/33102.
> >
> >For the 0.36 example you used earlier:
> >
> > >>> print cf(0.36, .01, Trace= True)
> >x:0.360000 tol:0.010000
> >n:0 a:0 p:0 q:1 approx:0.000000
> >n:1 a:2 p:1 q:2 approx:0.500000
> >n:2 a:1 p:1 q:3 approx:0.333333
> >n:3 a:3 p:4 q:11 approx:0.363636
> >(4, 11)
> > >>>
> >
> >it went right from 1/3 to 4/11 (0.363636), skipping the 3/8 (0.375) option
> >from the farey series.
> >
> >But this continued fraction algorithm is ill-suited to answer the question
> >"what's the closest fraction with a denominator < N", because it doesn't
> >try to find that, it jumps further ahead with each iteration.
> >
> >Anyway, I thought you might find it interesting based on our discussion.
>
>Terry,
>
>Well, I have to admit I don't understand your code at all. But I see it works.
>
>I modified one of my functions of frac.py, and came up with
>
>===============================================
>from __future__ import division
>import time, psyco
>
>psyco.full()
>
>def d(number):
>      import decimal
>      decimal.getcontext().prec = 16
>      return decimal.Decimal(str(number))
>
>def bestFracForMinimumError(decimal, minimumError):
>      denom = 0
>      smallestError = 10
>      count = 0
>      while True:
>          denom += 1
>          num = int(round(d(decimal) * d(denom)))
>          error = abs((((d(num)) / d(denom)) - d(decimal)) /
>d(decimal)) * d(100)
>          if d(error) <= d(smallestError):
>              count += 1
>              smallestError = d(error)
>              q = d(num)/d(denom)
>              print "%d/%d = %s has error of %s per cent" % (num,
>denom, q, smallestError)
>          if d(smallestError) <= d(minimumError):
>              print "count is", count
>              break
>
>=====================================================================

I just realized that I had used "<=" in my code where I should have 
used "<".  So after make these changes, the results also changed, of 
course. See them at 
http://www.rcblue.com/Python/PartOfReplyToTerryOnTutorList-2.txt

Dick

>You can see the results of both
>bestFracForMinimumError(3.14159265357989, 0.00000002)
>
>(BTW your pi is a bit off but I used yours, instead of math.pi, which
>is 3.1415926535897931 . Also, I needed 0.00000002 in order to produce
>your 103993/33102)
>
>and
>
>bestFracForMinimumError(.36, .01)
>
>at <http://www.rcblue.com/Python/PartOfReplyToTerryOnTutorList.txt>




From lists at mostrom.pp.se  Sat Jan  6 22:40:27 2007
From: lists at mostrom.pp.se (=?UTF-8?Q?Jan_Erik_Mostr=C3=B6?= =?UTF-8?Q?m?=)
Date: Sat,  6 Jan 2007 22:40:27 +0100
Subject: [Tutor] Question about ConfigParser
Message-ID: <b02020005-1048-ppc-7B2AF45BFCF5429B9A1FA03862F8568A@Infinitum.local>

I'm trying to use ConfigParser for the first time and I'm 
missing something. I have this code

import ConfigParser
import datetime

conf = ConfigParser.ConfigParser()

conf.add_section('general')
conf.set( 'general', 'revision', 0 )
conf.set( 'general', 'date', 
datetime.datetime.now().strftime("%Y-%m-%d") )
conf.set( 'general', 'currentsetname', '' )
conf.set( 'general', 'incrementalcount', 0 )
conf.add_section( "Hello world" )
conf.set( "Hello world", 'apa', 3298 )

print conf.sections()
print conf.items('general')

#for debug_repos in conf.sections():
#   print debug_repos #, conf.items( debug_repos )


When I run this I get the following result

['Hello world', 'general']
Traceback (most recent call last):
   File "backup.py", line 15, in <module>
     print conf.items('general')
   File 
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", 
line 557, in items
     for option in options]
   File 
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", 
line 565, in _interpolate
     if "%(" in value:
TypeError: argument of type 'int' is not iterable

What am I missing with the items call?

                     jem

From pytutmail at gmail.com  Sat Jan  6 22:56:04 2007
From: pytutmail at gmail.com (Toon Pieton)
Date: Sat, 6 Jan 2007 22:56:04 +0100
Subject: [Tutor] Floats and rounding down
Message-ID: <7c3104d20701061356p1924547dkaf0ee3bd0165a259@mail.gmail.com>

Hey all!

A very simple question. I'm writing a simple program which does some
calculations with money. I use floats for that, and yes, I know that floats
arent as perfect as decimals, but its doesnt have to be a perfect program.

I have, however, run into a "visual" problem.

Something like temp = '$' + str(round(x,2)) will make x = $1.537 read as
$1.54. That's perfect. However, when x = 1.3, or x = 5.0, it will display
just that: $1.3 or $5. I don't like that - I wan't 1.30 and 5.00, because
that looks much more clean and homogeneous.

Is there any - not to complicated - way to do that?

Thanks in advance for reading and caring!
Toon Pieton
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070106/ca88c8f1/attachment-0001.html 

From ajkadri at googlemail.com  Sat Jan  6 23:23:39 2007
From: ajkadri at googlemail.com (Asrarahmed Kadri)
Date: Sat, 6 Jan 2007 22:23:39 +0000
Subject: [Tutor] Query about using Pmw entry widget...
Message-ID: <b4e894c70701061423q45b70c5dwc781d0bc39c583fb@mail.gmail.com>

Hello Folks,

I am using Pmw mdoule to develop a User interface and in that I am using
entry widget.

Can some one help me how to add validation : only integers are allowed and
minimum value should be 1.

timeInterval = Pmw.EntryField(label_text='Time Interval(in
sec.):',labelpos='w',validate = 'numeric')

Also I want to validate date and time? I know that there is a way to do it
but I dont know the exact syntax..

Please help with the example.

Regards,
Asrarahmed

-- 
To HIM you shall return.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070106/83cd2714/attachment.htm 

From dkuhlman at rexx.com  Sun Jan  7 00:26:45 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sat, 6 Jan 2007 15:26:45 -0800
Subject: [Tutor] Question about ConfigParser
In-Reply-To: <b02020005-1048-ppc-7B2AF45BFCF5429B9A1FA03862F8568A@Infinitum.local>
References: <b02020005-1048-ppc-7B2AF45BFCF5429B9A1FA03862F8568A@Infinitum.local>
Message-ID: <20070106232645.GA49263@cutter.rexx.com>

On Sat, Jan 06, 2007 at 10:40:27PM +0100, Jan Erik Mostr??m wrote:
> I'm trying to use ConfigParser for the first time and I'm 
> missing something. I have this code
> 
> import ConfigParser
> import datetime
> 
> conf = ConfigParser.ConfigParser()
> 
> conf.add_section('general')
> conf.set( 'general', 'revision', 0 )
> conf.set( 'general', 'date', 
> datetime.datetime.now().strftime("%Y-%m-%d") )
> conf.set( 'general', 'currentsetname', '' )
> conf.set( 'general', 'incrementalcount', 0 )
> conf.add_section( "Hello world" )
> conf.set( "Hello world", 'apa', 3298 )
> 
> print conf.sections()
> print conf.items('general')
> 
> #for debug_repos in conf.sections():
> #   print debug_repos #, conf.items( debug_repos )
> 
> 
> When I run this I get the following result
> 
> ['Hello world', 'general']
> Traceback (most recent call last):
>    File "backup.py", line 15, in <module>
>      print conf.items('general')
>    File 
> "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", 
> line 557, in items
>      for option in options]
>    File 
> "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", 
> line 565, in _interpolate
>      if "%(" in value:
> TypeError: argument of type 'int' is not iterable
> 
> What am I missing with the items call?

Here is a clue -- If you write out your configuration to a file
with something like:

    conf.write(sys.stdout)

and store it in a file.  Then, if you read it in, all seems to work
well.  For example, the following function:

    def test2():
        conf = ConfigParser.ConfigParser()
        conf.read('test1.conf')
        print 'options -- general:', conf.options('general')
        opt1 = conf.get('general', 'date')
        print 'opt1:', opt1
        print conf.items('general')

executes without error.  Can you guess why?

Note that in your original code, the default values for some of
your options have type int.  If you change those to strings, then
the error goes away.  For example, change:

    conf.set( 'general', 'revision', 0 )

to:

    conf.set( 'general', 'revision', "0" )

Writing it to a file does this conversion and hides the error.

It's sort of hidden, but note the restriction to string values in
the docs on the set method:

    set(section, option, value)
      If the given section exists, set the given option to the specified
      value; otherwise raise NoSectionError. While it is possible to use
      RawConfigParser (or ConfigParser with raw parameters set to true)
      for internal storage of non-string values, full functionality
      (including interpolation and output to files) can only be achieved
      using string values. New in version 1.6.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From alan.gauld at btinternet.com  Sun Jan  7 01:23:42 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 7 Jan 2007 00:23:42 -0000
Subject: [Tutor] Floats and rounding down
References: <7c3104d20701061356p1924547dkaf0ee3bd0165a259@mail.gmail.com>
Message-ID: <enpeie$m9f$1@sea.gmane.org>


"Toon Pieton" <pytutmail at gmail.com> wrote

> Something like temp = '$' + str(round(x,2)) will make x = $1.537 
> read as
> $1.54. That's perfect. However, when x = 1.3, or x = 5.0, it will 
> display
> just that: $1.3 or $5. I don't like that - I wan't 1.30 and 5.00, 
> because
> that looks much more clean and homogeneous.
>
> Is there any - not to complicated - way to do that?

Yes, use string formatting.

>>> print "$%0.2f" % 1.3
$1.30

There are a wealth of other variations, worth studying in detail.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From rabidpoobear at gmail.com  Sun Jan  7 15:45:40 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 07 Jan 2007 08:45:40 -0600
Subject: [Tutor] Query about using Pmw entry widget...
In-Reply-To: <b4e894c70701061423q45b70c5dwc781d0bc39c583fb@mail.gmail.com>
References: <b4e894c70701061423q45b70c5dwc781d0bc39c583fb@mail.gmail.com>
Message-ID: <45A10794.1090101@gmail.com>

Asrarahmed Kadri wrote:
> Hello Folks,
>  
> I am using Pmw mdoule to develop a User interface and in that I am 
> using entry widget.
>  
> Can some one help me how to add validation : only integers are allowed 
> and minimum value should be 1.
>  
> timeInterval = Pmw.EntryField(label_text='Time Interval(in 
> sec.):',labelpos='w',validate = 'numeric')
>  
> Also I want to validate date and time? I know that there is a way to 
> do it but I dont know the exact syntax..
Asrarahmed -
 From what I remember (PMW is just an extension of TKinter so this 
should apply here)
it's a lot easier to validate the input when you're using it instead of 
trying to restrict their input.
I.E. when they hit 'submit' give them a little warning saying 'sorry, 
you can't submit unless you have an integer in field "fieldname" .....'
That's most likely the easiest way to do this.
If you just google for tkinter validate entry  you should come up with 
the other way, IIRC (where they can't input incorrect values).
HTH,
-Luke.
>
> -- 
> To HIM you shall return.
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From kent37 at tds.net  Sun Jan  7 06:57:29 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 07 Jan 2007 00:57:29 -0500
Subject: [Tutor] Floats and rounding down
In-Reply-To: <enpeie$m9f$1@sea.gmane.org>
References: <7c3104d20701061356p1924547dkaf0ee3bd0165a259@mail.gmail.com>
	<enpeie$m9f$1@sea.gmane.org>
Message-ID: <45A08BC9.2090008@tds.net>

Alan Gauld wrote:
> "Toon Pieton" <pytutmail at gmail.com> wrote
> 
>> Something like temp = '$' + str(round(x,2)) will make x = $1.537 
>> read as
>> $1.54. That's perfect. However, when x = 1.3, or x = 5.0, it will 
>> display
>> just that: $1.3 or $5. I don't like that - I wan't 1.30 and 5.00, 
>> because
>> that looks much more clean and homogeneous.
>>
>> Is there any - not to complicated - way to do that?
> 
> Yes, use string formatting.
> 
>>>> print "$%0.2f" % 1.3
> $1.30

There is no need to round first, either:
In [1]: print '$%0.2f' % 1.537
$1.54

Kent


From stormtrooper30 at gmail.com  Sat Jan  6 20:40:55 2007
From: stormtrooper30 at gmail.com (Stormtrooper30)
Date: Sat, 6 Jan 2007 13:40:55 -0600
Subject: [Tutor] Help Installing Livewires
Message-ID: <b493a9840701061140y30b7a039ged891dada302b3ce@mail.gmail.com>

Hi

I succesfully installed pygame and then attempted to install Livewires on my
Windows laptop.  I am using Python 2.4 and when I try to call a module from
Livewires it says that "module Livewires does not exist".  I double clicked
the setup program and it displayed some text then shut off.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070106/84cc3c56/attachment.html 

From alan.gauld at btinternet.com  Sun Jan  7 09:54:31 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 7 Jan 2007 08:54:31 -0000
Subject: [Tutor] Query about using Pmw entry widget...
References: <b4e894c70701061423q45b70c5dwc781d0bc39c583fb@mail.gmail.com>
	<45A10794.1090101@gmail.com>
Message-ID: <enqcg8$p24$1@sea.gmane.org>


"Luke Paireepinart" <rabidpoobear at gmail.com> wrote

OP>> Can some one help me how to add validation : only integers are 
allowed
OP>> and minimum value should be 1.
OP>>
OP>> timeInterval = Pmw.EntryField(label_text='Time Interval(in
OP>> sec.):',labelpos='w',validate = 'numeric')

I don;t have PMW installed. I tend to use Tix now that its part
of standard Python. However Grayson says this:

"validation is [performed by a function which takes
as its first argument the entered text and returns
one of three standard values...
Pmw.OK, Pmw.ERROR, Pmw.PARTIAL"

So it seems you need

def numeric(val):
    try: float(val)
    except ValueError: return Pmw.ERROR
    else: return Pmw.OK

timeinterval = Pmw.EntryField(.....validate=numeric)

At least that's how I read it, obviously without Pmw I can't try it...

>> Also I want to validate date and time? I know that there is a way 
>> to
>> do it but I dont know the exact syntax..

I'd use a similar technique as above. parse the string and try
to create a datetime object then handle the exceptions.

Luke> it's a lot easier to validate the input when you're using it 
instead of
Luke> trying to restrict their input.

Its easier for the programmer but much worse for the user.
We should always catch erroneous input as early as possible.
Early CGI Web pages were the classic example of late error
handling and there is nothing more annoying than filling in a form,
submitting it and then being told you filled in a field wrong right
at the start!

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From rabidpoobear at gmail.com  Sun Jan  7 22:15:47 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 07 Jan 2007 15:15:47 -0600
Subject: [Tutor] Help Installing Livewires
In-Reply-To: <b493a9840701061140y30b7a039ged891dada302b3ce@mail.gmail.com>
References: <b493a9840701061140y30b7a039ged891dada302b3ce@mail.gmail.com>
Message-ID: <45A16303.2040007@gmail.com>

Stormtrooper30 wrote:
> Hi
>  
> I succesfully installed pygame and then attempted to install Livewires 
> on my Windows laptop.  I am using Python 2.4 and when I try to call a 
> module from Livewires it says that "module Livewires does not exist".  
> I double clicked the setup program and it displayed some text then 
> shut off.
Did you try importing the module first?
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From rabidpoobear at gmail.com  Sun Jan  7 22:27:16 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 07 Jan 2007 15:27:16 -0600
Subject: [Tutor] Query about using Pmw entry widget...
In-Reply-To: <enqcg8$p24$1@sea.gmane.org>
References: <b4e894c70701061423q45b70c5dwc781d0bc39c583fb@mail.gmail.com>	<45A10794.1090101@gmail.com>
	<enqcg8$p24$1@sea.gmane.org>
Message-ID: <45A165B4.5010907@gmail.com>

Alan Gauld wrote:
> "Luke Paireepinart" <rabidpoobear at gmail.com> wrote
>
> OP>> Can some one help me how to add validation : only integers are 
> allowed
> OP>> and minimum value should be 1.
> OP>>
> OP>> timeInterval = Pmw.EntryField(label_text='Time Interval(in
> OP>> sec.):',labelpos='w',validate = 'numeric')
>
> I don;t have PMW installed. I tend to use Tix now that its part
> of standard Python. However Grayson says this:
>
> "validation is [performed by a function which takes
> as its first argument the entered text and returns
> one of three standard values...
> Pmw.OK, Pmw.ERROR, Pmw.PARTIAL"
>
> So it seems you need
>
> def numeric(val):
>     try: float(val)
>     except ValueError: return Pmw.ERROR
>     else: return Pmw.OK
>
> timeinterval = Pmw.EntryField(.....validate=numeric)
>
> At least that's how I read it, obviously without Pmw I can't try it...
>
>   
>>> Also I want to validate date and time? I know that there is a way 
>>> to
>>> do it but I dont know the exact syntax..
>>>       
>
> I'd use a similar technique as above. parse the string and try
> to create a datetime object then handle the exceptions.
>
> Luke> it's a lot easier to validate the input when you're using it 
> instead of
> Luke> trying to restrict their input.
>
> Its easier for the programmer but much worse for the user.
> We should always catch erroneous input as early as possible.
> Early CGI Web pages were the classic example of late error
> handling and there is nothing more annoying than filling in a form,
> submitting it and then being told you filled in a field wrong right
> at the start!
>   

The difference between a webpage and an application here is that if the 
user enters something incorrectly,
he'll know as soon as he tries to submit it,
without having to wait for the page to reload,
and he won't lose all of his information just to go back and change one 
field.
But I guess I don't know anything about UI design.
That's why I just purchased 'The Essential Guide To User Interface 
Design' from Half-Price Books!
Yes, a bit of a strange coincidence that I bought it just today.

Anyway,
I know it's frustrating to have to go back to fix entries,
but it's also annoying to have something restrict your input.
That seems sort of like the programmer didn't want to take the time to 
have a robust user input parser :D
I think the ideal situation for me would be that whenever an entry 
widget loses focus, the validate() function is called,
and I get some kind of visual warning that my entry is incorrect.
NOT a dialog box, I hope, but some kind of red warning label next to the 
entry widget or something.
However, this doesn't work for the last entry on the page, because most 
likely focus will switch straight from the entry to the submit button,
but then the whole 'check on submit' thing would catch the error.
Basically I don't want to see an entry box that behaves differently than 
a normal entry box (only accepts integers, for example).
-Luke

> HTH,
>
>   


From alan.gauld at btinternet.com  Sun Jan  7 10:57:18 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 7 Jan 2007 09:57:18 -0000
Subject: [Tutor] Query about using Pmw entry widget...
References: <b4e894c70701061423q45b70c5dwc781d0bc39c583fb@mail.gmail.com>	<45A10794.1090101@gmail.com><enqcg8$p24$1@sea.gmane.org>
	<45A165B4.5010907@gmail.com>
Message-ID: <enqg5v$6dp$1@sea.gmane.org>

"Luke Paireepinart" <rabidpoobear at gmail.com> wrote

>> Its easier for the programmer but much worse for the user.
>> We should always catch erroneous input as early as possible.
>
> The difference between a webpage and an application here is that if 
> the
> user enters something incorrectly, he'll know as soon as he tries to
> submit it, without having to wait for the page to reload,

Only a few seconds difference, he's still done all the work
of filling in 10 or more fields and now has to back to look
for the error.

> That's why I just purchased 'The Essential Guide To User Interface
> Design' from Half-Price Books!

I haven't seen that one, but I do like Abbout Face by Cooper - the
guy who wrote the first version of Visual Basic before MS bought it.

> but it's also annoying to have something restrict your input.

But if the input is wronmg better to get it right first time
rather than have the same error flagged to you after you've
stopped thinking about that bit of data.

> and I get some kind of visual warning that my entry is incorrect.
> NOT a dialog box, I hope, but some kind of red warning label next to 
> the
> entry widget or something.

I agree, dialogs are a pain for this.
But as I understand it (without having used it!) PMW actually
does give a visual indication by changing the colour of the
field to indicate an error rather than a dialog..

Also the validator is called on each keystroke *as well as*
when it loses focus.

> Basically I don't want to see an entry box that behaves differently 
> than
> a normal entry box (only accepts integers, for example).

But there are quite a few like that in Windows. Several of the
config tools regulate input. Think if the entry fields for inputting
an IP address.They autommatically jump to the next box
after 3 digits, and they won't let you enter a number above 255.

Similarly password entries are diffeerent to normal because
they show up asstars or blobs or sometimes as nothing at
all (I don't like those even though they are more secure!)


Alan G. 



From john at fouhy.net  Sun Jan  7 10:58:27 2007
From: john at fouhy.net (John Fouhy)
Date: Sun, 7 Jan 2007 22:58:27 +1300
Subject: [Tutor] Query about using Pmw entry widget...
In-Reply-To: <enqcg8$p24$1@sea.gmane.org>
References: <b4e894c70701061423q45b70c5dwc781d0bc39c583fb@mail.gmail.com>
	<45A10794.1090101@gmail.com> <enqcg8$p24$1@sea.gmane.org>
Message-ID: <5e58f2e40701070158q5ad827dema5f97835c4f66770@mail.gmail.com>

On 07/01/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
> I don;t have PMW installed. I tend to use Tix now that its part
> of standard Python. However Grayson says this:

Does Tix work with py2exe?  That's why I gave up on it, a while ago..

> So it seems you need
>
> def numeric(val):
>     try: float(val)
>     except ValueError: return Pmw.ERROR
>     else: return Pmw.OK
>
> timeinterval = Pmw.EntryField(.....validate=numeric)

>From memory, you have to do something like
"validate={'validator':numeric}" if you're not using one of the
built-in validators.

(which Asrarahmed would need to do, since he wants to restrict the
range of numbers available)

Also, this will not work quite right; you need something like:

def numeric(val):
    try:
        float(val)
    except ValueError:
        if val == '':
            return Pmw.PARTIAL
        return Pmw.ERROR
    return Pmw.OK

-- 
John.

From lists at mostrom.pp.se  Sun Jan  7 12:09:39 2007
From: lists at mostrom.pp.se (=?UTF-8?Q?Jan_Erik_Mostr=C3=B6?= =?UTF-8?Q?m?=)
Date: Sun,  7 Jan 2007 12:09:39 +0100
Subject: [Tutor] Question about ConfigParser
In-Reply-To: <20070106232645.GA49263@cutter.rexx.com>
Message-ID: <b02020005-1048-ppc-7531C60110E14B38B23329CC59BF2140@Infinitum.local>

Reply to Dave Kuhlman <dkuhlman at rexx.com> 07-01-06 15:26:

>It's sort of hidden, but note the restriction to string values in
>the docs on the set method:
>
>set(section, option, value)
>If the given section exists, set the given option to the specified
>value; otherwise raise NoSectionError. While it is possible to use
>RawConfigParser (or ConfigParser with raw parameters set to true)
>for internal storage of non-string values, full functionality
>(including interpolation and output to files) can only be achieved
>using string values. New in version 1.6.

Ahhhh ... I was spending all my time reading the docs for 
'items' ;-)

Thanks

             jem

From ajkadri at googlemail.com  Sun Jan  7 15:12:37 2007
From: ajkadri at googlemail.com (Asrarahmed Kadri)
Date: Sun, 7 Jan 2007 14:12:37 +0000
Subject: [Tutor] Query about using Pmw entry widget...
In-Reply-To: <45A165B4.5010907@gmail.com>
References: <b4e894c70701061423q45b70c5dwc781d0bc39c583fb@mail.gmail.com>
	<45A10794.1090101@gmail.com> <enqcg8$p24$1@sea.gmane.org>
	<45A165B4.5010907@gmail.com>
Message-ID: <b4e894c70701070612x6fa200far362ad8c44909366a@mail.gmail.com>

Hey Luke,
The dialog box, what I think is better than a 'visual warning' ; because it
forces the user to correct the input error that he has made. A visual
warning might be omitted by the user.

REgards,
Asrarahmed

On 1/7/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
>
> Alan Gauld wrote:
> > "Luke Paireepinart" <rabidpoobear at gmail.com> wrote
> >
> > OP>> Can some one help me how to add validation : only integers are
> > allowed
> > OP>> and minimum value should be 1.
> > OP>>
> > OP>> timeInterval = Pmw.EntryField(label_text='Time Interval(in
> > OP>> sec.):',labelpos='w',validate = 'numeric')
> >
> > I don;t have PMW installed. I tend to use Tix now that its part
> > of standard Python. However Grayson says this:
> >
> > "validation is [performed by a function which takes
> > as its first argument the entered text and returns
> > one of three standard values...
> > Pmw.OK, Pmw.ERROR, Pmw.PARTIAL"
> >
> > So it seems you need
> >
> > def numeric(val):
> >     try: float(val)
> >     except ValueError: return Pmw.ERROR
> >     else: return Pmw.OK
> >
> > timeinterval = Pmw.EntryField(.....validate=numeric)
> >
> > At least that's how I read it, obviously without Pmw I can't try it...
> >
> >
> >>> Also I want to validate date and time? I know that there is a way
> >>> to
> >>> do it but I dont know the exact syntax..
> >>>
> >
> > I'd use a similar technique as above. parse the string and try
> > to create a datetime object then handle the exceptions.
> >
> > Luke> it's a lot easier to validate the input when you're using it
> > instead of
> > Luke> trying to restrict their input.
> >
> > Its easier for the programmer but much worse for the user.
> > We should always catch erroneous input as early as possible.
> > Early CGI Web pages were the classic example of late error
> > handling and there is nothing more annoying than filling in a form,
> > submitting it and then being told you filled in a field wrong right
> > at the start!
> >
>
> The difference between a webpage and an application here is that if the
> user enters something incorrectly,
> he'll know as soon as he tries to submit it,
> without having to wait for the page to reload,
> and he won't lose all of his information just to go back and change one
> field.
> But I guess I don't know anything about UI design.
> That's why I just purchased 'The Essential Guide To User Interface
> Design' from Half-Price Books!
> Yes, a bit of a strange coincidence that I bought it just today.
>
> Anyway,
> I know it's frustrating to have to go back to fix entries,
> but it's also annoying to have something restrict your input.
> That seems sort of like the programmer didn't want to take the time to
> have a robust user input parser :D
> I think the ideal situation for me would be that whenever an entry
> widget loses focus, the validate() function is called,
> and I get some kind of visual warning that my entry is incorrect.
> NOT a dialog box, I hope, but some kind of red warning label next to the
> entry widget or something.
> However, this doesn't work for the last entry on the page, because most
> likely focus will switch straight from the entry to the submit button,
> but then the whole 'check on submit' thing would catch the error.
> Basically I don't want to see an entry box that behaves differently than
> a normal entry box (only accepts integers, for example).
> -Luke
>
> > HTH,
> >
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
To HIM you shall return.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070107/2b0c16a5/attachment.html 

From alan.gauld at btinternet.com  Sun Jan  7 17:16:25 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 7 Jan 2007 16:16:25 -0000
Subject: [Tutor] Query about using Pmw entry widget...
References: <b4e894c70701061423q45b70c5dwc781d0bc39c583fb@mail.gmail.com><45A10794.1090101@gmail.com>
	<enqcg8$p24$1@sea.gmane.org><45A165B4.5010907@gmail.com>
	<b4e894c70701070612x6fa200far362ad8c44909366a@mail.gmail.com>
Message-ID: <enr6cp$isd$1@sea.gmane.org>


"Asrarahmed Kadri" <ajkadri at googlemail.com> wrote

> The dialog box, what I think is better than a 'visual warning' ; 
> because it
> forces the user to correct the input error that he has made. A 
> visual
> warning might be omitted by the user.

I disagree. A dialog box in this situation has two bad effects:

1) It forces the users attention away from where the error occurs
(ie in the entry box) and in an extreme case could even hide the
error by popping up on top of the box beintg edited!

2) It is not specific enough - the dialog could be from another
application in the background or about some other error
- a network lost for example. You have to read it to interpret
it. Whereas if the entry box you are typing into beeps and
goes red, say, it is obvious where the error is and it's very
easy to fix.

As to forcing the user to correct the error a doalog is no
better than a coloured entry widget since the user can just
OK it and carry on filling I the other fields. In that situation
you have to do a submit time check on the fields too or else
refuse to allow access to any other field while the error
persists.

Designing a good UI is frought with difficulty.

Alan G. 



From carroll at tjc.com  Mon Jan  8 03:32:54 2007
From: carroll at tjc.com (Terry Carroll)
Date: Sun, 7 Jan 2007 18:32:54 -0800 (PST)
Subject: [Tutor] Need help with rewriting script to use Decimal module
In-Reply-To: <7.0.1.0.2.20070106100628.05c2fa78@rcblue.com>
Message-ID: <Pine.LNX.4.44.0701071800290.25272-100000@violet.rahul.net>

On Sat, 6 Jan 2007, Dick Moores wrote:

> Well, I have to admit I don't understand your code at all. But I see it
> works.

A continuing fraction is an expression that looks like this:

                1
A +  ----------------------------------
                   1
      B + -----------------------------
                         1
             C + ----------------------
                            1
                  D + -----------------
                         E + etc.

i.e., A + (1 / (B + (1 / (C + (1 / (D + (1 / E + ... )))))))

That is, the denominator of the fraction itself has a term that is a 
fraction; and that fraction itself has a term that is a fraction, etc., 
either to infinity or to some finite point.

The basic idea of using a continued fraction to get a rational 
approximation is something like this.   Say you want to get an 
approximation of 0.096.  Well, a good first approximation is 1/10.  But 
1/10 is 0.010.  That's too big, or, to put another way, the denominator is 
too small.  It should really be 1/(10+something), where "something" is 
some fraction 1/x (if it were larger than 1, then we'd be starting from 
11+ something).

The next best approximation is to figure out that "something" is.   It 
turns out, it's 1/2, i.e. .096 = about 1/(10+(1/2)), or about 0.9624.  
That's still too big, so that 1/2 we added should really be 1/(2+ 
something).

The next "something" we calculate is again 1/2, so it's 
1/(10+(1/(2+(1/2)), or .096154.  Getting closer, but the same thing.

Again, the next something is 1/2, so we get 1/(10+(1/(2+(1/(2+1/2))), 
which is 0.096, exactly.

So, in that butt-ugly ascii I have above, A=10, B = 2, C = 2 and D = 2,
and it turns out not to have been necessary to go any further.

(I admit I cheated above and picked 0.096 as an example, because some 
other examples, like .093 and .098 actually have a "something" that's 
equal to 1).

Now, I actually don't understand all of the math in the article at 
http://mathworld.wolfram.com/ContinuedFraction.html , which I based this 
on; but enough of it is clear that I could basically just take certain 
equations and translate them into Python:


>     a, r, p, q = [], [], [], []

This is a list of terms; "a" is the successive denominator, i.e. compared
to my description above a[0] is A; a[1] is B; a[2] is C, etc.  r[n] is
used to calculate a[n]; it actually could have been dispensed with.  p[n]
and q[n] are the value of the continued fraction after n iterations.

>         a.append(None)
>         r.append(None)
>         p.append(None)
>         q.append(None)

This is just so I can assign to a[n], r[n], etc.; it makes the code more 
readable.

>         if n == 0: r[n] = x
>         else: r[n] = 1/(r[n-1]-a[n-1])

These statements are equations 8 & 9 from the Wolfram page cited above.

>         a[n] = int(r[n])

This is equation 10.

>         if n == 0:
>             p[n] = a[0]
>             q[n] = 1

These are effectively equations 25 & 26 for the special case of n == 0, 
i.e. equation 24.

>         elif n ==1:
>             p[n] = a[n]*p[n-1] + 1
>             q[n] = a[n]

These are equations 25 & 26 for the special case of n == 1, taking into 
account equations 22 to get values for what would have otherwise looking 
for p[-1], i.e. an entry before the first element in the list.

>         else:
>             p[n] = a[n]*p[n-1] + p[n-2]
>             q[n] = a[n]*q[n-1] + q[n-2]

This is the general case for equations 25 & 26.

The rest is just cranking through the iterations.

> (BTW your pi is a bit off but I used yours, instead of math.pi, which 
> is 3.1415926535897931 . 

Oops.  I transposed the "79" and "89"; that's what I get for going from 
memory.

I may add this algorithm to the cookbook.


From dseto200 at yahoo.com  Mon Jan  8 03:52:58 2007
From: dseto200 at yahoo.com (David Seto)
Date: Sun, 7 Jan 2007 18:52:58 -0800 (PST)
Subject: [Tutor] Tutor Digest, Vol 35, Issue 16
In-Reply-To: <mailman.6884.1167981691.32030.tutor@python.org>
Message-ID: <20070108025259.14630.qmail@web52612.mail.yahoo.com>

Thanks, I finally figured it out. Here it is
#Coin Toss Game
import random

print"This game will simulate 100 coin tosses and then
tell you the number of head's and tails"

tosses=0
heads=0
tails=0

while tosses<100:
  tosses<100
  coin=random.randrange(2)
  tosses+=1
  if coin==0:
     heads +=1
     print "Heads"
  else:
      tails+=1
      print "Tails"

      
print"100 tosses have been simulated. Please wait for
your results"
print "\nOut of",tosses,",",heads,"were heads
and",tails,"were tails."
--- tutor-request at python.org wrote:

> Send Tutor mailing list submissions to
> 	tutor at python.org
> 
> To subscribe or unsubscribe via the World Wide Web,
> visit
> 	http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body
> 'help' to
> 	tutor-request at python.org
> 
> You can reach the person managing the list at
> 	tutor-owner at python.org
> 
> When replying, please edit your Subject line so it
> is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>    1. coin toss program without using the for/range
> loop (David)
>    2. Re: coin toss program without using the
> for/range loop
>       (Kent Johnson)
>    3. Re: coin toss program without using the
> for/range loop
>       (Luke Paireepinart)
>    4. Re: coin toss program without using the
> for/range loop
>       (Christopher Arndt)
>    5. Re: Question regarding parsing HTML with
> BeautifulSoup
>       (Shuai Jiang (Runiteking1))
>    6. Re: SPE - Stani's Python Editor ?
> (Shanmuhanathan T)
>    7. Re: Need help with rewriting script to use
> Decimal  module
>       (Terry Carroll)
> 
> 
>
----------------------------------------------------------------------
> 
> Message: 1
> Date: Thu, 4 Jan 2007 14:08:29 -0800
> From: "David" <dseto200 at pacbell.net>
> Subject: [Tutor] coin toss program without using the
> for/range loop
> To: <tutor at python.org>
> Message-ID: <000001c7304c$de339a40$7301a8c0 at davidxp>
> Content-Type: text/plain; charset="us-ascii"
> 
> How to write the coin toss program without using the
> for/range loop program.
> 
> Program flips a coin 100 times and then tells you
> the number of heads and
> tails.
> 
>  
> 
> I can only solve it using the for/range loop
> 
>  
> 
> Import random
> 
>   Heads=0
> 
>   For 1 in range (100):
> 
>   Heads+=random.randrange(2)
> 
>  
> 
> print "Hit heads"+" "+str(heads)+" "+"times"+" " +
> "hit tails" + "
> "+str(100-heads)+" " + "times"
> 
>  
> 
> I don't see how you solve this program just using
> the while loop program and
> if/else statement.
> 
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
>
http://mail.python.org/pipermail/tutor/attachments/20070104/8ca7ecfd/attachment-0001.html
> 
> 
> ------------------------------
> 
> Message: 2
> Date: Thu, 04 Jan 2007 19:12:05 -0500
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] coin toss program without using
> the for/range
> 	loop
> To: dseto200 at pacbell.net
> Cc: tutor at python.org
> Message-ID: <459D97D5.7050800 at tds.net>
> Content-Type: text/plain; charset=windows-1252;
> format=flowed
> 
> David wrote:
> > How to write the coin toss program without using
> the for/range loop program.
> > 
> > Program flips a coin 100 times and then tells you
> the number of heads 
> > and tails.
> > 
> >  
> > 
> > I can only solve it using the for/range loop
> > 
> >  
> > 
> > Import random
> > 
> >   Heads=0
> > 
> >   For 1 in range (100):
> > 
> >   Heads+=random.randrange(2)
> > 
> >  
> > 
> > print ?Hit heads?+? ?+str(heads)+? ?+?times?+? ? +
> ?hit tails? + ? 
> > ?+str(100-heads)+? ? + ?times?
> > 
> >  
> > 
> > I don?t see how you solve this program just using
> the while loop program 
> > and if/else statement.
> 
> This sounds a lot like homework so I won't give you
> the whole answer, 
> but you can write a for loop using while and a
> counter variable.
> 
> Kent
> 
> 
> 
> ------------------------------
> 
> Message: 3
> Date: Thu, 04 Jan 2007 18:41:57 -0600
> From: Luke Paireepinart <rabidpoobear at gmail.com>
> Subject: Re: [Tutor] coin toss program without using
> the for/range
> 	loop
> To: Kent Johnson <kent37 at tds.net>
> Cc: tutor at python.org, dseto200 at pacbell.net
> Message-ID: <459D9ED5.2010209 at gmail.com>
> Content-Type: text/plain; charset=windows-1252;
> format=flowed
> 
> Kent Johnson wrote:
> > David wrote:
> >   
> >> How to write the coin toss program without using
> the for/range loop program.
> >>
> >> Program flips a coin 100 times and then tells you
> the number of heads 
> >> and tails.
> >>
> >>  
> >>
> >> I can only solve it using the for/range loop
> >>
> >>  
> >>
> >> Import random
> >>
> >>   Heads=0
> >>
> >>   For 1 in range (100):
> >>
> >>   Heads+=random.randrange(2)
> >>
> >>  
> >>
> >> print ?Hit heads?+? ?+str(heads)+? ?+?times?+? ?
> + ?hit tails? + ? 
> >> ?+str(100-heads)+? ? + ?times?
> >>
> >>  
> >>
> >> I don?t see how you solve this program just using
> the while loop program 
> >> and if/else statement.
> >>     
> >
> > This sounds a lot like homework so I won't give
> you the whole answer, 
> > but you can write a for loop using while and a
> counter variable.
> >
> >   
> In fact, in most languages a for loop and a while
> loop are very similar:
> 
> for(int i =0; i < 100; i++)
> {
>     //do something
> }
> is the same as
> int i = 0
> while (i < 100)
> {
>     // do something
>     i++;
> }
> 
> The difference in Python comes from the fact that
> the 'for' loop 
> iterates over a list of objects,
> rather than incrementing a variable.
> If you're using a for-range loop in Python you're
> using it in the 
> old-style that C and C++ programs use (other
> languages too)
> in which case you could easily use a while loop as
> well.
> But if you're indexing into a specific list,
> it becomes much more clear why we use python's
> 'for',
> to index directly into that list without having to
> deal with an index 
> variable.
> 
> for x in some_list:
>     // do something with x
> 
> rather than
> 
> index = 0
> while index < len(some_list):
>     x = some_list[index]
>     // do something with x
>     index += 1
> 
> HTH,
> -Luke
> > Kent
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >   
> 
> 
> 
> ------------------------------
> 
> Message: 4
> Date: Fri, 05 Jan 2007 01:50:36 +0100
> From: Christopher Arndt <chris.arndt at web.de>
> Subject: Re: [Tutor] coin toss program without using
> the for/range
> 	loop
> To: Tutor at python.org
> Message-ID: <459DA0DC.2030907 at web.de>
> Content-Type: text/plain; charset=windows-1252
> 
> Kent Johnson schrieb:
> > David wrote:
> >> print ?Hit heads?+? ?+str(heads)+? ?+?times?+? ?
> + ?hit tails? + ? 
> >> ?+str(100-heads)+? ? + ?times?
> > 
> > This sounds a lot like homework [...]
> 
> An if you want to get extra marks for pythonicity 
> ;-), read about string
> formatting here:
> 
>
http://www.python.org/doc/current/lib/typesseq-strings.html
> 
> Chris
> 
> 
> ------------------------------
> 
> Message: 5
> Date: Thu, 4 Jan 2007 20:58:36 -0500
> From: "Shuai Jiang (Runiteking1)"
> <marshall.jiang at gmail.com>
> Subject: Re: [Tutor] Question regarding parsing HTML
> with
> 	BeautifulSoup
> To: "Kent Johnson" <kent37 at tds.net>
> Cc: Tutor at python.org
> Message-ID:
> 
>
<a678270c0701041758q7d7ba54bg605e4af5d2272e4 at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> Hi,
> 
> Wow, thats much more elegant than the idea I thought
> of.
> 
> Thank you very much Kent!
> 
> Marshall
> 
> On 1/3/07, Kent Johnson <kent37 at tds.net> wrote:
> >
> > Shuai Jiang (Runiteking1) wrote:
> > > Hello,
> > >
> > > I'm working on a program that need to parse a
> financial document on the
> > > internet
> > > using BeautifulSoup. Because of the nature of
> the information, it is all
> > > grouped
> > > as a table. I needed to get 3 types of info and
> have succeeded quite
> > > well using
> > > BeautifulSoup, but encountered problems on the
> third one.
> > >
> > > My question is that is there any easy way to
> parse an HTML tables column
> > > easily using BeautifulSoup. I copied the table
> here and I need to
> > > extract the EPS. The numbers are
> > > every sixth one from the  <tr> tag ex 2.27,
> 1.86, 1.61...
> >
> > Here is one way, found with a little experimenting
> at the command prompt:
> >
> > In [1]: data = '''<table id="INCS"
> style="width:580px" class="f10y"
> > cellspacing="0">
> > <snip the rest of your data>
> >     ...: </table>'''
> > In [3]: from BeautifulSoup import BeautifulSoup as
> BS
> >
> > In [4]: soup=BS(data)
> >
> > In [11]: for tr in soup.table.findAll('tr'):
> >     ....:     print tr.contents[11].string
> >     ....:
> >     ....:
> > EPS
> > 2.27
> >   1.86
> > 1.61
> >   1.27
> > 1.18
> >   0.84
> > 0.73
> >   0.46
> > 0.2
> >   0.0
> >
> > Kent
> >
> >
> >
> 
> 
> -- 
> I like pigs. Dogs look up to us. Cats look down on
> us. Pigs treat us as
> equals.
>     Sir Winston Churchill
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
>
http://mail.python.org/pipermail/tutor/attachments/20070104/09d685fb/attachment-0001.htm
> 
> 
> ------------------------------
> 
> Message: 6
> Date: Fri, 5 Jan 2007 11:48:50 +0530
> From: "Shanmuhanathan T" <shanmuha at gmail.com>
> Subject: Re: [Tutor] SPE - Stani's Python Editor ?
> To: "Mike Hansen" <Mike.Hansen at atmel.com>
> Cc: tutor at python.org
> Message-ID:
> 
>
<9871e7140701042218yefda759l8e614a51c58f7a2d at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> I found eclipse+pydev to be as good as/better than
> komodo or wingware.
> also eclipse has other plugins which makes it a
> powerful IDEs for
> php/ruby/perl etc.
> 
> Regards,
> Shanmu.
> 
> On 1/4/07, Mike Hansen <Mike.Hansen at atmel.com>
> wrote:
> >
> >
> >
> > > -----Original Message-----
> > > From: OkaMthembo [mailto:zebra05 at gmail.com]
> > > Sent: Thursday, January 04, 2007 9:18 AM
> > > To: Mike Hansen
> > > Subject: Re: [Tutor] SPE - Stani's Python Editor
> ?
> > >
> > > have you tried Komodo from ActiveState or
> Wingware? might be
> > > great, comeercial though.
> > >
> > >
> >
> > I convinced my company to purchase Komodo. I use
> it off an on. I mostly
> > gravitate toward VIM. I'm looking forward to the
> next version of Komodo
> > since it will have vi keybindings. The nice thing
> about Komodo is that
> > you can use it for other languages like Perl and
> Ruby where I believe
> > that Wingware is Python only.
> >
> > Mike
> >
> >
> > -------------
> >
> >   NOTICE:  This e-mail transmission and any
> documents or files attached to
> >   it contain information for the sole use of the
> above-identified
> > individual or entity.
> >
> >   Its contents may be privileged, confidential,
> and exempt from disclosure
> > under the law.
> >   Any dissemination, distribution, or copying of
> this communication is
> > strictly prohibited.
> >
> >   Please notify the sender immediately if you are
> not the intended
> > recipient.
> >
> > FGNS
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> >
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
>
http://mail.python.org/pipermail/tutor/attachments/20070105/f922f725/attachment.html
> 
> 
> ------------------------------
> 
> Message: 7
> Date: Thu, 4 Jan 2007 23:21:26 -0800 (PST)
> From: Terry Carroll <carroll at tjc.com>
> Subject: Re: [Tutor] Need help with rewriting script
> to use Decimal
> 	module
> To: tutor at python.org
> Message-ID:
> 
>
<Pine.LNX.4.44.0701042304480.30388-100000 at violet.rahul.net>
> Content-Type: TEXT/PLAIN; charset=US-ASCII
> 
> On Wed, 3 Jan 2007, Dick Moores wrote:
> 
> > Be that as it may, farey() is an amazing program. 
> 
> Not to beat this subject to death, but the comment
> at the bottom of 
>
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317
> about 
> continued fractions piqued my interest.  I'm no
> mathematician, but I 
> encountered continued fractions a long time ago and
> was fascinated by 
> them.  So I read the URL pointed to, 
> http://mathworld.wolfram.com/ContinuedFraction.html
> , and came up with the 
> following:
> 
>
#####################################################
> 
> def cf(x, tol=0.0001, Trace=False):
>     """
>     Calculate rational approximation of x to within
> tolerance of tol;
>     returns a tuple consisting of numerator and
> denominator p/q
>     Trace=True causes iterated results to be shown
>     """
>     a, r, p, q = [], [], [], []
>     Done = False
>     n = 0
>     if Trace: print "x:%f tol:%f" % (x, tol)
>     while not Done:
>         a.append(None)
>         r.append(None)
>         p.append(None)
>         q.append(None)
>         if n == 0: r[n] = x
>         else: r[n] = 1/(r[n-1]-a[n-1])
>         a[n] = int(r[n])
>         if n == 0:
>             p[n] = a[0]
>             q[n] = 1
>         elif n ==1:
>             p[n] = a[n]*p[n-1] + 1
>             q[n] = a[n]
>         else:
>             p[n] = a[n]*p[n-1] + p[n-2]
>             q[n] = a[n]*q[n-1] + q[n-2]
>         if Trace:
>             print "n:%d a:%d p:%d q:%d approx:%f" %
> \
>                   (n, a[n], p[n], q[n],
> float(p[n])/q[n])
>         if abs(float(p[n])/q[n] - x) < tol:
>             Done = True
>         num = p[n]; denom = q[n]
>         n += 1
>     return (num, denom)
> 
>
#####################################################
> 
> Here's a result for pi:
> 
> >>> print cf(3.14159265357989,0.0000001, Trace=True)
> x:3.141593 tol:0.000000
> n:0 a:3 p:3 q:1 approx:3.000000
> n:1 a:7 p:22 q:7 approx:3.142857
> n:2 a:15 p:333 q:106 approx:3.141509
> n:3 a:1 p:355 q:113 approx:3.141593
> n:4 a:292 p:103993 q:33102 approx:3.141593
> (103993, 33102)
> 
> i.e., the first 5 approximations it came up with
> were 3/1, 22/7, 333/106, 
> 355/113 and a whopping 103993/33102.
> 
> For the 0.36 example you used earlier:
> 
> >>> print cf(0.36, .01, Trace= True)
> x:0.360000 tol:0.010000
> n:0 a:0 p:0 q:1 approx:0.000000
> n:1 a:2 p:1 q:2 approx:0.500000
> n:2 a:1 p:1 q:3 approx:0.333333
> n:3 a:3 p:4 q:11 approx:0.363636
> (4, 11)
> >>>
> 
> it went right from 1/3 to 4/11 (0.363636), skipping
> the 3/8 (0.375) option 
> from the farey series.  
> 
> But this continued fraction algorithm is ill-suited
> to answer the question
> "what's the closest fraction with a denominator <
> N", because it doesn't
> try to find that, it jumps further ahead with each
> iteration.
> 
> Anyway, I thought you might find it interesting
> based on our discussion.
> 
> (Yeah, I know, I didn't choose the formats well on
> those print 
> statements.)
> 
> 
> 
> ------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> End of Tutor Digest, Vol 35, Issue 16
> *************************************
> 


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From carroll at tjc.com  Mon Jan  8 04:53:55 2007
From: carroll at tjc.com (Terry Carroll)
Date: Sun, 7 Jan 2007 19:53:55 -0800 (PST)
Subject: [Tutor] Need help with rewriting script to use Decimal module
In-Reply-To: <Pine.LNX.4.44.0701071800290.25272-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0701071953070.15228-100000@violet.rahul.net>

On Sun, 7 Jan 2007, Terry Carroll wrote:

> ...Say you want to get an approximation of 0.096.  Well, a good first
> approximation is 1/10.  But 1/10 is 0.010....

Um, that should be "...is 0.100"



From alan.gauld at btinternet.com  Mon Jan  8 06:04:00 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 8 Jan 2007 05:04:00 -0000
Subject: [Tutor] Tutor Digest, Vol 35, Issue 16
References: <mailman.6884.1167981691.32030.tutor@python.org>
	<20070108025259.14630.qmail@web52612.mail.yahoo.com>
Message-ID: <ensjc1$g11$1@sea.gmane.org>

Congratulations.
Just one wee niggle:


> 
> while tosses<100:
>  tosses<100

You don't need this line, it doesn't do anything.

HTH


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From olen88 at gmail.com  Mon Jan  8 07:04:30 2007
From: olen88 at gmail.com (olen88)
Date: Mon, 08 Jan 2007 01:04:30 -0500
Subject: [Tutor] smtplib starttls() error
Message-ID: <45A1DEEE.2040509@gmail.com>

Hello,
	I was wondering if anyone could point me in the right direction
	my system info:
Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on 
win32

	as the subject says. starttls() returns the following error,

reply, null = session.starttls();
File "C:\Python24\lib\smtplib.py", line 601, in starttls
sslobj = socket.ssl(self.sock, keyfile, certfile)
AttributeError: 'module' object has no attribute 'ssl'

I tried,

import socket

socket.ssl();

same AttributeError exception was raised, so this confirmed that
socket.py has no ssl attribute.

what can I do about this, some answers I digged up suggest

http://mail.python.org/pipermail/python-list/2003-June/207802.html

but I am hasty about this suggestion, and wishes to consult to you all
about what to do.

Thank you

ennma


From olen88 at gmail.com  Mon Jan  8 07:44:22 2007
From: olen88 at gmail.com (Olen)
Date: Mon, 8 Jan 2007 01:44:22 -0500
Subject: [Tutor] smtplib starttls() error
In-Reply-To: <45A1DEEE.2040509@gmail.com>
References: <45A1DEEE.2040509@gmail.com>
Message-ID: <49b753370701072244h11398eecv8ea9cfc7dfde75f7@mail.gmail.com>

I have also looked in all the documentation python 2.4.3 files I downloaded
and this points out that I should have install the socket.ssl()
my question is that is how do I install the

socket.ssl()

thank you

ennma
On 1/8/07, olen88 <olen88 at gmail.com> wrote:
> Hello,
>         I was wondering if anyone could point me in the right direction
>         my system info:
> Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on
> win32
>
>         as the subject says. starttls() returns the following error,
>
> reply, null = session.starttls();
> File "C:\Python24\lib\smtplib.py", line 601, in starttls
> sslobj = socket.ssl(self.sock, keyfile, certfile)
> AttributeError: 'module' object has no attribute 'ssl'
>
> I tried,
>
> import socket
>
> socket.ssl();
>
> same AttributeError exception was raised, so this confirmed that
> socket.py has no ssl attribute.
>
> what can I do about this, some answers I digged up suggest
>
> http://mail.python.org/pipermail/python-list/2003-June/207802.html
>
> but I am hasty about this suggestion, and wishes to consult to you all
> about what to do.
>
> Thank you
>
> ennma
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From rdm at rcblue.com  Mon Jan  8 13:20:24 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 08 Jan 2007 04:20:24 -0800
Subject: [Tutor] Need help with rewriting script to use Decimal  module
In-Reply-To: <Pine.LNX.4.44.0701071800290.25272-100000@violet.rahul.net>
References: <7.0.1.0.2.20070106100628.05c2fa78@rcblue.com>
	<Pine.LNX.4.44.0701071800290.25272-100000@violet.rahul.net>
Message-ID: <7.0.1.0.2.20070108030915.06936058@rcblue.com>

At 06:32 PM 1/7/2007, Terry Carroll wrote:
>I may add this algorithm to the cookbook.

You should.

Dick





From janos.juhasz at VELUX.com  Mon Jan  8 13:56:23 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Mon, 8 Jan 2007 13:56:23 +0100
Subject: [Tutor] import glob.glob('*.py')
In-Reply-To: <mailman.7157.1168225183.32030.tutor@python.org>
Message-ID: <OF92E1CB82.D1735DF2-ONC125725D.0046431C-C125725D.004713FE@velux.com>

Hi All,

I am playing with reportlab and I would like to make a directory where I 
can place all of my projects as ___.py files.
A project file should be like this:
test.py--------
title="Test project"
duedate = '2007-02-28'
description = "description _________"
detailed="""
detaileddetaileddetaileddetaileddetaileddetaileddetailed
detaileddetaileddetaileddetaileddetaileddetaileddetailed
detaileddetaileddetaileddetaileddetaileddetaileddetailed
detaileddetaileddetaileddetaileddetaileddetaileddetailed
detaileddetaileddetaileddetaileddetaileddetaileddetailed
"""
test.py--------

I plan to make a python script, that collect all the projectfiles from 
that folder and render them as a report summary.
I planned to import these files as modules like 

for filename in glob.glob('*.py'):
    if '_' in filename: continue
    import filename
    render(filename)

Probably you have better ideas to do that.


Yours sincerely, 
______________________________
Janos Juhasz 


From kent37 at tds.net  Mon Jan  8 14:38:42 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 08 Jan 2007 08:38:42 -0500
Subject: [Tutor] import glob.glob('*.py')
In-Reply-To: <OF92E1CB82.D1735DF2-ONC125725D.0046431C-C125725D.004713FE@velux.com>
References: <OF92E1CB82.D1735DF2-ONC125725D.0046431C-C125725D.004713FE@velux.com>
Message-ID: <45A24962.3030604@tds.net>

J?nos Juh?sz wrote:
> I plan to make a python script, that collect all the projectfiles from 
> that folder and render them as a report summary.
> I planned to import these files as modules like 
> 
> for filename in glob.glob('*.py'):
>     if '_' in filename: continue
>     import filename
>     render(filename)


This won't work, the import statement does not take a variable as an 
argument. You need something like
module = __import__(filename)
render(module)

You will want to take care that your modules don't have any side effects 
on import.

> 
> Probably you have better ideas to do that.

You might want to look at the existing Python document generation tools. 
There is a summary here (be sure to read the comments and the original 
post just below this one):
http://www.voidspace.org.uk/python/weblog/arch_d7_2006_12_30.shtml#e599

In particular PythonDoc supports structured comments that are similar to 
what you outlined and has pluggable output generators that could be used 
to drive ReportLab.

Kent


From mail at timgolden.me.uk  Mon Jan  8 17:49:24 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 08 Jan 2007 16:49:24 +0000
Subject: [Tutor] Apologies...
Message-ID: <45A27614.6020006@timgolden.me.uk>

... my many apologies to the readers of the tutor
list. I went away for a week without suspending delivery
just as my company changed name - and decided to send
an irritating response to anything directed at the
old name. The list admin has very properly unsubscribed
the old address (otherwise you'd be seeing loads more
of the things!). Sorry again. Hope it didn't spoil your
new year.

TJG

From pythontut at pusspaws.net  Mon Jan  8 20:24:37 2007
From: pythontut at pusspaws.net (Dave S)
Date: Mon, 8 Jan 2007 19:24:37 +0000
Subject: [Tutor] 'root' dir of a package from within the package ?
Message-ID: <200701081924.38050.pythontut@pusspaws.net>

Hi all,

I have written a python package, which works fine, the 'root' directory 
is 'my_app' with sub directories within in, complete with there __init__.py 
files.

I need to work out the path to the root directory from within the app, os.path 
gives me pythons path! - oh and its in XP.

Any suggestions ?

Dave

From hugonz-lists at h-lab.net  Tue Jan  9 07:28:08 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Tue, 09 Jan 2007 00:28:08 -0600
Subject: [Tutor] is gotchas?
In-Reply-To: <7e5ba9220611061851j30c7e1cdu47ecaf12c9df84ca@mail.gmail.com>
References: <20061106171601.GB1768@johnsons-web.com>
	<454F8ACC.9000202@tds.net>	<20061107002229.GA1780@johnsons-web.com>
	<7e5ba9220611061851j30c7e1cdu47ecaf12c9df84ca@mail.gmail.com>
Message-ID: <45A335F8.2050106@h-lab.net>


>       Hmmm! Hmmm!
>       Lookee here:
>       ## console session
>      >>> a=[1,2]
>      >>> b=[1,2]
>      >>> a is b
>     False
>      >>> c='1'  ## one byte
>      >>> d='1'  ## one byte
>      >>> c is d
>     True
>      >>> c='1,2'
>      >>> d='1,2'
>      >>> c is d
>     False
> 
>     The Hmmm! is emmitted because I'm thinking that if everything is an
>     object in python, then why does `c is d` evaluate to True when
>     the assigned value is 1 byte and evaluate to False when the assigned
>     value is more that 1 byte?

One and two byte strings are currently optimized in cPython as the same 
object, referenced multiple times.

Note that this is not to be relied upon! Jython, Ironpython, Python3000 
or cPython itself may break it!

Still cannot find a reference doc for this....

Hugo


From klappnase at freenet.de  Tue Jan  9 11:55:10 2007
From: klappnase at freenet.de (Michael Lange)
Date: Tue, 9 Jan 2007 11:55:10 +0100
Subject: [Tutor] 'root' dir of a package from within the package ?
In-Reply-To: <200701081924.38050.pythontut@pusspaws.net>
References: <200701081924.38050.pythontut@pusspaws.net>
Message-ID: <20070109115510.78172072.klappnase@freenet.de>

On Mon, 8 Jan 2007 19:24:37 +0000
Dave S <pythontut at pusspaws.net> wrote:

> Hi all,
> 
> I have written a python package, which works fine, the 'root' directory 
> is 'my_app' with sub directories within in, complete with there __init__.py 
> files.
> 
> I need to work out the path to the root directory from within the app, os.path 
> gives me pythons path! - oh and its in XP.
> 
> Any suggestions ?
> 

Hi Dave,

app_root = os.path.abspath(sys.path[0]) or, within the main executable .py file,
app_root = os.path.abspath(os.path.dirname(__file__)) should do the trick.

I hope this helps

Michael

From kent37 at tds.net  Tue Jan  9 12:11:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 09 Jan 2007 06:11:40 -0500
Subject: [Tutor] is gotchas?
In-Reply-To: <45A335F8.2050106@h-lab.net>
References: <20061106171601.GB1768@johnsons-web.com>	<454F8ACC.9000202@tds.net>	<20061107002229.GA1780@johnsons-web.com>	<7e5ba9220611061851j30c7e1cdu47ecaf12c9df84ca@mail.gmail.com>
	<45A335F8.2050106@h-lab.net>
Message-ID: <45A3786C.1040503@tds.net>

Hugo Gonz?lez Monteverde wrote:
>>       Hmmm! Hmmm!
>>       Lookee here:
>>       ## console session
>>      >>> a=[1,2]
>>      >>> b=[1,2]
>>      >>> a is b
>>     False
>>      >>> c='1'  ## one byte
>>      >>> d='1'  ## one byte
>>      >>> c is d
>>     True
>>      >>> c='1,2'
>>      >>> d='1,2'
>>      >>> c is d
>>     False
>>
>>     The Hmmm! is emmitted because I'm thinking that if everything is an
>>     object in python, then why does `c is d` evaluate to True when
>>     the assigned value is 1 byte and evaluate to False when the assigned
>>     value is more that 1 byte?
> 
> One and two byte strings are currently optimized in cPython as the same 
> object, referenced multiple times.

It's not just one-byte strings; I think any string that can be a Python 
identifier is interned and will always be the same string.

In [1]: a='abcd'

In [2]: b='abcd'

In [3]: a is b
Out[3]: True
> 
> Note that this is not to be relied upon! Jython, Ironpython, Python3000 
> or cPython itself may break it!

Right. But why do you even care? I don't think I have ever written code 
that compares strings using 'is'; just use ==.
> 
> Still cannot find a reference doc for this....

Probably the source code will be the only reference, this is an 
implementation detail.

Kent


From vgvr620034 at gmail.com  Tue Jan  9 13:46:02 2007
From: vgvr620034 at gmail.com (raghu raghu)
Date: Tue, 9 Jan 2007 18:16:02 +0530
Subject: [Tutor] Tutor Digest, Vol 35, Issue 27
In-Reply-To: <mailman.53.1168340418.17116.tutor@python.org>
References: <mailman.53.1168340418.17116.tutor@python.org>
Message-ID: <bedebdfb0701090446l11113aeds377eebc0fb43ffdf@mail.gmail.com>

i have a clarification regarding built in function,in some scripts it is
being used and it is give n: if _name_ == '_main_'
why this is being used in the scripts?

On 1/9/07, tutor-request at python.org <tutor-request at python.org> wrote:
>
> Send Tutor mailing list submissions to
>         tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>         http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>         tutor-request at python.org
>
> You can reach the person managing the list at
>         tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>    1. Re: Need help with rewriting script to use Decimal  module
>       (Dick Moores)
>    2. import glob.glob('*.py') (J?nos Juh?sz)
>    3. Re: import glob.glob('*.py') (Kent Johnson)
>    4. Apologies... (Tim Golden)
>    5. 'root' dir of a package from within the package ? (Dave S)
>    6. Re: is gotchas? (Hugo Gonz?lez Monteverde)
>    7. Re: 'root' dir of a package from within the package ?
>       (Michael Lange)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Mon, 08 Jan 2007 04:20:24 -0800
> From: Dick Moores <rdm at rcblue.com>
> Subject: Re: [Tutor] Need help with rewriting script to use Decimal
>         module
> To: Terry Carroll <carroll at tjc.com>, tutor at python.org
> Message-ID: <7.0.1.0.2.20070108030915.06936058 at rcblue.com>
> Content-Type: text/plain; charset="us-ascii"; format=flowed
>
> At 06:32 PM 1/7/2007, Terry Carroll wrote:
> >I may add this algorithm to the cookbook.
>
> You should.
>
> Dick
>
>
>
>
>
>
> ------------------------------
>
> Message: 2
> Date: Mon, 8 Jan 2007 13:56:23 +0100
> From: J?nos Juh?sz <janos.juhasz at VELUX.com>
> Subject: [Tutor] import glob.glob('*.py')
> To: tutor at python.org
> Message-ID:
>         <
> OF92E1CB82.D1735DF2-ONC125725D.0046431C-C125725D.004713FE at velux.com>
> Content-Type: text/plain; charset="US-ASCII"
>
> Hi All,
>
> I am playing with reportlab and I would like to make a directory where I
> can place all of my projects as ___.py files.
> A project file should be like this:
> test.py--------
> title="Test project"
> duedate = '2007-02-28'
> description = "description _________"
> detailed="""
> detaileddetaileddetaileddetaileddetaileddetaileddetailed
> detaileddetaileddetaileddetaileddetaileddetaileddetailed
> detaileddetaileddetaileddetaileddetaileddetaileddetailed
> detaileddetaileddetaileddetaileddetaileddetaileddetailed
> detaileddetaileddetaileddetaileddetaileddetaileddetailed
> """
> test.py--------
>
> I plan to make a python script, that collect all the projectfiles from
> that folder and render them as a report summary.
> I planned to import these files as modules like
>
> for filename in glob.glob('*.py'):
>     if '_' in filename: continue
>     import filename
>     render(filename)
>
> Probably you have better ideas to do that.
>
>
> Yours sincerely,
> ______________________________
> Janos Juhasz
>
>
>
> ------------------------------
>
> Message: 3
> Date: Mon, 08 Jan 2007 08:38:42 -0500
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] import glob.glob('*.py')
> To: J?nos Juh?sz <janos.juhasz at VELUX.com>
> Cc: tutor at python.org
> Message-ID: <45A24962.3030604 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> J?nos Juh?sz wrote:
> > I plan to make a python script, that collect all the projectfiles from
> > that folder and render them as a report summary.
> > I planned to import these files as modules like
> >
> > for filename in glob.glob('*.py'):
> >     if '_' in filename: continue
> >     import filename
> >     render(filename)
>
>
> This won't work, the import statement does not take a variable as an
> argument. You need something like
> module = __import__(filename)
> render(module)
>
> You will want to take care that your modules don't have any side effects
> on import.
>
> >
> > Probably you have better ideas to do that.
>
> You might want to look at the existing Python document generation tools.
> There is a summary here (be sure to read the comments and the original
> post just below this one):
> http://www.voidspace.org.uk/python/weblog/arch_d7_2006_12_30.shtml#e599
>
> In particular PythonDoc supports structured comments that are similar to
> what you outlined and has pluggable output generators that could be used
> to drive ReportLab.
>
> Kent
>
>
>
> ------------------------------
>
> Message: 4
> Date: Mon, 08 Jan 2007 16:49:24 +0000
> From: Tim Golden <mail at timgolden.me.uk>
> Subject: [Tutor] Apologies...
> To: tutor at python.org
> Message-ID: <45A27614.6020006 at timgolden.me.uk>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> ... my many apologies to the readers of the tutor
> list. I went away for a week without suspending delivery
> just as my company changed name - and decided to send
> an irritating response to anything directed at the
> old name. The list admin has very properly unsubscribed
> the old address (otherwise you'd be seeing loads more
> of the things!). Sorry again. Hope it didn't spoil your
> new year.
>
> TJG
>
>
> ------------------------------
>
> Message: 5
> Date: Mon, 8 Jan 2007 19:24:37 +0000
> From: Dave S <pythontut at pusspaws.net>
> Subject: [Tutor] 'root' dir of a package from within the package ?
> To: Python Tutor <tutor at python.org>
> Message-ID: <200701081924.38050.pythontut at pusspaws.net>
> Content-Type: text/plain;  charset="us-ascii"
>
> Hi all,
>
> I have written a python package, which works fine, the 'root' directory
> is 'my_app' with sub directories within in, complete with there
> __init__.py
> files.
>
> I need to work out the path to the root directory from within the app,
> os.path
> gives me pythons path! - oh and its in XP.
>
> Any suggestions ?
>
> Dave
>
>
> ------------------------------
>
> Message: 6
> Date: Tue, 09 Jan 2007 00:28:08 -0600
> From: Hugo Gonz?lez Monteverde <hugonz-lists at h-lab.net>
> Subject: Re: [Tutor] is gotchas?
> To: tutor at python.org
> Message-ID: <45A335F8.2050106 at h-lab.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
>
> >       Hmmm! Hmmm!
> >       Lookee here:
> >       ## console session
> >      >>> a=[1,2]
> >      >>> b=[1,2]
> >      >>> a is b
> >     False
> >      >>> c='1'  ## one byte
> >      >>> d='1'  ## one byte
> >      >>> c is d
> >     True
> >      >>> c='1,2'
> >      >>> d='1,2'
> >      >>> c is d
> >     False
> >
> >     The Hmmm! is emmitted because I'm thinking that if everything is an
> >     object in python, then why does `c is d` evaluate to True when
> >     the assigned value is 1 byte and evaluate to False when the assigned
> >     value is more that 1 byte?
>
> One and two byte strings are currently optimized in cPython as the same
> object, referenced multiple times.
>
> Note that this is not to be relied upon! Jython, Ironpython, Python3000
> or cPython itself may break it!
>
> Still cannot find a reference doc for this....
>
> Hugo
>
>
>
> ------------------------------
>
> Message: 7
> Date: Tue, 9 Jan 2007 11:55:10 +0100
> From: Michael Lange <klappnase at freenet.de>
> Subject: Re: [Tutor] 'root' dir of a package from within the package ?
> To: pythontut at pusspaws.net
> Cc: tutor at python.org
> Message-ID: <20070109115510.78172072.klappnase at freenet.de>
> Content-Type: text/plain; charset=US-ASCII
>
> On Mon, 8 Jan 2007 19:24:37 +0000
> Dave S <pythontut at pusspaws.net> wrote:
>
> > Hi all,
> >
> > I have written a python package, which works fine, the 'root' directory
> > is 'my_app' with sub directories within in, complete with there
> __init__.py
> > files.
> >
> > I need to work out the path to the root directory from within the app,
> os.path
> > gives me pythons path! - oh and its in XP.
> >
> > Any suggestions ?
> >
>
> Hi Dave,
>
> app_root = os.path.abspath(sys.path[0]) or, within the main executable .py
> file,
> app_root = os.path.abspath(os.path.dirname(__file__)) should do the trick.
>
> I hope this helps
>
> Michael
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 35, Issue 27
> *************************************
>



-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070109/62946071/attachment.html 

From berlinlikoa at mynet.com  Tue Jan  9 13:17:55 2007
From: berlinlikoa at mynet.com (ziok)
Date: Tue, 9 Jan 2007 04:17:55 -0800 (PST)
Subject: [Tutor] python Error:IndentationError: expected an indented
 block
In-Reply-To: <eit7tl$ms0$1@sea.gmane.org>
References: <20061108154919.14248.qmail@web58108.mail.re3.yahoo.com>
	<eit7tl$ms0$1@sea.gmane.org>
Message-ID: <8236580.post@talk.nabble.com>


hi ..

i'm learning python .i have a book with examples. i did the examples for
"if" and have the same errors...
here is the simple code(two of them)
>>> z=['ze','se']
>>> for s in z:
... if s=='ze':
  File "<stdin>", line 2
    if s=='ze':
     ^
IndentationError: expected an indented block
>>> z=['ze','se']
>>> while s in z:
... if s=='ze':
  File "<stdin>", line 2
    if s=='ze':
     ^
IndentationError: expected an indented block
 why why  :/ 
-- 
View this message in context: http://www.nabble.com/python-Error%3AIndentationError%3A-expected-an-indented-block-tf2596004.html#a8236580
Sent from the Python - tutor mailing list archive at Nabble.com.


From kent37 at tds.net  Tue Jan  9 14:18:44 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 09 Jan 2007 08:18:44 -0500
Subject: [Tutor] python Error:IndentationError: expected an indented
	block
In-Reply-To: <8236580.post@talk.nabble.com>
References: <20061108154919.14248.qmail@web58108.mail.re3.yahoo.com>	<eit7tl$ms0$1@sea.gmane.org>
	<8236580.post@talk.nabble.com>
Message-ID: <45A39634.1090500@tds.net>

ziok wrote:
> hi ..
> 
> i'm learning python .i have a book with examples. i did the examples for
> "if" and have the same errors...
> here is the simple code(two of them)
>>>> z=['ze','se']
>>>> for s in z:
> ... if s=='ze':
>   File "<stdin>", line 2
>     if s=='ze':
>      ^
> IndentationError: expected an indented block

Python uses indentation to define blocks. For example, to show which 
statements are controlled by a for or if statement, the controlled 
statements are indented. Your book should talk about this.

So when typing these examples you need to indent the lines after the 
for, if or while. The indentation can be any consistent white space. 
Four spaces is a very common indent. When typing at the interactive 
prompt I usually use two spaces just because it's easier to type.

Your code should look something like this:
 >>> z=['ze','se']
 >>> for s in z:
...   if s=='ze':
...     print 'found ze'
...   else:
...     print 'not ze'

Kent


From kent37 at tds.net  Tue Jan  9 14:24:41 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 09 Jan 2007 08:24:41 -0500
Subject: [Tutor] Tutor Digest, Vol 35, Issue 27
In-Reply-To: <bedebdfb0701090446l11113aeds377eebc0fb43ffdf@mail.gmail.com>
References: <mailman.53.1168340418.17116.tutor@python.org>
	<bedebdfb0701090446l11113aeds377eebc0fb43ffdf@mail.gmail.com>
Message-ID: <45A39799.1050102@tds.net>

raghu raghu wrote:
> i have a clarification regarding built in function,in some scripts it is 
> being used and it is give n: if _name_ == '_main_'
> why this is being used in the scripts?

This is a way to include test code that runs if the module is run as a 
main program, but not if the module is imported.

Here is some more explanation:
http://diveintopython.org/getting_to_know_python/testing_modules.html
http://pyfaq.infogami.com/tutor-what-is-if-name-main-for

Kent


From rabidpoobear at gmail.com  Tue Jan  9 14:35:10 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 09 Jan 2007 07:35:10 -0600
Subject: [Tutor] Question about __name__ global variable (Was: Tutor
 Digest, Vol 35, Issue 27)
In-Reply-To: <bedebdfb0701090446l11113aeds377eebc0fb43ffdf@mail.gmail.com>
References: <mailman.53.1168340418.17116.tutor@python.org>
	<bedebdfb0701090446l11113aeds377eebc0fb43ffdf@mail.gmail.com>
Message-ID: <45A39A0E.7030108@gmail.com>

raghu raghu wrote:
> i have a clarification regarding built in function,in some scripts it 
> is being used and it is give n: if _name_ == '_main_'
> why this is being used in the scripts?
The global variable __name__ is equal to '__main__' when the python 
script is run.
If the script is imported, __name__ is something other than '__main__' 
(not sure what.)
So by checking if __name__ == '__main__' we can ensure that our code can 
work both as a standalone script
and as a module.
For example:

#test-script.py
import random

def someFunction(a):
    return a * random.randrange(100)

if __name__ == "__main__":
    print "The number 42 passed to someFunction is: " + someFunction(42)

#-----

If we want to use the function someFunction from test-script.py in a 
different file,
the 'main' part won't be run.
#
import test-script

print "The number 3 passed to someFunction is: " + someFunction(3)
#-------------

if the 'if __name__ == '__main__' ' test weren't in the original 
test-script.py,
the 42 version of the print statement would be run whenever someone 
imported it.

HTH,
-Luke

From David.Barton at nottingham.ac.uk  Tue Jan  9 14:34:53 2007
From: David.Barton at nottingham.ac.uk (Barton David)
Date: Tue, 9 Jan 2007 13:34:53 -0000
Subject: [Tutor] feeding data to subprocess exes and getting results without
	writing files
Message-ID: <BAA2EE790D828F4E8B262F17B3B0A7A3026BDFDF@VUIEXCH1.ad.nottingham.ac.uk>

Hi there,
I can easily use the subprocess module to run a separate exe from within
MyScript.py..
 
e.g.
import subprocess
process=subprocess.Popen("myprog.exe -i inputfile.txt -o
outputfile.txt")
 
..and that's just fine as far as it goes, if I don't mind creating
'inputfile.txt' first, and reading 'outputfile.txt' afterward.
 
But what if I do mind? I'm trying to do something like..
 
stdin="my input string"
process=subprocess.Popen("myprog.exe -i stdin -o stdout") # (infact
these are the default args for -i and -o, so it seems like myprog.exe
can be used this way)
myresults=stdout
 
I just can't wrap my head around stdin, stdout and the whole pipes
thing, but there's got to be a relatively simple way to do this, surely?
 
 
thanks for any help,
Dave (relative newbie using PythonWin & Python 2.4)

This message has been checked for viruses but the contents of an attachment
may still contain software viruses, which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070109/cb713cd1/attachment.htm 

From chris.arndt at web.de  Tue Jan  9 15:26:07 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Tue, 09 Jan 2007 15:26:07 +0100
Subject: [Tutor] feeding data to subprocess exes and getting results
 without writing files
In-Reply-To: <BAA2EE790D828F4E8B262F17B3B0A7A3026BDFDF@VUIEXCH1.ad.nottingham.ac.uk>
References: <BAA2EE790D828F4E8B262F17B3B0A7A3026BDFDF@VUIEXCH1.ad.nottingham.ac.uk>
Message-ID: <45A3A5FF.6040800@web.de>

Barton David schrieb:
> I just can't wrap my head around stdin, stdout and the whole pipes
> thing, but there's got to be a relatively simple way to do this, surely?

You have to distinguish between three different concepts:

1) file names
2) file objects
3) file contents

1) Is just a string with some identifier (the file path). To use a file with
that identifier in Python, you have to create a file object from it by using
the builtin 'open' function.

2) File objects are builtin Python objects that are usually created by the
'open' function or returned by some other function. There are a few file
objects that are already opened and accessible to your Python program. These
are sys.stdin, sys.stderr and sys.stdout. They are file objects, *not* strings
representing the (non-existant) file name or file content!

3) File contents are just represented by binary strings in Python. You
read/write them with the appropriate methods of file objects.

==> The subprocess.Popen constructor expects *file objects* not strings for its
'stdin' and 'stdout' arguments. Read the documentation of subprocess.Popen very
carefully again (ignore references to file *descriptors*).

BTW: a pipe is just an object or function that reads from one file object and
writes to another.

Chris

From olen88 at gmail.com  Tue Jan  9 19:05:29 2007
From: olen88 at gmail.com (Olen)
Date: Tue, 9 Jan 2007 13:05:29 -0500
Subject: [Tutor] smtplib starttls() error
In-Reply-To: <49b753370701072244h11398eecv8ea9cfc7dfde75f7@mail.gmail.com>
References: <45A1DEEE.2040509@gmail.com>
	<49b753370701072244h11398eecv8ea9cfc7dfde75f7@mail.gmail.com>
Message-ID: <49b753370701091005k3dbba71co484edef0995772ce@mail.gmail.com>

On 1/8/07, Olen <olen88 at gmail.com> wrote:
> I have also looked in all the documentation python 2.4.3 files I downloaded
> and this points out that I should have install the socket.ssl()
> my question is that is how do I install the
>
> socket.ssl()
>
> thank you
>
> ennma
> On 1/8/07, olen88 <olen88 at gmail.com> wrote:
> > Hello,
> >         I was wondering if anyone could point me in the right direction
> >         my system info:
> > Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on
> > win32
> >
> >         as the subject says. starttls() returns the following error,
> >
> > reply, null = session.starttls();
> > File "C:\Python24\lib\smtplib.py", line 601, in starttls
> > sslobj = socket.ssl(self.sock, keyfile, certfile)
> > AttributeError: 'module' object has no attribute 'ssl'
> >
> > I tried,
> >
> > import socket
> >
> > socket.ssl();
> >
> > same AttributeError exception was raised, so this confirmed that
> > socket.py has no ssl attribute.
> >
> > what can I do about this, some answers I digged up suggest
> >
> > http://mail.python.org/pipermail/python-list/2003-June/207802.html
> >
> > but I am hasty about this suggestion, and wishes to consult to you all
> > about what to do.
> >
> > Thank you
> >
> > ennma
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>

From olen88 at gmail.com  Tue Jan  9 19:06:33 2007
From: olen88 at gmail.com (Olen)
Date: Tue, 9 Jan 2007 13:06:33 -0500
Subject: [Tutor] Fwd:  smtplib starttls() error
In-Reply-To: <49b753370701072244h11398eecv8ea9cfc7dfde75f7@mail.gmail.com>
References: <45A1DEEE.2040509@gmail.com>
	<49b753370701072244h11398eecv8ea9cfc7dfde75f7@mail.gmail.com>
Message-ID: <49b753370701091006t5d6c3735i62f40a51ce4484b5@mail.gmail.com>

---------- Forwarded message ----------
From: Olen <olen88 at gmail.com>
Date: Jan 8, 2007 1:44 AM
Subject: Re: [Tutor] smtplib starttls() error
To: tutor at python.org


I have also looked in all the documentation python 2.4.3 files I downloaded
and this points out that I should have install the socket.ssl()
my question is that is how do I install the

socket.ssl()

thank you

ennma
On 1/8/07, olen88 <olen88 at gmail.com> wrote:
> Hello,
>         I was wondering if anyone could point me in the right direction
>         my system info:
> Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on
> win32
>
>         as the subject says. starttls() returns the following error,
>
> reply, null = session.starttls();
> File "C:\Python24\lib\smtplib.py", line 601, in starttls
> sslobj = socket.ssl(self.sock, keyfile, certfile)
> AttributeError: 'module' object has no attribute 'ssl'
>
> I tried,
>
> import socket
>
> socket.ssl();
>
> same AttributeError exception was raised, so this confirmed that
> socket.py has no ssl attribute.
>
> what can I do about this, some answers I digged up suggest
>
> http://mail.python.org/pipermail/python-list/2003-June/207802.html
>
> but I am hasty about this suggestion, and wishes to consult to you all
> about what to do.
>
> Thank you
>
> ennma
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From rajusubbanna at yahoo.com  Tue Jan  9 19:23:45 2007
From: rajusubbanna at yahoo.com (Hemantharaju Subbanna)
Date: Tue, 9 Jan 2007 10:23:45 -0800 (PST)
Subject: [Tutor] Before I start
Message-ID: <455253.23591.qm@web54605.mail.yahoo.com>

Hi,
Before I jump into the investigation, I wanted to ask
experts and get help/direction.

I am looking to develop a simple web application. 
What would be my best approach.

Thank you
Raju

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From rajusubbanna at yahoo.com  Tue Jan  9 19:25:47 2007
From: rajusubbanna at yahoo.com (Hemantharaju Subbanna)
Date: Tue, 9 Jan 2007 10:25:47 -0800 (PST)
Subject: [Tutor] Before I start
Message-ID: <20070109182547.26221.qmail@web54615.mail.yahoo.com>

Hi,
Before I jump into the investigation, I wanted to ask
experts and get help/direction.

I am looking to develop a simple web application. 
What would be my best approach? What package/s is good
to explore?

Need HTML GUI for Client (Qt plug-in may be ok).
Server application with database

Thank you
Raju

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From kent37 at tds.net  Tue Jan  9 19:49:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 09 Jan 2007 13:49:18 -0500
Subject: [Tutor] smtplib starttls() error
In-Reply-To: <45A1DEEE.2040509@gmail.com>
References: <45A1DEEE.2040509@gmail.com>
Message-ID: <45A3E3AE.3040003@tds.net>

olen88 wrote:
> Hello,
> 	I was wondering if anyone could point me in the right direction
> 	my system info:
> Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on 
> win32
> 
> 	as the subject says. starttls() returns the following error,
> 
> reply, null = session.starttls();
> File "C:\Python24\lib\smtplib.py", line 601, in starttls
> sslobj = socket.ssl(self.sock, keyfile, certfile)
> AttributeError: 'module' object has no attribute 'ssl'
> 
> I tried,
> 
> import socket
> 
> socket.ssl();
> 
> same AttributeError exception was raised, so this confirmed that
> socket.py has no ssl attribute.

Are you using the standard Python installer from python.org or something 
else? SSL support is a build option. It is included in the standard 
Python for Windows v2.3.5 and 2.4.4. Can you upgrade to the standard 
2.4.4 distribution and see if that works?
> 
> what can I do about this, some answers I digged up suggest
> 
> http://mail.python.org/pipermail/python-list/2003-June/207802.html
> 
> but I am hasty about this suggestion, and wishes to consult to you all
> about what to do.

I don't think that should be needed.

Kent


From nephish at gmail.com  Tue Jan  9 20:44:25 2007
From: nephish at gmail.com (shawn bright)
Date: Tue, 9 Jan 2007 13:44:25 -0600
Subject: [Tutor] question about pydev
Message-ID: <384c93600701091144j2ee3df1ek6adb841a9f2c48d5@mail.gmail.com>

hey there gents, i was wondering if anyone uses pydev ?
its a plugin for eclipse. Has lots of cool stuffs, but i don't like the way
it does code snippets,
when i paste one that is kinda long, it messes up the indentation.
anyone know a way around this ? i have posted this question on the pydev
sourceforge list ( about 2 weeks ago )
and have not heard anything, so thought i would ask the folk most likely to
be using it.

thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070109/922f365d/attachment.html 

From carroll at tjc.com  Wed Jan 10 02:24:42 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 9 Jan 2007 17:24:42 -0800 (PST)
Subject: [Tutor] smtplib starttls() error
In-Reply-To: <45A3E3AE.3040003@tds.net>
Message-ID: <Pine.LNX.4.44.0701091718510.782-100000@violet.rahul.net>

On Tue, 9 Jan 2007, Kent Johnson wrote:

> Are you using the standard Python installer from python.org or something 
> else? SSL support is a build option. It is included in the standard 
> Python for Windows v2.3.5 and 2.4.4. Can you upgrade to the standard 
> 2.4.4 distribution and see if that works?

I'm guessing that Olen is using Activestate's distribution, which does not 
include SSL for export control reasons:

   ActivePython does not include SSL support. Why is this, and how can I 
   add it?

   Here is an answer on python-list while discussing the differences
   between ActivePython and python.org's Python:


   http://mail.python.org/pipermail/python-list/2005-December/315754.html
   [http://mail.python.org/pipermail/python-list/2005-December/357227.html]

   ...
   - As Neil pointed out, ActivePython does not currently have SSL
     bindings (the _ssl module) that python.org's Python builds do. We
     are currently going through the legal hurdles so that we can
     include those.  I expect that by or before the Python 2.5
     timeframe we'll have _ssl in ActivePython.
   ...

   In the interim just plopping in the _ssl.pyd|so from either
   python.org's build or from your own build into ActivePython's
   lib-dynload directory will work to get ActivePython talking SSL.

http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/faq.html#ext_ssl



From wescpy at gmail.com  Wed Jan 10 06:55:20 2007
From: wescpy at gmail.com (wesley chun)
Date: Tue, 9 Jan 2007 21:55:20 -0800
Subject: [Tutor] Question about __name__ global variable (Was: Tutor
	Digest, Vol 35, Issue 27)
In-Reply-To: <45A39A0E.7030108@gmail.com>
References: <mailman.53.1168340418.17116.tutor@python.org>
	<bedebdfb0701090446l11113aeds377eebc0fb43ffdf@mail.gmail.com>
	<45A39A0E.7030108@gmail.com>
Message-ID: <78b3a9580701092155r5abdc61t4d2977e173a6a208@mail.gmail.com>

> The global variable __name__ is equal to '__main__' when the python
> script is run.
> If the script is imported, __name__ is something other than '__main__'
> (not sure what.)


it will be the name of your module.  so for foo.py, if you execute it
(as a script), __name__ == '__main__', but if you 'import foo',
__name__ == 'foo'.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From olen88 at gmail.com  Wed Jan 10 08:42:33 2007
From: olen88 at gmail.com (Olen)
Date: Wed, 10 Jan 2007 02:42:33 -0500
Subject: [Tutor] smtplib starttls() error
In-Reply-To: <Pine.LNX.4.44.0701091718510.782-100000@violet.rahul.net>
References: <45A3E3AE.3040003@tds.net>
	<Pine.LNX.4.44.0701091718510.782-100000@violet.rahul.net>
Message-ID: <49b753370701092342p51a3051k5d02296b2b67fca5@mail.gmail.com>

Hi Kent and Terry,
             Correct I am using Active state python,and did not read
the full information about installations. Thank you for for the
information.

I just need to confirm something, In python when we "upgrade" we
essentially install a new
version of python , and we would be needing to install what ever
custom packages we have previously installed right?

thank you once again

Olen


On 1/9/07, Terry Carroll <carroll at tjc.com> wrote:
> On Tue, 9 Jan 2007, Kent Johnson wrote:
>
> > Are you using the standard Python installer from python.org or something
> > else? SSL support is a build option. It is included in the standard
> > Python for Windows v2.3.5 and 2.4.4. Can you upgrade to the standard
> > 2.4.4 distribution and see if that works?
>
> I'm guessing that Olen is using Activestate's distribution, which does not
> include SSL for export control reasons:
>
>    ActivePython does not include SSL support. Why is this, and how can I
>    add it?
>
>    Here is an answer on python-list while discussing the differences
>    between ActivePython and python.org's Python:
>
>
>    http://mail.python.org/pipermail/python-list/2005-December/315754.html
>    [http://mail.python.org/pipermail/python-list/2005-December/357227.html]
>
>    ...
>    - As Neil pointed out, ActivePython does not currently have SSL
>      bindings (the _ssl module) that python.org's Python builds do. We
>      are currently going through the legal hurdles so that we can
>      include those.  I expect that by or before the Python 2.5
>      timeframe we'll have _ssl in ActivePython.
>    ...
>
>    In the interim just plopping in the _ssl.pyd|so from either
>    python.org's build or from your own build into ActivePython's
>    lib-dynload directory will work to get ActivePython talking SSL.
>
> http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/faq.html#ext_ssl
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From paulino1 at sapo.pt  Wed Jan 10 10:33:34 2007
From: paulino1 at sapo.pt (paulino1 at sapo.pt)
Date: Wed, 10 Jan 2007 09:33:34 +0000
Subject: [Tutor] CGI script: get the client user
Message-ID: <1168421614.1z15qmhj971c@w6.mail.sapo.pt>

I have some python CGI scripts running in an intranet.

I would like to get the user of the client browser to use it as an input in the
script, so it can show the the data related to that user.

There is the function getpass.getuser() that would return the user logged in the
server.

Is it possible to get the user in the client side with Python or I do I have to
use javascript for that purpose?


Thank you,

Paulino
___________________________________________________________________

O SAPO j? est? livre de v?rus com a Panda Software, fique voc? tamb?m!
Clique em: http://antivirus.sapo.pt


From dyoo at hkn.eecs.berkeley.edu  Wed Jan 10 11:22:32 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 10 Jan 2007 02:22:32 -0800 (PST)
Subject: [Tutor] CGI script: get the client user
In-Reply-To: <1168421614.1z15qmhj971c@w6.mail.sapo.pt>
References: <1168421614.1z15qmhj971c@w6.mail.sapo.pt>
Message-ID: <Pine.LNX.4.64.0701100154180.31777@hkn.eecs.berkeley.edu>



On Wed, 10 Jan 2007, paulino1 at sapo.pt wrote:

> I have some python CGI scripts running in an intranet.
>
> I would like to get the user of the client browser to use it as an input 
> in the script, so it can show the the data related to that user.
>
> There is the function getpass.getuser() that would return the user 
> logged in the server.


But people are supposed to be anonymous on the Internet, right?  *wink* I 
suspect that's less true on an Intranet.  Still, from the perspective of 
the server, you only know as much as the client is willing to share with 
you.  Login information isn't usually a part of that communication, so 
you'll need to make it explicitely so.


One thing you can do is ask the user explicitely for their authentication 
information, and save that as a "cookie" or some other session mechanism.

Think of a web-email application, such as Google Mail.  If it's the first 
time you visit a site like gmail, it begins a new session and asks for 
your login information.  I'd suspect that they implement sessions with 
cookies.  If so, then a cookie is saved on your web browser, and on 
subsequent interactions with the system, your web browser will pass those 
cookies off for the server to look at, in order to maintain the illusion 
of the system remembering who you are.

For examples and documentation of cookies, see:

     http://hkn.eecs.berkeley.edu/~dyoo/python/cookiecounter.py
     http://docs.python.org/lib/module-Cookie.html


However, doing the work necessary to set up authentication can be tedious 
code: people have done this stuff already.  Have you looked into a web 
development framework such as Django or web.py?  Both provide session 
support that you should be able to reuse.

From torhildrum at gmail.com  Wed Jan 10 11:28:24 2007
From: torhildrum at gmail.com (Tor Hildrum)
Date: Wed, 10 Jan 2007 11:28:24 +0100
Subject: [Tutor] Before I start
In-Reply-To: <20070109182547.26221.qmail@web54615.mail.yahoo.com>
References: <20070109182547.26221.qmail@web54615.mail.yahoo.com>
Message-ID: <f15641eb0701100228o2dbc783erc766d188539bfa49@mail.gmail.com>

On 1/9/07, Hemantharaju Subbanna <rajusubbanna at yahoo.com> wrote:
> Hi,
> Before I jump into the investigation, I wanted to ask
> experts and get help/direction.
>
> I am looking to develop a simple web application.
> What would be my best approach? What package/s is good
> to explore?
>
> Need HTML GUI for Client (Qt plug-in may be ok).
> Server application with database

Have a look at Turbogears or Django.

Tor

From kent37 at tds.net  Wed Jan 10 12:03:28 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 10 Jan 2007 06:03:28 -0500
Subject: [Tutor] Before I start
In-Reply-To: <455253.23591.qm@web54605.mail.yahoo.com>
References: <455253.23591.qm@web54605.mail.yahoo.com>
Message-ID: <45A4C800.7000201@tds.net>

Hemantharaju Subbanna wrote:
> Hi,
> Before I jump into the investigation, I wanted to ask
> experts and get help/direction.
> 
> I am looking to develop a simple web application. 
> What would be my best approach.

We just discussed this:
http://mail.python.org/pipermail/tutor/2007-January/051816.html

Kent


From kent37 at tds.net  Wed Jan 10 12:05:55 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 10 Jan 2007 06:05:55 -0500
Subject: [Tutor] smtplib starttls() error
In-Reply-To: <49b753370701092342p51a3051k5d02296b2b67fca5@mail.gmail.com>
References: <45A3E3AE.3040003@tds.net>	<Pine.LNX.4.44.0701091718510.782-100000@violet.rahul.net>
	<49b753370701092342p51a3051k5d02296b2b67fca5@mail.gmail.com>
Message-ID: <45A4C893.4000701@tds.net>

Olen wrote:
> Hi Kent and Terry,
>              Correct I am using Active state python,and did not read
> the full information about installations. Thank you for for the
> information.
> 
> I just need to confirm something, In python when we "upgrade" we
> essentially install a new
> version of python , and we would be needing to install what ever
> custom packages we have previously installed right?

For major version upgrades (2.x -> 2.x+1) that is correct. For minor 
upgrades (2.x.y -> 2.x.y+1) the new version usually installs over the 
old and uses the same custom packages. I don't know what happens if you 
install the python.org distribution over an ActiveState distribution, 
though.

Kent


From nswitanek at stanford.edu  Wed Jan 10 07:13:06 2007
From: nswitanek at stanford.edu (Switanek, Nick)
Date: Tue, 9 Jan 2007 22:13:06 -0800
Subject: [Tutor] setting lists
In-Reply-To: <mailman.7384.1168368565.32030.tutor@python.org>
Message-ID: <21EB45BA6A0A4844B97D46A7721CFDF202DE2FF7@gsb-exchmb02.stanford.edu>

I'd like to remove redundant items from a list, and have read that using
set() is an effective way to do it. But I often get the following error,
and I'd be glad for your help understanding what's wrong.

>>> z = ['test','test',1,2,1]
>>> set(z)
set(['test', 1, 2])
>>> list(set(z))	# Works as I expect
['test', 1, 2]

>>> type(n)		# This is a list of lists of strings
<type 'list'>
>>> n1 = list(set(n))
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: list objects are unhashable

From kent37 at tds.net  Wed Jan 10 14:04:56 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 10 Jan 2007 08:04:56 -0500
Subject: [Tutor] setting lists
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF202DE2FF7@gsb-exchmb02.stanford.edu>
References: <21EB45BA6A0A4844B97D46A7721CFDF202DE2FF7@gsb-exchmb02.stanford.edu>
Message-ID: <45A4E478.9070405@tds.net>

Switanek, Nick wrote:
> I'd like to remove redundant items from a list, and have read that using
> set() is an effective way to do it. But I often get the following error,
> and I'd be glad for your help understanding what's wrong.
> 
>>>> type(n)		# This is a list of lists of strings
> <type 'list'>
>>>> n1 = list(set(n))
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> TypeError: list objects are unhashable

So you have a list of lists of strings and you want to remove 
duplicates? The problem is that sets (and dicts) require that their 
values (or keys) be hashable, which means that a unique, unchanging 
reference number can be computed from the value. Practically speaking 
this means that the value must be immutable (unable to be changed) which 
excludes lists.

The solution is to turn the list into something immutable. One way would 
be to convert the lists to tuples:
n1 = list(set(tuple(i) for i in n))

This gives you a list of tuples, if you need a list of lists you will 
have to convert back which you can do with a list comprehension:
n1 = [ list(j) for j in set(tuple(i) for i in n)) ]

Another way would be to use the string representation of the list as a 
dictionary key and the original list as the value, then pull the 
original lists back out:
n1 = dict((repr(i), i) for i in n).values()

Kent


From marshallpenguin at gmail.com  Wed Jan 10 18:19:41 2007
From: marshallpenguin at gmail.com (Joey Marshall)
Date: Wed, 10 Jan 2007 14:19:41 -0300
Subject: [Tutor] Colorize an image with PIL
Message-ID: <73cf534f0701100919p2b43867crdc214748fe20208a@mail.gmail.com>

hello,
I tried asking this on the image-sig mailing list but didn't get an
complete answer.
I am having a difficulty with developing my game. I would like to
colorize the outfits on my penguins
(http://joey101.net/projects/snowballz/). I have them separated out to
make it easier to colorize... but I haven't been able to figure out
how to.

I already have PIL as a dependency for snowballz so I would like to
use it, but there is nothing in PIL to do this easily. Does anyone
know how to colorize an image? (all images are (RGBA) in red and I
would like to be able to use a color like: (0,0,255) to colorize it
to)

Any help would be awesome.

Thanks!
Joey


-- 
http://joey101.net - my blog on web development

From carroll at tjc.com  Wed Jan 10 19:12:07 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 10 Jan 2007 10:12:07 -0800 (PST)
Subject: [Tutor] smtplib starttls() error
In-Reply-To: <45A4C893.4000701@tds.net>
Message-ID: <Pine.LNX.4.44.0701101006100.21264-100000@violet.rahul.net>

On Wed, 10 Jan 2007, Kent Johnson wrote:

> For major version upgrades (2.x -> 2.x+1) that is correct. For minor 
> upgrades (2.x.y -> 2.x.y+1) the new version usually installs over the 
> old and uses the same custom packages. I don't know what happens if you 
> install the python.org distribution over an ActiveState distribution, 
> though.

I have no firsthand knowledge here, but I would suggest following the 
approach Activestate's page recommends.  Install the python.org 
distribution to a separate directory (actually, if possible, I'd do it on 
a different machine, so the install process doesn't mess up your paths 
and file associations), and copy out the two ssl files to the ActivePython 
directory.  Again, verify that the install process didn't muck up your 
path, file associations, or anything else; and if it did, fix it manually.

Or else maybe someone on this list can volunteer to email him the two SSL
files.  (I would, but I'm an Activestate user, too, so I don't have them
either.)


From kent37 at tds.net  Wed Jan 10 21:06:49 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 10 Jan 2007 15:06:49 -0500
Subject: [Tutor] setting lists
In-Reply-To: <45A4E478.9070405@tds.net>
References: <21EB45BA6A0A4844B97D46A7721CFDF202DE2FF7@gsb-exchmb02.stanford.edu>
	<45A4E478.9070405@tds.net>
Message-ID: <45A54759.4000706@tds.net>

Kent Johnson wrote:
> The solution is to turn the list into something immutable. One way would 
> be to convert the lists to tuples:
> n1 = list(set(tuple(i) for i in n))
> 
> This gives you a list of tuples, if you need a list of lists you will 
> have to convert back which you can do with a list comprehension:
> n1 = [ list(j) for j in set(tuple(i) for i in n)) ]
> 
> Another way would be to use the string representation of the list as a 
> dictionary key and the original list as the value, then pull the 
> original lists back out:
> n1 = dict((repr(i), i) for i in n).values()

You could combine these two, use a tuple as the key but retain the list:
n1 = dict((tuple(i), i) for i in n).values()

I think I like this the best, it avoids the conversion from tuple back 
to list, and I suspect that converting a list to a tuple - which should 
involve just copying references to the list contents - is quicker than 
converting it to a string.

Kent


From pytutmail at gmail.com  Wed Jan 10 22:30:45 2007
From: pytutmail at gmail.com (Toon Pieton)
Date: Wed, 10 Jan 2007 22:30:45 +0100
Subject: [Tutor] Creating folders
Message-ID: <7c3104d20701101330h6b040e7cs65f5ac6c1b4d2005@mail.gmail.com>

Hey friendly users!

My question is pretty simple. How can I create a folder with Python? Trying
to make a program which will allow me to save my notes (txt files) quickly
and cleanly. Having to create folder manually would really make it a bit
obsolete.

Thanks in advance!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070110/31f6297c/attachment.html 

From Mike.Hansen at atmel.com  Wed Jan 10 22:55:28 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Wed, 10 Jan 2007 14:55:28 -0700
Subject: [Tutor] Creating folders
Message-ID: <57B026980605A64F9B23484C5659E32E4C76F2@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Toon Pieton
> Sent: Wednesday, January 10, 2007 2:31 PM
> To: tutor
> Subject: [Tutor] Creating folders
> 
> Hey friendly users!
> 
> My question is pretty simple. How can I create a folder with 
> Python? Trying to make a program which will allow me to save 
> my notes (txt files) quickly and cleanly. Having to create 
> folder manually would really make it a bit obsolete. 
> 
> Thanks in advance!
> 
>

http://docs.python.org/lib/os-file-dir.html

os.mkdir

Mike 
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS

From cspears2002 at yahoo.com  Thu Jan 11 00:20:16 2007
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Wed, 10 Jan 2007 15:20:16 -0800 (PST)
Subject: [Tutor] rename files
Message-ID: <848366.72136.qm@web51609.mail.yahoo.com>

I'm trying to write a script that will rename files. 
The files are in this format: 

replace_dashes_stuff03

I want to rename the files to

replace.dashes.STF.v03

Here is what I have so far:

#!/usr/bin/python

import os,sys

oldFile = sys.argv[1]

if oldFile.find('_') != -1:
	print "Found dashes!"
	newFile_without_dashes = oldFile.replace('_','.')
	print newFile_without_dashes
	#os.rename(oldFile,newFile)
else:
	print "No dashes!"
	
if newFile_without_dashes.find('stuff') != -1:
	print "Found db!"
	newFile_without_db =
newFile_without_dashes.replace('stuff','STF')
	print newFile_without_db
	#os.rename(oldFile,newFile_without_db)
	 
Here is the result:

io at io-station-1 ./bin 125> replace_dashes.py
replace_dashes_stuff03
Found dashes!
replace.dashes.stuff03
Found db!
replace.dashes.STF03

Is there a more elegant way to do this?  I haven't
figure out how to convert stuff03 to STF.v03.

THanks!

From bds at waywood.co.uk  Thu Jan 11 00:34:17 2007
From: bds at waywood.co.uk (Barnaby Scott)
Date: Wed, 10 Jan 2007 23:34:17 +0000
Subject: [Tutor] string.uppercase: too many for locale
Message-ID: <45A577F9.8020208@waywood.co.uk>

Can anyone explain the following: I was getting string.uppercase 
returning an unexpected number of characters, given that the Python Help 
says that it should normally be A-Z. Being locale-dependent, I checked 
that my locale was not set to something exotic, and sure enough it is 
only what I expected - see below:


IDLE 1.1      ==== No Subprocess ====
 >>> import locale, string
 >>> locale.getlocale()
['English_United Kingdom', '1252']
 >>> print string.uppercase
ABCDEFGHIJKLMNOPQRSTUVWXYZ??????????????????????????????????
 >>> print string.lowercase
abcdefghijklmnopqrstuvwxyz????????????????????????????????????
 >>>

What am I missing here? Surely for UK English, I really should just be 
getting A-Z and a-z. In case it is relevant, the platform is Windows 2000.

Thanks

Barnaby Scott

From gtnorton at earthlink.net  Thu Jan 11 01:11:56 2007
From: gtnorton at earthlink.net (Glenn T Norton)
Date: Wed, 10 Jan 2007 18:11:56 -0600
Subject: [Tutor] Creating folders
In-Reply-To: <7c3104d20701101330h6b040e7cs65f5ac6c1b4d2005@mail.gmail.com>
References: <7c3104d20701101330h6b040e7cs65f5ac6c1b4d2005@mail.gmail.com>
Message-ID: <45A580CC.2050908@earthlink.net>

Toon Pieton wrote:

> Hey friendly users!
>
> My question is pretty simple. How can I create a folder with Python? 
> Trying to make a program which will allow me to save my notes (txt 
> files) quickly and cleanly. Having to create folder manually would 
> really make it a bit obsolete.
>
> Thanks in advance!
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
import os
os.mkdir(name_of_directory, permissions)

 >>> print os.mkdir.__doc__

Glenn

-- 
"Ketchup. For the good times... " - Ketchup Advisory Board 
Glenn Norton
Application Developer
Nebraska.gov
1-402-471-2777
glenn at nebraska.gov


From kent37 at tds.net  Thu Jan 11 01:20:45 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 10 Jan 2007 19:20:45 -0500
Subject: [Tutor] rename files
In-Reply-To: <848366.72136.qm@web51609.mail.yahoo.com>
References: <848366.72136.qm@web51609.mail.yahoo.com>
Message-ID: <45A582DD.9050501@tds.net>

Christopher Spears wrote:
> Is there a more elegant way to do this?  I haven't
> figure out how to convert stuff03 to STF.v03.

Just replace 'stuff' with 'STF.v' instead of 'STF' ? Or am I missing 
something?

You don't have to do the find(), you can just replace(); if the string 
being replaced is not there, nothing will be changed.

Kent


From kent37 at tds.net  Thu Jan 11 01:28:46 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 10 Jan 2007 19:28:46 -0500
Subject: [Tutor] string.uppercase: too many for locale
In-Reply-To: <45A577F9.8020208@waywood.co.uk>
References: <45A577F9.8020208@waywood.co.uk>
Message-ID: <45A584BE.2050700@tds.net>

Barnaby Scott wrote:
> Can anyone explain the following: I was getting string.uppercase 
> returning an unexpected number of characters, given that the Python Help 
> says that it should normally be A-Z. Being locale-dependent, I checked 
> that my locale was not set to something exotic, and sure enough it is 
> only what I expected - see below:
> 
> 
> IDLE 1.1      ==== No Subprocess ====
>  >>> import locale, string
>  >>> locale.getlocale()
> ['English_United Kingdom', '1252']
>  >>> print string.uppercase
> ABCDEFGHIJKLMNOPQRSTUVWXYZ??????????????????????????????????
>  >>> print string.lowercase
> abcdefghijklmnopqrstuvwxyz????????????????????????????????????
>  >>>
> 
> What am I missing here? Surely for UK English, I really should just be 
> getting A-Z and a-z. In case it is relevant, the platform is Windows 2000.

Interesting. Here is what I get:
 >>> import locale, string
 >>> locale.getlocale()
(None, None)
 >>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

Somehow the locale for your system has changed from the 'C' locale. If I 
set the default locale I get similar results to yours:
 >>> locale.setlocale(locale.LC_ALL, '')
'English_United States.1252'
 >>> locale.getlocale()
('English_United States', '1252')
 >>> print string.uppercase
ABCDEFGHIJKLMNOPQRSTUVWXYZ??????????????????????????????????

which doesn't print correctly because my console encoding is actually 
cp437 not cp1252.

It looks like string.uppercase is giving you all the characters which 
are uppercase in the current encoding, which seems reasonable. You can 
use string.ascii_uppercase if you want just A-Z.

Kent


From andrew.arobert at gmail.com  Thu Jan 11 01:51:05 2007
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Wed, 10 Jan 2007 19:51:05 -0500
Subject: [Tutor] Question on joining out of order dictionary elements
Message-ID: <fd85eb130701101651h6155318cgcfd39da4738619ed@mail.gmail.com>

Hi everyone,

I have a quick quick question joining out of order dictionary values.

For example:

I created an empty

>>> config={}

Added some key/value pairs

>>> config["test1"]="elem1"
>>> config["test2"]="elem2"
>>> config["test3"]="elem3"
....
  etc
>>>

Dumped the values and joined them at the same time.

>>> print "\\".join(config.values())
elem1\elem3\elem2

This is fine but it doesn't entirely solve the issue.

Only some of the key/value pairs in the dictionary are needed so a
dump of all values does not work.

Also, the order in which the values are joined is important so walking
through and joining all values does not work either.


The simplest way would be to do something like:

>>> print "\\".join((config["val2"],config["val1"],config["val3"]))
elem2\elem1\elem3

or

>>> print "%s\\%s\\%s" % (config["val2"],config["val1"],config["val3"])
elem2\elem1\elem3

but this seems somehow uneligent.

Are there a more efficient/compact ways of doing this kind of
operation or is this it?

The key/value pairs in these examples are contrived for purposes of
this discussion but the end goal is to piece together server and
directory path information for use with pysvn.

I have a Perl programmer who is learning Python and he is griping that
this kind of operation is far simpler in Perl.

-- 
Thank you,
Andrew Robert

Senior MQ Engineer
Information Technologies
Massachusetts Financial Services
Phone: 617-954-5882

From john at fouhy.net  Thu Jan 11 02:00:23 2007
From: john at fouhy.net (John Fouhy)
Date: Thu, 11 Jan 2007 14:00:23 +1300
Subject: [Tutor] Question on joining out of order dictionary elements
In-Reply-To: <fd85eb130701101651h6155318cgcfd39da4738619ed@mail.gmail.com>
References: <fd85eb130701101651h6155318cgcfd39da4738619ed@mail.gmail.com>
Message-ID: <5e58f2e40701101700g2ff73db6rd9ace35ee3767d29@mail.gmail.com>

On 11/01/07, Andrew Robert <andrew.arobert at gmail.com> wrote:
> Only some of the key/value pairs in the dictionary are needed so a
> dump of all values does not work.
>
> Also, the order in which the values are joined is important so walking
> through and joining all values does not work either.

Well, a dictionary is by definition unordered, so you will need to
tell python which elements you want, and in which order.

I would do something like this:

####
config = {}
# insert code here to set the values of config

keysToDump = ['test1', 'test2', 'test3']
output = '\\'.join(config[k] for k in keysToDump)
####

(note that, if you are using python2.3 or earlier, you will need to
write that last line as:

output = '\\'.join([config[k] for k in keysToDump])

)

HTH!

-- 
John.

From cspears2002 at yahoo.com  Thu Jan 11 02:50:28 2007
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Wed, 10 Jan 2007 17:50:28 -0800 (PST)
Subject: [Tutor] removing padded numbers
In-Reply-To: <mailman.7600.1168472736.32030.tutor@python.org>
Message-ID: <20070111015028.89171.qmail@web51608.mail.yahoo.com>

Does anyone how to remove padded numbers with python? 
I want to be able to take a file like

afile.0001.cin

and convert it to

afile.1.cin

I've been checking the docs but nothing jumps out at
me.  

Thanks!

From kent37 at tds.net  Thu Jan 11 03:43:28 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 10 Jan 2007 21:43:28 -0500
Subject: [Tutor] removing padded numbers
In-Reply-To: <20070111015028.89171.qmail@web51608.mail.yahoo.com>
References: <20070111015028.89171.qmail@web51608.mail.yahoo.com>
Message-ID: <45A5A450.8040307@tds.net>

Christopher Spears wrote:
> Does anyone how to remove padded numbers with python? 
> I want to be able to take a file like
> 
> afile.0001.cin
> 
> and convert it to
> 
> afile.1.cin

The straightforward way is just to pick it apart and put it back 
together the way you want it:

 >>> a, b, c = 'afile.0001.cin'.split('.')
 >>> '%s.%s.%s' % (a, b.lstrip('0'), c)
'afile.1.cin'

Or if you prefer, here is an obscure one-liner using the ability of 
re.sub() to take a callable as the replacement argument. (That is a 
pretty cool feature but overkill here...) This one replaces any run of 
digits with the same digits with leading zeros removed:

 >>> import re
 >>> re.sub(r'\d+', lambda m: m.group().lstrip('0'), 'afile.0001.cin')
'afile.1.cin'

Kent


From David.Barton at nottingham.ac.uk  Thu Jan 11 10:00:34 2007
From: David.Barton at nottingham.ac.uk (Barton David)
Date: Thu, 11 Jan 2007 09:00:34 -0000
Subject: [Tutor] feeding data to subprocess exes and getting results
	without writing files
Message-ID: <BAA2EE790D828F4E8B262F17B3B0A7A3026BE9EF@VUIEXCH1.ad.nottingham.ac.uk>

Thanks Chris,

I figured it out after a while..

import subprocess
inputtext="my input string"
process=subprocess.Popen("myprog.exe -i stdin -o
stdout",stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.S
TDOUT)
outputtext,errortext=process.communicate(inputtext)
 
..so it is fairly simple after all.

Thanks for the help,
Dave

(ps I inadvertantly replied directly to you Chris, rather than the
mailing list- sorry-, so this is just for posterity in case anybody else
wants to know the solution)


-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
Behalf Of Christopher Arndt
Sent: 09 January 2007 14:26
To: Tutor at python.org
Subject: Re: [Tutor] feeding data to subprocess exes and getting results
without writing files

Barton David schrieb:
> I just can't wrap my head around stdin, stdout and the whole pipes 
> thing, but there's got to be a relatively simple way to do this,
surely?

You have to distinguish between three different concepts:

1) file names
2) file objects
3) file contents

1) Is just a string with some identifier (the file path). To use a file
with that identifier in Python, you have to create a file object from it
by using the builtin 'open' function.

2) File objects are builtin Python objects that are usually created by
the 'open' function or returned by some other function. There are a few
file objects that are already opened and accessible to your Python
program. These are sys.stdin, sys.stderr and sys.stdout. They are file
objects, *not* strings representing the (non-existant) file name or file
content!

3) File contents are just represented by binary strings in Python. You
read/write them with the appropriate methods of file objects.

==> The subprocess.Popen constructor expects *file objects* not strings
for its 'stdin' and 'stdout' arguments. Read the documentation of
subprocess.Popen very carefully again (ignore references to file
*descriptors*).

BTW: a pipe is just an object or function that reads from one file
object and writes to another.

Chris
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor

This message has been checked for viruses but the contents of an attachment
may still contain software viruses, which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.


From bds at waywood.co.uk  Thu Jan 11 10:27:50 2007
From: bds at waywood.co.uk (Barnaby Scott)
Date: Thu, 11 Jan 2007 09:27:50 +0000
Subject: [Tutor] string.uppercase: too many for locale
Message-ID: <45A60316.6040800@waywood.co.uk>

Kent Johnson wrote:
> Barnaby Scott wrote:
>> Can anyone explain the following: I was getting string.uppercase 
>> returning an unexpected number of characters, given that the Python 
>> Help says that it should normally be A-Z. Being locale-dependent, I 
>> checked that my locale was not set to something exotic, and sure 
>> enough it is only what I expected - see below:
>>
>>
>> IDLE 1.1      ==== No Subprocess ====
>>  >>> import locale, string
>>  >>> locale.getlocale()
>> ['English_United Kingdom', '1252']
>>  >>> print string.uppercase
>> ABCDEFGHIJKLMNOPQRSTUVWXYZ??????????????????????????????????
>>  >>> print string.lowercase
>> abcdefghijklmnopqrstuvwxyz????????????????????????????????????
>>  >>>
>>
>> What am I missing here? Surely for UK English, I really should just be 
>> getting A-Z and a-z. In case it is relevant, the platform is Windows 
>> 2000.
> 
> Interesting. Here is what I get:
>  >>> import locale, string
>  >>> locale.getlocale()
> (None, None)
>  >>> string.uppercase
> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
> 
> Somehow the locale for your system has changed from the 'C' locale. If I 
> set the default locale I get similar results to yours:
>  >>> locale.setlocale(locale.LC_ALL, '')
> 'English_United States.1252'
>  >>> locale.getlocale()
> ('English_United States', '1252')
>  >>> print string.uppercase
> ABCDEFGHIJKLMNOPQRSTUVWXYZ??????????????????????????????????
> 
> which doesn't print correctly because my console encoding is actually 
> cp437 not cp1252.
> 
> It looks like string.uppercase is giving you all the characters which 
> are uppercase in the current encoding, which seems reasonable. You can 
> use string.ascii_uppercase if you want just A-Z.
> 
> Kent
> 
Thanks, but this raises various questions:

Why would my locale have 'changed' - and from what?
What *would* be the appropriate locale given that I am in the UK and use
English, and how would I set it?
Why on earth does the ['English_United Kingdom', '1252'] locale setting
consider ?????????????????????????????????? to be appropriate?
Is this less to do with Python than the operating system?
Where can I read more on the subject?

Sorry for all the open-ended questions, but I am baffled by this and can
find no information. Sadly, just using string.ascii_uppercase is not a
solution because I am trying to develop something for different locales,
but only want the actual letters that a particular language uses to be
returned - e.g. English should be A-Z only, Swedish should be A-Z + ???
(only) etc. The thing I really want to avoid is having to hard-code for
every language on the planet - surely this is the whole point of locale
settings, and locale-dependent functions and constants?

Thanks

Barnaby Scott


From carloslara at web.de  Thu Jan 11 11:20:35 2007
From: carloslara at web.de (Carlos)
Date: Thu, 11 Jan 2007 11:20:35 +0100
Subject: [Tutor] Image Question, List of Image Colors
In-Reply-To: <mailman.7156.1168225183.32030.tutor@python.org>
References: <mailman.7156.1168225183.32030.tutor@python.org>
Message-ID: <45A60F73.4090103@web.de>

Hello,

Could someone who is familiar with image manipulation tell me what is 
the best way to obtain the list of colors inside an image?

By best I'm referring to something that gets the job done in the fastest 
way, because this operation will be repeated a number of times.

Thanks for your help,
Carlos


From wesbrooks at gmail.com  Thu Jan 11 11:21:06 2007
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Thu, 11 Jan 2007 10:21:06 +0000
Subject: [Tutor] Finding the key for a value in a dictionary.
Message-ID: <eec9f8ee0701110221w185ce4e5i65fa425c129585e1@mail.gmail.com>

Dear Users,

I'm trying to find the key of a unique value within a dictionary. Is
the code bellow a safe way of doing so, or is there a better way of
doing it?

a = {'de':'df', 'gf':'hg'}
key = a.keys()[a.values().index('hg')]

Thanks for your help,

Yours Faithfully,

Wesley Brooks

From vgvr620034 at gmail.com  Thu Jan 11 11:45:44 2007
From: vgvr620034 at gmail.com (raghu raghu)
Date: Thu, 11 Jan 2007 16:15:44 +0530
Subject: [Tutor]  Question on joining out of order dictionary elements
Message-ID: <bedebdfb0701110245q5bef8beeo4209b1e9ebad7b80@mail.gmail.com>

Hi everyone,

I have a quick quick question joining out of order dictionary values.

For example:

I created an empty

>>> config={}

Added some key/value pairs

>>> config["test1"]="elem1"
>>> config["test2"]="elem2"
>>> config["test3"]="elem3"
....
 etc
>>>

Dumped the values and joined them at the same time.

>>> print "\\".join(config.values())
elem1\elem3\elem2

This is fine but it doesn't entirely solve the issue.

Only some of the key/value pairs in the dictionary are needed so a
dump of all values does not work.

Also, the order in which the values are joined is important so walking
through and joining all values does not work either.


The simplest way would be to do something like:

>>> print "\\".join((config["val2"],config["val1"],config["val3"]))
elem2\elem1\elem3

or

>>> print "%s\\%s\\%s" % (config["val2"],config["val1"],config["val3"])
elem2\elem1\elem3

but this seems somehow uneligent.

Are there a more efficient/compact ways of doing this kind of
operation or is this it?

The key/value pairs in these examples are contrived for purposes of
this discussion but the end goal is to piece together server and
directory path information for use with pysvn.

I have a Perl programmer who is learning Python and he is griping that
this kind of operation is far simpler in Perl.

To print or to retain individual values from a list,it has to be written in
the form of
config={'test1':'elem1','test2':'elem2','test3':'elem3'}
config['test4'] = 'elem4'
print config.values()
print config['test1']- To get individual values from a list
If we want to retrieve all the values or say 2 from 4 its not possible to
put in a while loop and get that as a list only takes one argument at a time
better way is to extract individually and respective keys could not be
obtained if corresponding values are given.



-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070111/8fbee283/attachment.html 

From kent37 at tds.net  Thu Jan 11 11:58:13 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 11 Jan 2007 05:58:13 -0500
Subject: [Tutor] Finding the key for a value in a dictionary.
In-Reply-To: <eec9f8ee0701110221w185ce4e5i65fa425c129585e1@mail.gmail.com>
References: <eec9f8ee0701110221w185ce4e5i65fa425c129585e1@mail.gmail.com>
Message-ID: <45A61845.2060305@tds.net>

Wesley Brooks wrote:
> Dear Users,
> 
> I'm trying to find the key of a unique value within a dictionary. Is
> the code bellow a safe way of doing so, or is there a better way of
> doing it?
> 
> a = {'de':'df', 'gf':'hg'}
> key = a.keys()[a.values().index('hg')]

This is safe, as long as the dict is not being modified (by another 
thread, presumably) while this is going on - the docs for dict 
explicitly guarantee that the order of items in a.keys() and a.values() 
will correspond as long as a doesn't change.

Whether it is a good solution or not, I don't know. It sounds like your 
dictionary is backwards, maybe, if you are looking up by value.

Kent


From wesbrooks at gmail.com  Thu Jan 11 12:09:07 2007
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Thu, 11 Jan 2007 11:09:07 +0000
Subject: [Tutor] Finding the key for a value in a dictionary.
In-Reply-To: <45A61845.2060305@tds.net>
References: <eec9f8ee0701110221w185ce4e5i65fa425c129585e1@mail.gmail.com>
	<45A61845.2060305@tds.net>
Message-ID: <eec9f8ee0701110309j1a0de2aeifbead416ab89c18a@mail.gmail.com>

Cheers for the reply.

I'm creating a custom dictionary that I can use to store list of
unique objects used in a GUI. Items are added then a unique string is
returned. I have used this approach so if an item is deleted from the
storage dictionary I can still find it using the key, where as if I
had used a list I would have to update all references to an object if
an object before it in the list was deleted as it's index would
change.

Wesley.

On 11/01/07, Kent Johnson <kent37 at tds.net> wrote:
> Wesley Brooks wrote:
> > Dear Users,
> >
> > I'm trying to find the key of a unique value within a dictionary. Is
> > the code bellow a safe way of doing so, or is there a better way of
> > doing it?
> >
> > a = {'de':'df', 'gf':'hg'}
> > key = a.keys()[a.values().index('hg')]
>
> This is safe, as long as the dict is not being modified (by another
> thread, presumably) while this is going on - the docs for dict
> explicitly guarantee that the order of items in a.keys() and a.values()
> will correspond as long as a doesn't change.
>
> Whether it is a good solution or not, I don't know. It sounds like your
> dictionary is backwards, maybe, if you are looking up by value.
>
> Kent
>
>

From kent37 at tds.net  Thu Jan 11 12:10:15 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 11 Jan 2007 06:10:15 -0500
Subject: [Tutor] string.uppercase: too many for locale
In-Reply-To: <45A60316.6040800@waywood.co.uk>
References: <45A60316.6040800@waywood.co.uk>
Message-ID: <45A61B17.5080509@tds.net>

Barnaby Scott wrote:
> Thanks, but this raises various questions:

I am in no way an expert on this, I am guessing...if anyone else knows 
for sure what is going on, please let me know!
> 
> Why would my locale have 'changed' - and from what?

The docs for the locale module say "According to POSIX, a program which 
has not called setlocale(LC_ALL, '') runs using the portable 'C' 
locale. Calling setlocale(LC_ALL, '') lets it use the default locale as 
defined by the LANG variable." So "from what" is the so-called 'C' 
locale; this is the setting on my machine. Why it would change I don't 
know - due to an environment variable setting or perhaps a setlocale() 
call in sitecustomize.py?

> What *would* be the appropriate locale given that I am in the UK and use
> English, and how would I set it?

I think your locale is appropriate...

> Why on earth does the ['English_United Kingdom', '1252'] locale setting
> consider ?????????????????????????????????? to be appropriate?

The locale specifies 1252 as the encoding. Presumably this is Windows 
code page 1252. All of the characters you list are valid uppercase 
characters in that encoding.

> Is this less to do with Python than the operating system?

Python's locale capabilities are built on those of the underlying C 
language so that is probably where this is coming from.

> Where can I read more on the subject?

comp.lang.python is where I would start, ask your question there. State 
you confusion and ask your real question - how do I find out the actual 
uppercase letters for the language in use? If you come at it from 
"Python is broken, why does it do such a stupid thing" you will get the 
explanation of why it is not broken rather than the solution to your 
problem.

Kent

> 
> Sorry for all the open-ended questions, but I am baffled by this and can
> find no information. Sadly, just using string.ascii_uppercase is not a
> solution because I am trying to develop something for different locales,
> but only want the actual letters that a particular language uses to be
> returned - e.g. English should be A-Z only, Swedish should be A-Z + ???
> (only) etc. The thing I really want to avoid is having to hard-code for
> every language on the planet - surely this is the whole point of locale
> settings, and locale-dependent functions and constants?
> 
> Thanks
> 
> Barnaby Scott
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



From rdm at rcblue.com  Thu Jan 11 13:36:40 2007
From: rdm at rcblue.com (Dick Moores)
Date: Thu, 11 Jan 2007 04:36:40 -0800
Subject: [Tutor] Psyco Puzzle
Message-ID: <7.0.1.0.2.20070111041220.07766ad8@rcblue.com>

Sometimes psyco speeds up a script by a factor of 10, and sometimes 
it makes no difference at all. Here's a case where I fully expected 
it to make a difference: 
<http://www.rcblue.com/Python/Psyco_Puzzle.txt>. Whether using psyco 
or not, this takes about 13 seconds on my computer. Why no difference?

Here's a script where psyco makes a big difference: 
<http://www.rcblue.com/Python/2primes1-a2.py>. 1.8 seconds with 
psyco, vs. 12.7. without.seconds.

Thanks,

Dick Moores
Win XP
Python 2.5
psyco for Python 2.5


From kent37 at tds.net  Thu Jan 11 13:46:53 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 11 Jan 2007 07:46:53 -0500
Subject: [Tutor] Image Question, List of Image Colors
In-Reply-To: <45A60F73.4090103@web.de>
References: <mailman.7156.1168225183.32030.tutor@python.org>
	<45A60F73.4090103@web.de>
Message-ID: <45A631BD.4090906@tds.net>

Carlos wrote:
> Hello,
> 
> Could someone who is familiar with image manipulation tell me what is 
> the best way to obtain the list of colors inside an image?
> 
> By best I'm referring to something that gets the job done in the fastest 
> way, because this operation will be repeated a number of times.

The Image object in the Python Imaging Library has a getcolors() method 
that seems to do what you want.
http://www.pythonware.com/library/pil/handbook/image.htm

Kent


From andreengels at gmail.com  Thu Jan 11 14:34:52 2007
From: andreengels at gmail.com (Andre Engels)
Date: Thu, 11 Jan 2007 14:34:52 +0100
Subject: [Tutor] Question on joining out of order dictionary elements
In-Reply-To: <bedebdfb0701110245q5bef8beeo4209b1e9ebad7b80@mail.gmail.com>
References: <bedebdfb0701110245q5bef8beeo4209b1e9ebad7b80@mail.gmail.com>
Message-ID: <6faf39c90701110534g33b504can1dca778f29e6935@mail.gmail.com>

2007/1/11, raghu raghu <vgvr620034 at gmail.com>:

> >>> print "\\".join((config["val2"],config["val1"],config["val3"]))
> elem2\elem1\elem3
>
> or
>
> >>> print "%s\\%s\\%s" % (config["val2"],config["val1"],config["val3"])
> elem2\elem1\elem3
>
> but this seems somehow uneligent.
>
> Are there a more efficient/compact ways of doing this kind of
> operation or is this it?
>

Maybe you like:
print "\\".join([config[val] for val in ["val2","val1","val3"]])

-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070111/86d36510/attachment.htm 

From jeff at taupro.com  Thu Jan 11 14:41:45 2007
From: jeff at taupro.com (Jeff Rush)
Date: Thu, 11 Jan 2007 07:41:45 -0600
Subject: [Tutor] Reminder: Early Bird Registration for PyCon Ending Soon
Message-ID: <45A63E99.7050009@taupro.com>

Greetings.  As co-chair for the upcoming volunteer-run conference in the 
Dallas (Addison) area I would like to extend a *special* invitation to those 
just getting started with Python.  PyCon is not just for the experts and this 
year we are making a special effort to reach out to those new to or curious 
about Python.

The event is the fifth international Python Conference, being held Feb 23-25, 
2007 at the Marriott-Quorum in Addison, with early-bird registration ending 
*Jan 15*.

The conference draws approximately 400-500 attendees from diverse backgrounds 
such as scientists from national and medical labs, college/K-12 educators, web 
engineers and the myriad of IT developers and programming hobbyists.

Those new to the Python language are welcome, and we're offering a half-day 
"Python 101" tutorial in the morning as well as a "Code Like a Pythonista: 
Idiomatic Python" tutorial in the afternoon, on the day before the conference, 
Thursday Feb 22.  This pair of tutorials is designed to help you get up to 
speed and better enjoy the rest of the conference.

Other talks that may be of special interest to new Python programmers are:

  - Iterators in Action
  - Good-bye Hello World, Rethinking Teaching with Python
  - Easy Creation of Interactive Tutorials
  - pyweek: make games in 7 days
  - Developing Python Applications in Komodo 4.0
  - Tutorial: How to Document a Python Open Source Project

Being run by the Python community as a non-profit event, the conference 
strives to be inexpensive, with registration being only $260 (or $195 if you 
register prior to Jan 15th), with a further discount for students.  On the day 
before the conference we are running the full day of classroom tutorials 
(extra charge per class) and then after the conference is a free four-days of 
sprints, which are informal gatherings of programmers to work together in 
coding on various projects.  Sprints are excellent opportunities to do agile 
pair-programming side-by-side with experienced programmers and make new friends.

Other activities are lightning talks, which are 5-minute presentations to show 
off a cool technology or spread the word about a project, open space talks, 
which are spontaneous gatherings around a topic and, new this year, a Python 
Lab where experienced and novice programmers will work together to solve 
challenging problems and then present their solutions.

The conference is also running four keynote talks by leaders in the 
programming field, with a special focus on education this year:

   "The Power of Dangerous Ideas: Python and One Laptop per Child"
      by Ivan Krstic, senior member of the One Laptop per Child project

   "Premise: eLearning does not Belong in Public Schools"
      by Adele Goldberg, of SmallTalk fame

   "Python 3000"
      by Guido van Rossum, creator of Python

   "The Importance of Programming Literacy"
      by Robert M. "r0ml" Lefkowitz, a frequent speaker at O'Reilly conferences

I believe you will find the conference educational and enjoyable. More 
information about the conference along with the full schedule of presentations 
with abstracts, is available online:

   http://us.pycon.org/

Thanks for any help you can give in spreading the word,

Jeff Rush
Co-Chair PyCon 2007

From andrew.arobert at gmail.com  Thu Jan 11 15:15:04 2007
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Thu, 11 Jan 2007 09:15:04 -0500
Subject: [Tutor] Question on joining out of order dictionary elements
In-Reply-To: <6faf39c90701110534g33b504can1dca778f29e6935@mail.gmail.com>
References: <bedebdfb0701110245q5bef8beeo4209b1e9ebad7b80@mail.gmail.com>
	<6faf39c90701110534g33b504can1dca778f29e6935@mail.gmail.com>
Message-ID: <fd85eb130701110615v5eb69f8ao9ab8b5e783336080@mail.gmail.com>

I like this solution.

Thanks everyone for all of the suggestions.

On 1/11/07, Andre Engels <andreengels at gmail.com> wrote:
> 2007/1/11, raghu raghu <vgvr620034 at gmail.com>:
>
> > >>> print "\\".join((config["val2"]
> > ,config["val1"],config["val3"]))
> > elem2\elem1\elem3
> >
> > or
> >
> > >>> print "%s\\%s\\%s" %
> (config["val2"],config["val1"],config["val3"])
> > elem2\elem1\elem3
> >
> > but this seems somehow uneligent.
> >
> > Are there a more efficient/compact ways of doing this kind of
> > operation or is this it?
> >
>
> Maybe you like:
> print "\\".join([config[val] for val in ["val2","val1","val3"]])
>
> --
> Andre Engels, andreengels at gmail.com
> ICQ: 6260644  --  Skype: a_engels
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
Thank you,
Andrew Robert

Senior MQ Engineer
Information Technologies
Massachusetts Financial Services
Phone: 617-954-5882

From kabads at gmail.com  Thu Jan 11 15:19:48 2007
From: kabads at gmail.com (Adam Cripps)
Date: Thu, 11 Jan 2007 14:19:48 +0000
Subject: [Tutor] Removing duplicates in a list with a fixed length of items
	in the list.
Message-ID: <c7ff38550701110619w7da57b71n968178ed583bed39@mail.gmail.com>

I have a list which comprises of simple random arithmetic problems for
teachers to give to their pupils. This list must be a set length (if
the teacher asks for 10 questions, they should get 10 questions), but
should not have any duplicates.

I've seen the use of sets, but this reduces the size of the list, when
I have to have a fixed length.

Is there a quick way of checking if a string is already within a list
without iterating over the items of the list (which will slow the
application down slightly)?

TIA
Adam
-- 
http://www.monkeez.org
PGP key: 0x7111B833

From kent37 at tds.net  Thu Jan 11 15:32:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 11 Jan 2007 09:32:40 -0500
Subject: [Tutor] Removing duplicates in a list with a fixed length of
 items	in the list.
In-Reply-To: <c7ff38550701110619w7da57b71n968178ed583bed39@mail.gmail.com>
References: <c7ff38550701110619w7da57b71n968178ed583bed39@mail.gmail.com>
Message-ID: <45A64A88.7090500@tds.net>

Adam Cripps wrote:
> I have a list which comprises of simple random arithmetic problems for
> teachers to give to their pupils. This list must be a set length (if
> the teacher asks for 10 questions, they should get 10 questions), but
> should not have any duplicates.
> 
> I've seen the use of sets, but this reduces the size of the list, when
> I have to have a fixed length.
> 
> Is there a quick way of checking if a string is already within a list
> without iterating over the items of the list (which will slow the
> application down slightly)?

Hmm. If you are trying to pick 10 elements at random from a larger list, 
use random.sample(problems, 10)

If for some reason that doesn't work for you (maybe you are creating 
problems on the fly?) you could build a set in a loop, adding items 
until it is the size you want:
problemSet = set()
while len(problemSet) < 10:
   # do something to add a (possibly) new problem to the set

Finally, unless your lists are huge (thousands of items, at a guess) or 
you are doing this very many times (thousands of times), you will not 
notice the time it takes to search the list for duplicates.

Kent


From kabads at gmail.com  Thu Jan 11 16:17:16 2007
From: kabads at gmail.com (Adam Cripps)
Date: Thu, 11 Jan 2007 15:17:16 +0000
Subject: [Tutor] Removing duplicates in a list with a fixed length of
	items in the list.
In-Reply-To: <c7ff38550701110716j381cc637v89e354c8cdcfdfac@mail.gmail.com>
References: <c7ff38550701110619w7da57b71n968178ed583bed39@mail.gmail.com>
	<45A64A88.7090500@tds.net>
	<c7ff38550701110716j381cc637v89e354c8cdcfdfac@mail.gmail.com>
Message-ID: <c7ff38550701110717u5d397f97x941325d736f0501d@mail.gmail.com>

On 1/11/07, Adam Cripps <kabads at gmail.com> wrote:
> On 1/11/07, Kent Johnson <kent37 at tds.net> wrote:
> > Adam Cripps wrote:
> > > I have a list which comprises of simple random arithmetic problems for
> > > teachers to give to their pupils. This list must be a set length (if
> > > the teacher asks for 10 questions, they should get 10 questions), but
> > > should not have any duplicates.
> > >
> > > I've seen the use of sets, but this reduces the size of the list, when
> > > I have to have a fixed length.
> > >
> > > Is there a quick way of checking if a string is already within a list
> > > without iterating over the items of the list (which will slow the
> > > application down slightly)?
> >
> > Hmm. If you are trying to pick 10 elements at random from a larger list,
> > use random.sample(problems, 10)
> >
> > If for some reason that doesn't work for you (maybe you are creating
> > problems on the fly?) you could build a set in a loop, adding items
> > until it is the size you want:
> > problemSet = set()
> > while len(problemSet) < 10:
> >    # do something to add a (possibly) new problem to the set
> >
>

I'm creating them on the fly - so this suggestion seems to be the
sensible way forward.

I've not worked with Sets before but will give it a go. Is there a way
of turning the Set back to a list?

TIA
Adam
-- 
http://www.monkeez.org
PGP key: 0x7111B833

From kent37 at tds.net  Thu Jan 11 16:31:13 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 11 Jan 2007 10:31:13 -0500
Subject: [Tutor] Removing duplicates in a list with a fixed length of
 items in the list.
In-Reply-To: <c7ff38550701110717u5d397f97x941325d736f0501d@mail.gmail.com>
References: <c7ff38550701110619w7da57b71n968178ed583bed39@mail.gmail.com>	<45A64A88.7090500@tds.net>	<c7ff38550701110716j381cc637v89e354c8cdcfdfac@mail.gmail.com>
	<c7ff38550701110717u5d397f97x941325d736f0501d@mail.gmail.com>
Message-ID: <45A65841.2030900@tds.net>

Adam Cripps wrote:
> I've not worked with Sets before but will give it a go. Is there a way
> of turning the Set back to a list?

list(mySet)


From carloslara at web.de  Thu Jan 11 17:00:31 2007
From: carloslara at web.de (Carlos)
Date: Thu, 11 Jan 2007 17:00:31 +0100
Subject: [Tutor] Image Question, List of Image Colors
In-Reply-To: <mailman.7669.1168528640.32030.tutor@python.org>
References: <mailman.7669.1168528640.32030.tutor@python.org>
Message-ID: <45A65F1F.9010807@web.de>

Hello,

I'm trying to do what Kent suggested, but I have a little problem, no 
matter were I put my image or if I use sys.path.append to append the 
folder were my Image is located it is impossible to open the image. I 
know that this is a silly question but what is going on?

I like to solve problems but this is... well. I searched the web for 
help, but nothing.

This is how I am doing it

from PIL import Image
import sys

sys.path.append('D:\MASTER THESIS\Branch_01\Thesis B_01\images\tmp')
im = Image.open("Wind_Test_01")

Thanks and sorry for bothering you with such a basic thing
Carlos

From amadeo.bellotti at gmail.com  Thu Jan 11 22:47:44 2007
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Thu, 11 Jan 2007 16:47:44 -0500
Subject: [Tutor] Converting a string to a list with each character as an item
Message-ID: <d7253a230701111347n1ab3d44jde79abdfdb347226@mail.gmail.com>

does anyone know how to do this? I need it because i want to make a binary
coverter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070111/41542e3f/attachment.html 

From carroll at tjc.com  Thu Jan 11 23:05:30 2007
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 11 Jan 2007 14:05:30 -0800 (PST)
Subject: [Tutor] Converting a string to a list with each character as an
 item
In-Reply-To: <d7253a230701111347n1ab3d44jde79abdfdb347226@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0701111404290.15868-100000@violet.rahul.net>

On Thu, 11 Jan 2007, Amadeo Bellotti wrote:

> does anyone know how to do this? I need it because i want to make a binary
> coverter

>>> s = "101001100100101"
>>> l = list(s)
>>> l
['1', '0', '1', '0', '0', '1', '1', '0', '0', '1', '0', '0', '1', '0', '1']


From rabidpoobear at gmail.com  Thu Jan 11 23:08:57 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 11 Jan 2007 16:08:57 -0600
Subject: [Tutor] Question on joining out of order dictionary elements
In-Reply-To: <bedebdfb0701110245q5bef8beeo4209b1e9ebad7b80@mail.gmail.com>
References: <bedebdfb0701110245q5bef8beeo4209b1e9ebad7b80@mail.gmail.com>
Message-ID: <45A6B579.3050204@gmail.com>

raghu raghu wrote:
>
> [snip original message]
>
>
> To print or to retain individual values from a list,it has to be 
> written in the form of
> config={'test1':'elem1','test2':'elem2','test3':'elem3'}
> config['test4'] = 'elem4'
> print config.values()
> print config['test1']- To get individual values from a list
> If we want to retrieve all the values or say 2 from 4 its not possible 
> to put in a while loop and get that as a list only takes one argument 
> at a time better way is to extract individually and respective keys 
> could not be obtained if corresponding values are given.
Hello, raghu -
Please don't reply like this.
It breaks threading.
You should have a Re: in the title bar,
and the quoted text should have > before it.
If you reply like you did, it creates a new thread in Thunderbird.
I believe the 'reply all' button has some kind of magic that tells mail 
clients it's a reply to another message.

In addition, please don't use bolding.
If you reply normally, it will be clear what text is yours and what is 
from the original author.
Bolding text just makes it harder to read.
Thanks,
-Luke

From dyoo at hkn.eecs.berkeley.edu  Thu Jan 11 23:13:47 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 11 Jan 2007 14:13:47 -0800 (PST)
Subject: [Tutor] Psyco Puzzle
In-Reply-To: <7.0.1.0.2.20070111041220.07766ad8@rcblue.com>
References: <7.0.1.0.2.20070111041220.07766ad8@rcblue.com>
Message-ID: <Pine.LNX.4.64.0701111358540.20574@hkn.eecs.berkeley.edu>



> Sometimes psyco speeds up a script by a factor of 10, and sometimes
> it makes no difference at all. Here's a case where I fully expected
> it to make a difference:
> <http://www.rcblue.com/Python/Psyco_Puzzle.txt>. Whether using psyco
> or not, this takes about 13 seconds on my computer. Why no difference?

Psyco implements a Just-In-Time optimization approach, so I suspect that 
it does its analysis of a function only after that function has been run 
at least once --- otherwise, it has no run-time information on which it 
can use to analyze.

In the code above, the code we want to optimize is fact().  However, 
fact() is only called one time in the whole program.  To test this 
hypothesis, it might be interesting to see if "priming" fact up will help.

#############################################################
if __name__ == '__main__':
     printFact(5)            ## just to prime the function up
     timeStart = time.time()
     printFact(20000)
     timeEnd = time.time()
     print "Time was %.4g seconds" % (timeEnd - timeStart)
#############################################################



Furthermore, the magnitude of the numbers in the fact() code quickly get 
into bignum range, where psyco's optimizations probably won't be so 
effective.  In contrast, the primes code you have all deal with integers 
in the range of 32 bits.

Unfortunately, I can't test psyco, so there might be another factor that 
I'm missing.  If you want an authoritative answer, I'd recommend asking 
your question on the psyco mailing list: they have more experience with 
what psyco's good at.


One other thing to note: something looks weird:

     if __name__ == '__main__'== '__main__':
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This looks off.  Can you correct it?


Good luck!

From hugonz-lists at h-lab.net  Thu Jan 11 07:53:52 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Thu, 11 Jan 2007 00:53:52 -0600
Subject: [Tutor] python web dev
In-Reply-To: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
References: <c7c6f3bc0701040811g13afbb1cn4b9b42197f92db@mail.gmail.com>
Message-ID: <45A5DF00.9060101@h-lab.net>

OkaMthembo wrote:

> this is my first post. please could you tell me which is the best 
> lightweight python web framework? also, which is the best templating 
> language for python? (which can handle other data formats in addition to 
> text). so far im lured by Cheetah, although i havent done any web dev 
> with python yet.

If you really want to go light, you may want to try Albatross, as others 
like Django are pretty heavy.

Hugo


From hugonz-lists at h-lab.net  Thu Jan 11 08:13:55 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Thu, 11 Jan 2007 01:13:55 -0600
Subject: [Tutor] XML-RPC data transfers.
In-Reply-To: <4596FF8F.8080401@gmail.com>
References: <BAY12-F204AF27D9D281699F3E163B1C60@phx.gbl>	<c25107380612292114o786c24ft41bea4931562cce6@mail.gmail.com>	<45967D0C.9040205@tds.net>	<c25107380612301504m372283cei227a339b2d1303b8@mail.gmail.com>
	<4596FF8F.8080401@gmail.com>
Message-ID: <45A5E3B3.60502@h-lab.net>

Luke Paireepinart wrote:
  > But the main strategy is to get the data out of the ImageGrab object.
> one way is stated above - use the save method to write to a file.
> another possible way is to create a filelike class, implementing 'tell' 
> 'seek' and 'write' methods, that just collects all the data written to 
> it and keeps it in memory
> rather than writing it out to a file.
> This is hinted at in the documentation for im.save():
> "You can use a file object instead of a filename. In this case, you must 
> always specify the format. The file object must implement the *seek*, 
> *tell*, and *write* methods, and be opened in binary mode."
> (I assume it means you can use a file-like object, also, but it's 
> possible that you can't, and I leave it to you to test that :) )


hmmm StringIO module maybe?

Hugo


From hugonz-lists at h-lab.net  Thu Jan 11 08:36:43 2007
From: hugonz-lists at h-lab.net (=?windows-1252?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Thu, 11 Jan 2007 01:36:43 -0600
Subject: [Tutor] problems pickling functions
In-Reply-To: <30A4356E-4A4A-46F2-8422-BDF212A53CA0@stud.ntnu.no>
References: <15902802-7CDB-4812-BA30-6D5ACDD633D5@stud.ntnu.no>	<45796335.8030606@tds.net>	<918C920B-8630-4A3B-B1E0-46BE2BAAED3D@stud.ntnu.no>	<45797A07.1050408@tds.net>
	<30A4356E-4A4A-46F2-8422-BDF212A53CA0@stud.ntnu.no>
Message-ID: <45A5E90B.8020903@h-lab.net>

Arild B. N?ss wrote:
> I haven't found out how to change the working directory in IDLE,  
> though ? and for some reason it seems to be a different one this  
> session from the last one. Does anyone know?
> 	(I use a mac by the way.)


take a look at os.chdir()

This changes the interpreter's working dir (and thus whatever you're 
writing into the prompt in IDLE)


From hugonz-lists at h-lab.net  Thu Jan 11 08:27:13 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Thu, 11 Jan 2007 01:27:13 -0600
Subject: [Tutor] Python and rpy
In-Reply-To: <5d8e35a70612280431s6a423dffg720a6bd8a3abd241@mail.gmail.com>
References: <5d8e35a70612210743j69f30d54kfec867df695a93b6@mail.gmail.com>	<458AEDE3.8030006@tds.net>	<5d8e35a70612220221r7f324d1fl30ef1810d6c838c1@mail.gmail.com>	<458F31E0.9070107@tds.net>
	<5d8e35a70612280431s6a423dffg720a6bd8a3abd241@mail.gmail.com>
Message-ID: <45A5E6D1.5080101@h-lab.net>

Geoframer wrote:
> 
> However i switched to Ubuntu 6.10 today (from WinXP) and to my suprise 
> it does work under linux! :-)

Probably Numeric is included in Ubuntu's  Python distro.

Hugo


From dyoo at hkn.eecs.berkeley.edu  Thu Jan 11 23:19:37 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 11 Jan 2007 14:19:37 -0800 (PST)
Subject: [Tutor] Image Question, List of Image Colors
In-Reply-To: <45A65F1F.9010807@web.de>
References: <mailman.7669.1168528640.32030.tutor@python.org>
	<45A65F1F.9010807@web.de>
Message-ID: <Pine.LNX.4.64.0701111415250.20574@hkn.eecs.berkeley.edu>

> I'm trying to do what Kent suggested, but I have a little problem, no 
> matter were I put my image or if I use sys.path.append to append the 
> folder were my Image is located it is impossible to open the image. I 
> know that this is a silly question but what is going on?

sys.path contains a list of paths that Python will use to search for 
modules.  It does not affect anything else.  In particular, adding it 
won't affect the paths that PIL uses to open files.



> sys.path.append('D:\MASTER THESIS\Branch_01\Thesis B_01\images\tmp')
> im = Image.open("Wind_Test_01")

You can build up the fulle path name, using os.path.join:

     http://www.python.org/doc/lib/module-os.path.html


By the way, beware backslashes in your path there.  You can use forward 
slashes with fewer problems.  The reason backslashes are more problematic 
is because it almost always collides with the way we make string literal 
escapes in Python.

From rabidpoobear at gmail.com  Thu Jan 11 23:20:09 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 11 Jan 2007 16:20:09 -0600
Subject: [Tutor] Image Question, List of Image Colors
In-Reply-To: <45A65F1F.9010807@web.de>
References: <mailman.7669.1168528640.32030.tutor@python.org>
	<45A65F1F.9010807@web.de>
Message-ID: <45A6B819.9040008@gmail.com>

Carlos wrote:
> Hello,
>
> I'm trying to do what Kent suggested, but I have a little problem, no 
> matter were I put my image or if I use sys.path.append to append the 
> folder were my Image is located it is impossible to open the image. I 
> know that this is a silly question but what is going on?
>
> I like to solve problems but this is... well. I searched the web for 
> help, but nothing.
>
> This is how I am doing it
>
> from PIL import Image
> import sys
>
> sys.path.append('D:\MASTER THESIS\Branch_01\Thesis B_01\images\tmp')
> im = Image.open("Wind_Test_01")
>   
You should include your traceback whenever you have a problem.
For example, if it said "File Wind_Test_01 not found" I would say
'You probably need to specify the file extension, like you would with 
any other program.'
but I don't know, because I can't see the error message.

-Luke

From dyoo at hkn.eecs.berkeley.edu  Thu Jan 11 23:22:11 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 11 Jan 2007 14:22:11 -0800 (PST)
Subject: [Tutor] Converting a string to a list with each character as an
 item
In-Reply-To: <Pine.LNX.4.44.0701111404290.15868-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0701111404290.15868-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.64.0701111420130.20574@hkn.eecs.berkeley.edu>



On Thu, 11 Jan 2007, Terry Carroll wrote:

> On Thu, 11 Jan 2007, Amadeo Bellotti wrote:
>
>> does anyone know how to do this? I need it because i want to make a binary
>> coverter
>
>>>> s = "101001100100101"
>>>> l = list(s)
>>>> l
> ['1', '0', '1', '0', '0', '1', '1', '0', '0', '1', '0', '0', '1', '0', '1']

By the way Amadeo, is it really necessary to do the conversion here? 
Strings follow the same indexing as lists, and they can also be used in 
loops.

From bgailer at alum.rpi.edu  Thu Jan 11 23:27:08 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu, 11 Jan 2007 14:27:08 -0800
Subject: [Tutor] Converting a string to a list with each character as an
 item
In-Reply-To: <d7253a230701111347n1ab3d44jde79abdfdb347226@mail.gmail.com>
References: <d7253a230701111347n1ab3d44jde79abdfdb347226@mail.gmail.com>
Message-ID: <45A6B9BC.1050705@alum.rpi.edu>

Amadeo Bellotti wrote:
> does anyone know how to do this? I need it because i want to make a 
> binary coverter
 >>> list('abc')
['a', 'b', 'c']

-- 
Bob Gailer
510-978-4454


From carloslara at web.de  Thu Jan 11 23:58:44 2007
From: carloslara at web.de (Carlos)
Date: Thu, 11 Jan 2007 23:58:44 +0100
Subject: [Tutor] Image Question, List of Image Colors
In-Reply-To: <mailman.7740.1168554045.32030.tutor@python.org>
References: <mailman.7740.1168554045.32030.tutor@python.org>
Message-ID: <45A6C124.2060103@web.de>

Hello,

Well seems like Danny was right, the backslashes were the problem! This 
really got an 11 in my frustration meter.

Thanks for your help
Carlos


From cspears2002 at yahoo.com  Fri Jan 12 01:03:19 2007
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 11 Jan 2007 16:03:19 -0800 (PST)
Subject: [Tutor] more fun and games with padded numbers
In-Reply-To: <mailman.7600.1168472736.32030.tutor@python.org>
Message-ID: <20070112000319.8482.qmail@web51608.mail.yahoo.com>

Let's say I have a series of files that are named like
so:

0001.ext
0230.ext
0041.ext
0050.ext

How would I convert these from a padding of 4 to a
padding of 1?  In other words, I want the files to be
renamed as:

1.ext
230.ext
41.ext
50.ext

At first I used strip(), which was a mistake because
it removed all the zeroes.  

The only other solution I can think of is to use
slicing to slice off the zeroes.  Perhaps I could loop
through the name and remove zeroes until I hit a
number that is not zero and then exit the loop.

Any hints or suggestions?
 

From john at fouhy.net  Fri Jan 12 01:17:14 2007
From: john at fouhy.net (John Fouhy)
Date: Fri, 12 Jan 2007 13:17:14 +1300
Subject: [Tutor] more fun and games with padded numbers
In-Reply-To: <20070112000319.8482.qmail@web51608.mail.yahoo.com>
References: <mailman.7600.1168472736.32030.tutor@python.org>
	<20070112000319.8482.qmail@web51608.mail.yahoo.com>
Message-ID: <5e58f2e40701111617r1046a32dr7b9bd29d139bdfc6@mail.gmail.com>

On 12/01/07, Christopher Spears <cspears2002 at yahoo.com> wrote:
> Let's say I have a series of files that are named like
> so:
>
> 0001.ext
> 0230.ext
> 0041.ext
> 0050.ext
>
> How would I convert these from a padding of 4 to a
> padding of 1?  In other words, I want the files to be
> renamed as:
>
> 1.ext
> 230.ext
> 41.ext
> 50.ext
>
> At first I used strip(), which was a mistake because
> it removed all the zeroes.

Are you sure?  If you used .replace('0', '') it would remove all the
zeros.  But this is what strip is for.

>>> lst = ['0001.ext', '0230.ext', '0041.ext', '0050.ext']
>>> [s.lstrip('0') for s in lst]
['1.ext', '230.ext', '41.ext', '50.ext']

-- 
John.

From klaus.ramelow at GMX.de  Fri Jan 12 01:30:59 2007
From: klaus.ramelow at GMX.de (Klaus Ramelow)
Date: Fri, 12 Jan 2007 01:30:59 +0100
Subject: [Tutor] Removing duplicates in a list with a fixed length of
 items in the list.
Message-ID: <45A6D6C3.8080902@GMX.de>

Why not sorting the items and throw out all multiples until you reach 
the fixed length ?

Klaus Ramelow

From carroll at tjc.com  Fri Jan 12 04:24:19 2007
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 11 Jan 2007 19:24:19 -0800 (PST)
Subject: [Tutor] more fun and games with padded numbers
In-Reply-To: <20070112000319.8482.qmail@web51608.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0701111910560.15868-100000@violet.rahul.net>

On Thu, 11 Jan 2007, Christopher Spears wrote:

> Let's say I have a series of files that are named like
> so:
> 
> 0001.ext
> 0230.ext
> 0041.ext
> 0050.ext
> 
> How would I convert these from a padding of 4 to a
> padding of 1?  In other words, I want the files to be
> renamed as:
> 
> 1.ext
> 230.ext
> 41.ext
> 50.ext

That doesn't look to me like a padding of 1; that looks to me like no 
padding.

But if that's what you want, I'm sure there's a better way, but my initial 
approach would be:

>>> oldnames = ["0001.ext", "0230.ext", "0041.ext", "0050.ext"]
>>> for name in oldnames:
...  newfname, fext = name.split('.')
...  newname = "%s.%s" % (int(newfname), fext)
...  print newname
...
1.ext
230.ext
41.ext
50.ext
>>>

Note that this assumes that the filename portion is entirely numeric.  
This would break on, for example, a file named 00abc.ext.

Actually, what I don't like here is the conversion of string to int to 
string for no real purpose.

> At first I used strip(), which was a mistake because
> it removed all the zeroes.

That should work, with an argument:

>>> oldnames = ["0001.ext", "0230.ext", "0041.ext", "0050.ext"]
>>> newnames = [name.strip('0') for name in oldnames]
>>> newnames
['1.ext', '230.ext', '41.ext', '50.ext']




From kent37 at tds.net  Fri Jan 12 12:00:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 12 Jan 2007 06:00:58 -0500
Subject: [Tutor] more fun and games with padded numbers
In-Reply-To: <5e58f2e40701111617r1046a32dr7b9bd29d139bdfc6@mail.gmail.com>
References: <mailman.7600.1168472736.32030.tutor@python.org>	<20070112000319.8482.qmail@web51608.mail.yahoo.com>
	<5e58f2e40701111617r1046a32dr7b9bd29d139bdfc6@mail.gmail.com>
Message-ID: <45A76A6A.1060300@tds.net>

John Fouhy wrote:
> On 12/01/07, Christopher Spears <cspears2002 at yahoo.com> wrote:
>> At first I used strip(), which was a mistake because
>> it removed all the zeroes.
> 
> Are you sure?  If you used .replace('0', '') it would remove all the
> zeros.  But this is what strip is for.
> 
>>>> lst = ['0001.ext', '0230.ext', '0041.ext', '0050.ext']
>>>> [s.lstrip('0') for s in lst]
> ['1.ext', '230.ext', '41.ext', '50.ext']

I just want to highlight that your code uses lstrip(), not strip(). 
lstrip() is perfect for this problem, it removes leading characters 
only, in this case leading 0s.

Kent


From asonia at TechMahindra.com  Fri Jan 12 08:35:41 2007
From: asonia at TechMahindra.com (sonia agarwal)
Date: Fri, 12 Jan 2007 13:05:41 +0530
Subject: [Tutor] openssl 0.9.7l for i686,python:need help
Message-ID: <696D9B0CA989184E85CF4BFADE7CAEB706AAE5@SINNODEX001.TechMahindra.com>



Hi

I am trying to download files from a network element whose IP address,username and password is the only thing i know to establish an SFTP connection using python script.I have found that I need to use M2Crypto package which in turn requires openssl 0.9.7l or newer.
I am unable to download openssl 0.9.7l for my machine architecture i.e. i686,CentOS 4.4.
Kindly help.

Thanks & Regards
Sonia Agrawal
Technical Associate
Tech Mahindra Ltd
A-20,Sector-60,Noida
India


============================================================================================================================

Tech Mahindra, formerly Mahindra-British Telecom.
 
Disclaimer:

This message and the information contained herein is proprietary and confidential and subject to the Tech Mahindra policy statement, you may review at <a href="http://www.techmahindra.com/Disclaimer.html">http://www.techmahindra.com/Disclaimer.html</a> externally and <a href="http://tim.techmahindra.com/Disclaimer.html">http://tim.techmahindra.com/Disclaimer.html</a> internally within Tech Mahindra.

============================================================================================================================
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070112/3025abdd/attachment.html 

From chris.arndt at web.de  Fri Jan 12 13:47:40 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 12 Jan 2007 13:47:40 +0100
Subject: [Tutor] openssl 0.9.7l for i686,python:need help
In-Reply-To: <696D9B0CA989184E85CF4BFADE7CAEB706AAE5@SINNODEX001.TechMahindra.com>
References: <696D9B0CA989184E85CF4BFADE7CAEB706AAE5@SINNODEX001.TechMahindra.com>
Message-ID: <45A7836C.5080904@web.de>

sonia agarwal schrieb:
> I am trying to download files from a network element whose IP
> address,username and password is the only thing i know to establish an
> SFTP connection using python script.I have found that I need to use
> M2Crypto package which in turn requires openssl 0.9.7l or newer.
> I am unable to download openssl 0.9.7l for my machine architecture i.e.
> i686,CentOS 4.4.

CentOS 4 is based on Red Hat Enterprise Linux 4, which is in turn based
on Fedora Core 3 (says the wikipedia), and is supposed to be binary
compatible with the former. So, in theory, you should be able to install
openssl from a RH or Fedora RPM package.

You could also have a look at paramiko (http://www.lag.net/paramiko/),
which is a pure Python implementation of SSH2 but dependent on pycrypto
(http://www.amk.ca/python/code/crypto.html).

HTH, Chris

From adam.jtm30 at gmail.com  Fri Jan 12 15:16:59 2007
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Fri, 12 Jan 2007 14:16:59 +0000
Subject: [Tutor] Psyco Puzzle
In-Reply-To: <Pine.LNX.4.64.0701111358540.20574@hkn.eecs.berkeley.edu>
References: <7.0.1.0.2.20070111041220.07766ad8@rcblue.com>
	<Pine.LNX.4.64.0701111358540.20574@hkn.eecs.berkeley.edu>
Message-ID: <be4fbf920701120616m60b3a957s58461623347cad7@mail.gmail.com>

On 11/01/07, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
>
> > Sometimes psyco speeds up a script by a factor of 10, and sometimes
> > it makes no difference at all. Here's a case where I fully expected
> > it to make a difference:
> > <http://www.rcblue.com/Python/Psyco_Puzzle.txt>. Whether using psyco
> > or not, this takes about 13 seconds on my computer. Why no difference?
>
> Psyco implements a Just-In-Time optimization approach, so I suspect that
> it does its analysis of a function only after that function has been run
> at least once --- otherwise, it has no run-time information on which it
> can use to analyze.
>
> In the code above, the code we want to optimize is fact().  However,
> fact() is only called one time in the whole program.  To test this
> hypothesis, it might be interesting to see if "priming" fact up will help.
>
> #############################################################
> if __name__ == '__main__':
>      printFact(5)            ## just to prime the function up
>      timeStart = time.time()
>      printFact(20000)
>      timeEnd = time.time()
>      print "Time was %.4g seconds" % (timeEnd - timeStart)
> #############################################################
>
>
>
> Furthermore, the magnitude of the numbers in the fact() code quickly get
> into bignum range, where psyco's optimizations probably won't be so
> effective.  In contrast, the primes code you have all deal with integers
> in the range of 32 bits.


I tested this myself and it looks like bignum is probably the slowdown here
without psyco:
20000! = 1.81e+77337
Time was 7.58 seconds
with psyco no priming:
20000! = 1.81e+77337
Time was 7.55 seconds
with psyco and priming:
5! = 1.20e+002
20000! = 1.81e+77337
Time was 7.591 seconds

there seems to be no difference with psyco or without even if you run the
function first.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070112/1768d599/attachment.html 

From nixonron at yahoo.com  Fri Jan 12 19:37:30 2007
From: nixonron at yahoo.com (Ron Nixon)
Date: Fri, 12 Jan 2007 10:37:30 -0800 (PST)
Subject: [Tutor] urlretrieve
Message-ID: <20070112183730.88881.qmail@web34203.mail.mud.yahoo.com>

Is there a way to get the urlretrive module to grab multiple files similar to wget?


Ron Nixon




 
____________________________________________________________________________________
Expecting? Get great news right away with email Auto-Check. 
Try the Yahoo! Mail Beta.
http://advision.webevents.yahoo.com/mailbeta/newmail_tools.html 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070112/43d2bd12/attachment.htm 

From kent37 at tds.net  Fri Jan 12 20:26:43 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 12 Jan 2007 14:26:43 -0500
Subject: [Tutor] urlretrieve
In-Reply-To: <20070112183730.88881.qmail@web34203.mail.mud.yahoo.com>
References: <20070112183730.88881.qmail@web34203.mail.mud.yahoo.com>
Message-ID: <45A7E0F3.7060501@tds.net>

Ron Nixon wrote:
> Is there a way to get the urlretrive module to grab multiple files 
> similar to wget?

I'm not familiar enough with wget to know exactly what you are looking 
for. urllib.urlretrieve() just grabs a single file. If you want a bunch 
of named files, just put it in a loop. If you are trying to retrieve a 
whole web site you might be interested in HarvestMan, either as working 
code or a source of ideas:
http://harvestman.freezope.org/

Kent


From pythontut at pusspaws.net  Fri Jan 12 21:29:10 2007
From: pythontut at pusspaws.net (Dave S)
Date: Fri, 12 Jan 2007 20:29:10 +0000
Subject: [Tutor] 'root' dir of a package from within the package ?
In-Reply-To: <20070109115510.78172072.klappnase@freenet.de>
References: <200701081924.38050.pythontut@pusspaws.net>
	<20070109115510.78172072.klappnase@freenet.de>
Message-ID: <200701122029.10745.pythontut@pusspaws.net>

On Tuesday 09 January 2007 10:55, Michael Lange wrote:
> On Mon, 8 Jan 2007 19:24:37 +0000
>
> Dave S <pythontut at pusspaws.net> wrote:
> > Hi all,
> >
> > I have written a python package, which works fine, the 'root' directory
> > is 'my_app' with sub directories within in, complete with there
> > __init__.py files.
> >
> > I need to work out the path to the root directory from within the app,
> > os.path gives me pythons path! - oh and its in XP.
> >
> > Any suggestions ?
>
> Hi Dave,
>
> app_root = os.path.abspath(sys.path[0]) or, within the main executable .py
> file, app_root = os.path.abspath(os.path.dirname(__file__)) should do the
> trick.
>
> I hope this helps
>
> Michael



Many thanks, 

Sorry for the delay - work got in the way :)

Cheers

Dave

From carroll at tjc.com  Fri Jan 12 21:43:08 2007
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 12 Jan 2007 12:43:08 -0800 (PST)
Subject: [Tutor] more fun and games with padded numbers
In-Reply-To: <45A76A6A.1060300@tds.net>
Message-ID: <Pine.LNX.4.44.0701121242040.11279-100000@violet.rahul.net>

On Fri, 12 Jan 2007, Kent Johnson wrote:

> I just want to highlight that your code uses lstrip(), not strip(). 

Oops.  I didn't even notice that.  I'll take it as a good sign that I'm
finally getting comfortable in Python that I instinctively used it without
realizing it.



From kent37 at tds.net  Fri Jan 12 21:57:56 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 12 Jan 2007 15:57:56 -0500
Subject: [Tutor] more fun and games with padded numbers
In-Reply-To: <Pine.LNX.4.44.0701121242040.11279-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0701121242040.11279-100000@violet.rahul.net>
Message-ID: <45A7F654.3040506@tds.net>

Terry Carroll wrote:
> On Fri, 12 Jan 2007, Kent Johnson wrote:
> 
>> I just want to highlight that your code uses lstrip(), not strip(). 
> 
> Oops.  I didn't even notice that.  I'll take it as a good sign that I'm
> finally getting comfortable in Python that I instinctively used it without
> realizing it.

Mmm, it was John's code I was referring to, yours uses strip() :-)


From rdm at rcblue.com  Fri Jan 12 22:31:10 2007
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 12 Jan 2007 13:31:10 -0800
Subject: [Tutor] Psyco Puzzle
In-Reply-To: <be4fbf920701120616m60b3a957s58461623347cad7@mail.gmail.com
 >
References: <7.0.1.0.2.20070111041220.07766ad8@rcblue.com>
	<Pine.LNX.4.64.0701111358540.20574@hkn.eecs.berkeley.edu>
	<be4fbf920701120616m60b3a957s58461623347cad7@mail.gmail.com>
Message-ID: <7.0.1.0.2.20070112124734.07d29d78@rcblue.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070112/01010f56/attachment.html 

From rdm at rcblue.com  Fri Jan 12 23:17:22 2007
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 12 Jan 2007 14:17:22 -0800
Subject: [Tutor] Psyco Puzzle
In-Reply-To: <7.0.1.0.2.20070112124734.07d29d78@rcblue.com>
References: <7.0.1.0.2.20070111041220.07766ad8@rcblue.com>
	<Pine.LNX.4.64.0701111358540.20574@hkn.eecs.berkeley.edu>
	<be4fbf920701120616m60b3a957s58461623347cad7@mail.gmail.com>
	<7.0.1.0.2.20070112124734.07d29d78@rcblue.com>
Message-ID: <7.0.1.0.2.20070112141105.07f07468@rcblue.com>

At 01:31 PM 1/12/2007, Dick Moores wrote:

>But another question. I tried testing just my function fact() (see < 
>http://www.rcblue.com/Python/Psyco_Puzzle.txt>) using timeit.py's 
>template, with and without psyco. Without psyco I used
>=============================
>def inner(_it, _timer):
>     from mine.mycalc import fact
>     _t0 = _timer()
>     for _i in _it:
>         fact (5)
>     _t1 = _timer()
>     return _t1 - _t0
>=============================
>and got 100000 loops, best of 3: 2.35 usec per loop
>
>With psyco I used
>=================================
>def inner(_it, _timer):
>     from mine.mycalc import fact; import psyco
>     _t0 = _timer()
>     for _i in _it:
>         psyco.full();fact (5)
>     _t1 = _timer()
>     return _t1 - _t0
>=================================

Oops! I just realized I probably didn't use the template correctly. I 
should have used
=============================================
def inner(_it, _timer):
     from mine.mycalc import fact; import psyco; psyco.full()
     _t0 = _timer()
     for _i in _it:
         fact (5)
     _t1 = _timer()
     return _t1 - _t0
=============================================

I'll rerun and repost.

Dick


From wescpy at gmail.com  Sat Jan 13 00:02:50 2007
From: wescpy at gmail.com (wesley chun)
Date: Fri, 12 Jan 2007 15:02:50 -0800
Subject: [Tutor] ANN: Python training course, Feb 7-9, San Francisco
In-Reply-To: <78b3a9580701121501v52ab23b1gd9103ca2db8a0197@mail.gmail.com>
References: <78b3a9580701121501v52ab23b1gd9103ca2db8a0197@mail.gmail.com>
Message-ID: <78b3a9580701121502n174c355bj1220ca322183056a@mail.gmail.com>

FINAL REMINDER... we still have some seats left!

What:   (Intensive) Intro to Python
When:  February 7-9, 2007
Where: San Francisco (SFO/San Bruno), CA, USA
Web:    http://cyberwebconsulting.com (click "Python Training" link)

Need to get up-to-speed with Python as quickly as possible?  Come join
us in beautiful Northern California for another one of our rigorous
Python training events! This is an intense introduction to Python
directed towards those who have some proficiency in another high-level
language. This course will take place in San Bruno right near the San
Francisco International Airport.

LOCALS: easy freeway (101/280/380) with lots of parking plus public
transit (BART and CalTrain) access via the San Bruno stations, easily
accessible from all parts of the Bay Area

VISITORS: the hotel offers free shuttle to/from the airport, free
high-speed internet, free breakfast and evening reception daily

The cost is only $1095 (reg $1295) per attendee.  Discounts are
available for multiple registrations as well as students and teachers
of secondary and post-secondary educational institutions. Registration
will be opening soon for the next Intro and Advanced courses both
taking place back-to-back in May 2007. See website for more details.

hope to meet you soon!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From carloslara at web.de  Sat Jan 13 01:08:53 2007
From: carloslara at web.de (Carlos)
Date: Sat, 13 Jan 2007 01:08:53 +0100
Subject: [Tutor] Problems with a Class
In-Reply-To: <mailman.7912.1168635486.32030.tutor@python.org>
References: <mailman.7912.1168635486.32030.tutor@python.org>
Message-ID: <45A82315.5010908@web.de>

Hello,

I'm just about to finish my project, but something is causing me 
trouble. I need to find out how to get some information out of the 
genetic algorithm that Im using. This algorithm is generating some 
coordinates for a collection of objects, until now I needed only the 
final result of the process. But I discovered that the final information 
is not enough, I need to get some intermediate data to actualize the 
positions of the objects and then evaluate those positions.

This is the area of the algorith that I think holds the info that I need:

def evolve(self, generations = 100):
  
        self.halt_reached = 0
       
        for gen in range(generations):

            #Changed.
            print 'GEN:',gen, self.entities
           
            self.do_mutation()
            self.do_crossover()
            print "Average fitness generation " + str(gen) + ": " + 
str(self.avg_fitness())
            if self.debug == 1:
                self.echo_fitness()
            if self.halt >= 0:
                max_entity = self.get_max_fitness()
                fit = self.calc_fitness(max_entity)
                if fit >= halt:
                    self.halt_reached = 1
                    return [max_entity]

The line marked as #Changed is what I changed,  with this I was able to 
print the info, but I'm sorry to say that I have no clue at how to apply 
something like return() that would give me this self.entities list. As 
you can see there is a for loop and I need the info every time that it 
gets updated by the loop.

Hopefully I'm making myself clear and the info is enough.

Thanks for your help in advance
Carlos



From carloslara at web.de  Sat Jan 13 01:51:05 2007
From: carloslara at web.de (Carlos)
Date: Sat, 13 Jan 2007 01:51:05 +0100
Subject: [Tutor] Problems with a Class
In-Reply-To: <45A82315.5010908@web.de>
References: <mailman.7912.1168635486.32030.tutor@python.org>
	<45A82315.5010908@web.de>
Message-ID: <45A82CF9.9060409@web.de>

Hi,

Just in case that the info that I provided is not enough, I posted the 
code in a python forum, hope that somebody can take a look.

http://python-forum.org/py/viewtopic.php?p=11063#11063

Regards,
Carlos

From rdm at rcblue.com  Sat Jan 13 03:19:25 2007
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 12 Jan 2007 18:19:25 -0800
Subject: [Tutor] Psyco Puzzle
In-Reply-To: <7.0.1.0.2.20070112124734.07d29d78@rcblue.com>
References: <7.0.1.0.2.20070111041220.07766ad8@rcblue.com>
	<Pine.LNX.4.64.0701111358540.20574@hkn.eecs.berkeley.edu>
	<be4fbf920701120616m60b3a957s58461623347cad7@mail.gmail.com>
	<7.0.1.0.2.20070112124734.07d29d78@rcblue.com>
Message-ID: <7.0.1.0.2.20070112170324.07d2b4f8@rcblue.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070112/d1d6aa78/attachment.html 

From bgailer at alum.rpi.edu  Sat Jan 13 05:46:03 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 12 Jan 2007 20:46:03 -0800
Subject: [Tutor] Problems with a Class
In-Reply-To: <45A82315.5010908@web.de>
References: <mailman.7912.1168635486.32030.tutor@python.org>
	<45A82315.5010908@web.de>
Message-ID: <45A8640B.2070308@alum.rpi.edu>

Carlos wrote:
> Hello,
>
> I'm just about to finish my project, but something is causing me 
> trouble. I need to find out how to get some information out of the 
> genetic algorithm that Im using. This algorithm is generating some 
> coordinates for a collection of objects, until now I needed only the 
> final result of the process. But I discovered that the final information 
> is not enough, I need to get some intermediate data to actualize the 
> positions of the objects and then evaluate those positions.
>
> This is the area of the algorith that I think holds the info that I need:
>
> def evolve(self, generations = 100):
>   
>         self.halt_reached = 0
>        
>         for gen in range(generations):
>
>             #Changed.
>             print 'GEN:',gen, self.entities
>            
>             self.do_mutation()
>             self.do_crossover()
>             print "Average fitness generation " + str(gen) + ": " + 
> str(self.avg_fitness())
>             if self.debug == 1:
>                 self.echo_fitness()
>             if self.halt >= 0:
>                 max_entity = self.get_max_fitness()
>                 fit = self.calc_fitness(max_entity)
>                 if fit >= halt:
>                     self.halt_reached = 1
>                     return [max_entity]
>
> The line marked as #Changed is what I changed,  with this I was able to 
> print the info, but I'm sorry to say that I have no clue at how to apply 
> something like return() that would give me this self.entities list. As 
> you can see there is a for loop and I need the info every time that it 
> gets updated by the loop.
>
> Hopefully I'm making myself clear and the info is enough.
>   
Unfortunately, no. I for one can't interpret "I need the info every time 
that it gets updated by the loop".

-- 
Bob Gailer
510-978-4454


From python-tutor at runtime.nu  Sat Jan 13 02:08:16 2007
From: python-tutor at runtime.nu (Dom Hamon)
Date: Fri, 12 Jan 2007 17:08:16 -0800
Subject: [Tutor] Problems with a Class
In-Reply-To: <45A82315.5010908@web.de>
Message-ID: <003601c736af$4fcead30$6500a8c0@tweak>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Carlos
> Sent: 12 January 2007 16:09
> To: tutor at python.org
> Subject: [Tutor] Problems with a Class
> 
> This is the area of the algorith that I think holds the info 
> that I need:
> 
> def evolve(self, generations = 100):
>   
>         self.halt_reached = 0
>        
>         for gen in range(generations):
> 
>             #Changed.
>             print 'GEN:',gen, self.entities
>            
>             self.do_mutation()
>             self.do_crossover()
>             print "Average fitness generation " + str(gen) + ": " +
> str(self.avg_fitness())
>             if self.debug == 1:
>                 self.echo_fitness()
>             if self.halt >= 0:
>                 max_entity = self.get_max_fitness()
>                 fit = self.calc_fitness(max_entity)
>                 if fit >= halt:
>                     self.halt_reached = 1
>                     return [max_entity]

I think if you change this line to:

			 return self.entities, [max_entity]

And handle the return as a tuple of two lists, you should get what you 
want. It does mean changing the code that calls this function to handle 
the different return value, of course. 

dom



From carloslara at web.de  Sat Jan 13 10:32:09 2007
From: carloslara at web.de (Carlos)
Date: Sat, 13 Jan 2007 10:32:09 +0100
Subject: [Tutor] Tutor Digest, Vol 35, Issue 38
In-Reply-To: <mailman.7970.1168663628.32030.tutor@python.org>
References: <mailman.7970.1168663628.32030.tutor@python.org>
Message-ID: <45A8A719.4020709@web.de>


Hello,

> Unfortunately, no. I for one can't interpret "I need the info every 
> time that it gets updated by the loop"
The GA is creating solutions for a given problem, that are contained in 
self.entities that looks like this:

Generation_01: [[1, 0, 0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 
0, 0], [1, 1, 0, 0, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0, 1, 0, 1], 
[1, 0, 1, 0, 1, 0, 1, 1, 0, 1]]
Generation_02, Generation_03, Generation_04...
Generation_25:[[1, 1, 1, 1, 1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 
1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

self.entities gets new values with each generation, because the solution 
to a given problem is evolving and getting closer to a correct result. 
The problem is that with:

 Phenotypes = ga_inst.evolve(Gen)

I only get the last generation -or iteration- and I need to actualize 
some objects position before evaluating the generation, so what I need 
is to get the values of self.entity on each generation. Since this 
values are going to be evaluted, I need to actualize some gemetrical 
objects with every new self.entities before evaluating the solution.

I tried this:

def evolve(self, generations = 100):
        """ Process a number of generations
        Stop if:
        - number of generations = generations
        - halt variable has been set AND
          there is an entity with a fitness which has obtained or exceeded
          the halt value
        Return the list of entities, or the halt-entity if prematurely 
halted
          """
       
        self.halt_reached = 0
       
        for gen in range(generations):

            print 'TEST', self.entities ### THIS IS MY CHANGE


            self.do_mutation()
            self.do_crossover()
            print "Average fitness generation " + str(gen) + ": " + 
str(self.avg_fitness())
            if self.debug == 1:
                self.echo_fitness()
            if self.halt >= 0:
                max_entity = self.get_max_fitness()
                fit = self.calc_fitness(max_entity)
                if fit >= halt:
                    self.halt_reached = 1
                    return [max_entity]
               
        return self.entities

I can actually print the self.entities list once for each iteration, 
before the evaluation takes place. What I dont know is how to actually 
do something with the list, like putting it in a variable or something 
to get access to it and actualize the geometry of my project. So 
basically if there are 100 iterations I would need a way to get this 
list 100 times, one for each iteration with its new data.

And just in case that it helps, the address of the forum were I uploaded 
a piece of the code:

http://python-forum.org/py/viewtopic.php?p=11063#11063

And the GA project page:

Genetic Algorithm Python module
http://www.alextreme.org/projects/python_ai/

If you can help me please do it, this is critical for my project :(

Thanks for helping
Carlos


From thomas.coopman at gmail.com  Sat Jan 13 13:12:51 2007
From: thomas.coopman at gmail.com (thomas coopman)
Date: Sat, 13 Jan 2007 13:12:51 +0100
Subject: [Tutor] Problems with a Class
In-Reply-To: <45A82315.5010908@web.de>
References: <mailman.7912.1168635486.32030.tutor@python.org>
	<45A82315.5010908@web.de>
Message-ID: <20070113131251.57544b44@localhost>

On Sat, 13 Jan 2007 01:08:53 +0100
Carlos <carloslara at web.de> wrote:

> Hello,
> 
> I'm just about to finish my project, but something is causing me 
> trouble. I need to find out how to get some information out of the 
> genetic algorithm that Im using. This algorithm is generating some 
> coordinates for a collection of objects, until now I needed only the 
> final result of the process. But I discovered that the final
> information is not enough, I need to get some intermediate data to
> actualize the positions of the objects and then evaluate those
> positions.
> 
> This is the area of the algorith that I think holds the info that I
> need:
> 
> def evolve(self, generations = 100):
>   
>         self.halt_reached = 0
>        
>         for gen in range(generations):
> 
>             #Changed.
>             print 'GEN:',gen, self.entities
>            
>             self.do_mutation()
>             self.do_crossover()
>             print "Average fitness generation " + str(gen) + ": " + 
> str(self.avg_fitness())
>             if self.debug == 1:
>                 self.echo_fitness()
>             if self.halt >= 0:
>                 max_entity = self.get_max_fitness()
>                 fit = self.calc_fitness(max_entity)
>                 if fit >= halt:
>                     self.halt_reached = 1
>                     return [max_entity]
> 
> The line marked as #Changed is what I changed,  with this I was able
> to print the info, but I'm sorry to say that I have no clue at how to
> apply something like return() that would give me this self.entities
> list. As you can see there is a for loop and I need the info every
> time that it gets updated by the loop.
> 
> Hopefully I'm making myself clear and the info is enough.
> 
> Thanks for your help in advance
> Carlos
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


Hi,

when you call return, you return from the function so
when you have something like this:

def loop():
	for i in range(10):
		return i

print loop()

This will print just 0.

when you want to get all the numbers, you can't use return in the loop
you could save them in a list or something, and after the loop return
the list.

def loop():
	x = []
	for i in range(10):
		x.append(i)
	return x

print loop()

this will print a list with all the numbers.

I hope this is what you mean.


Thomas

From carloslara at web.de  Sat Jan 13 12:02:02 2007
From: carloslara at web.de (Carlos)
Date: Sat, 13 Jan 2007 12:02:02 +0100
Subject: [Tutor] Problems with a Class
In-Reply-To: <mailman.7970.1168663628.32030.tutor@python.org>
References: <mailman.7970.1168663628.32030.tutor@python.org>
Message-ID: <45A8BC2A.4080302@web.de>

Hello Again,

Looks like Im getting there now. I did this inside the GA module:

def update(self):

        return self.entities

now Im putting it in my code:

def my_fitness(entity):
        x = ga.update()
        print 'X', x
        fitness = 0.0
        for i in entity:
            if i == 1:
                fitness += 1.0
        return fitness

This fitness fuction sets the evaluation criteria. I does the job, but 
there is a small problem, it returns too much information! for example 
in generation 1 it gives:

X [[0, 0, 1, 1, 0, 1, 1, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 
1, 1, 0, 0, 0, 0]]
X [[0, 0, 1, 1, 0, 1, 1, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 
1, 1, 0, 0, 0, 0]]
X [[0, 0, 1, 1, 0, 1, 1, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 
1, 1, 0, 0, 0, 0]]
X [[0, 0, 1, 1, 0, 1, 1, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 
1, 1, 0, 0, 0, 0]]
X [[0, 0, 1, 1, 0, 1, 1, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 
1, 1, 0, 0, 0, 0]]

and in generation 2:

X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 
0, 1, 1, 0, 0, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 
1, 1, 0, 1, 1, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 
1, 1, 0, 1, 1, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 
1, 1, 0, 1, 1, 0]] ## Small change here
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 
1, 1, 0, 1, 1, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 
1, 1, 0, 1, 1, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 
1, 1, 0, 1, 1, 0]]
X [[1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 
1, 0, 1, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 
1, 1, 0, 1, 1, 0]]

As you can see it is almost the same, the problem is that if I update my 
3D objects with each list, the system becomes too slow because I'm 
working with hundreds and even thousands of generations, and updating 
geometry is not a vera fast process.

The question now would be, how to update my objects only if the new list 
is different from the previous???



From zebra05 at gmail.com  Sat Jan 13 15:25:05 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Sat, 13 Jan 2007 16:25:05 +0200
Subject: [Tutor] lighttpd for windows
Message-ID: <c7c6f3bc0701130625n3fdd47acvbece77c14f877894@mail.gmail.com>

hey folks!

Could someone please show me where to get lighttpd for windows xp sp2? ive
tried the lighttpd site but no success

thanks

"shortash"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070113/ea6b6982/attachment.html 

From geoframer at gmail.com  Sun Jan 14 14:01:03 2007
From: geoframer at gmail.com (Geoframer)
Date: Sun, 14 Jan 2007 14:01:03 +0100
Subject: [Tutor] Python and rpy
In-Reply-To: <45A5E6D1.5080101@h-lab.net>
References: <5d8e35a70612210743j69f30d54kfec867df695a93b6@mail.gmail.com>
	<458AEDE3.8030006@tds.net>
	<5d8e35a70612220221r7f324d1fl30ef1810d6c838c1@mail.gmail.com>
	<458F31E0.9070107@tds.net>
	<5d8e35a70612280431s6a423dffg720a6bd8a3abd241@mail.gmail.com>
	<45A5E6D1.5080101@h-lab.net>
Message-ID: <5d8e35a70701140501x7475aa0j877a8e0f390cb311@mail.gmail.com>

I actually had Numeric under WinXP also, manually installed it and could
import Numeric so that wasn't it imho.

On 1/11/07, Hugo Gonz?lez Monteverde <hugonz-lists at h-lab.net> wrote:
>
> Geoframer wrote:
> >
> > However i switched to Ubuntu 6.10 today (from WinXP) and to my suprise
> > it does work under linux! :-)
>
> Probably Numeric is included in Ubuntu's  Python distro.
>
> Hugo
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070114/0b858423/attachment.html 

From agunnerson at gmail.com  Sun Jan 14 16:47:06 2007
From: agunnerson at gmail.com (Andy)
Date: Sun, 14 Jan 2007 08:47:06 -0700
Subject: [Tutor] Is Python the language for me?
Message-ID: <26e972870701140747p63eb896by35ddfe433d92bebc@mail.gmail.com>

Hey everyone, I'm looking to get the opinions of some people with more
experience then myself.  Currently I only have time to learn one
language and I'm torn between C++ and Python.  Eventually I would like
to make a game, nothing too extravagant, a turn based strategy game to
be exact.  I'm not planning on having crazy graphics effects, I'm
going to focus on game play.  Anyway, I'm getting a little off course
here.  I want to learn one of the two mentioned languages with the end
goal to be able to make my game.  I know it's a long way off before
I'll be able to make it so please don't assume that I'm going to jump
right in expecting to make this in a matter of months.  Besides the
game, I have all kinds of ideas for small little programs that I would
like to make.

I would honestly rather use Python then C++ but I have a few concerns.
 How hard is it to manage a large project in Python vs. C++?  If I do
decide to use Python I would be using Pygame for the graphics end of
things.  From what I can tell, Pygame does not work with the current
release of Python, that's one of the things that causes me to worry.
If I finish this game and release it, are people going to constantly
be having to upgrade Python and Pygame for it to keep working?  And
how much really changes between releases?

Python has built in access to a windowing toolkit (Tkinter), C++ can
of course use the native windows/linux/mac API but that seems like
more of a hassle to me.  Once the C++ program has been compiled it's
much easier to distribute.  C++ has a much higher learning curve and
development time then Python does.  Python has a much nicer community
built around it then C++ from what I can see though.

So as you can see I feel that each language has it's own pro's and
con's and I might end up learning them both eventually.  Do you all
think Python will work for what I want right now?  My biggest concern
with Python is the upkeep involved in trying to distribute your
applications.  Do updates to Python usually cause issues?  Why would
something like Pygame work with Python 2.4 but not 2.5?

I'm sorry if this is a horribly dumb question but I've been looking
around and I can't find the answer to these on my own.  Thank you all
for any help you can give me.

-- 
-Andy
"I have a great faith in fools; self-confidence my friends call it." ?
Edgar Allen Poe

From ajkadri at googlemail.com  Sun Jan 14 22:10:11 2007
From: ajkadri at googlemail.com (Asrarahmed Kadri)
Date: Sun, 14 Jan 2007 21:10:11 +0000
Subject: [Tutor] Change the font size of the lines and rectangle on a
	Tkinter Canvas
Message-ID: <b4e894c70701141310o29b3f8f2p4371fec8478c88@mail.gmail.com>

Hi Folks,

I have a Tkinter canvas on which there are two axes: X and Y and a
horizontal bar chart.

I want to provide with a functionality of changing the font size, in this
case the width of the lines.

Is it possible to do it dynamically; I mean the graph is already drawn, now
with a Menu, suppose I want to provide the user with options of 50%, 100%
and 200% font size.

Can you tell me how to do it.?

Thanks in anticipation.

Best Regards,
Asrarahmed


-- 
To HIM you shall return.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070114/7af5a6bf/attachment.html 

From rabidpoobear at gmail.com  Sun Jan 14 22:58:29 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 14 Jan 2007 15:58:29 -0600
Subject: [Tutor] Is Python the language for me?
In-Reply-To: <26e972870701140747p63eb896by35ddfe433d92bebc@mail.gmail.com>
References: <26e972870701140747p63eb896by35ddfe433d92bebc@mail.gmail.com>
Message-ID: <45AAA785.5070809@gmail.com>

Andy wrote:
> Hey everyone, I'm looking to get the opinions of some people with more
> experience then myself.  Currently I only have time to learn one
> language and I'm torn between C++ and Python.  Eventually I would like
> to make a game, nothing too extravagant, a turn based strategy game to
> be exact.  I'm not planning on having crazy graphics effects, I'm
> going to focus on game play.  Anyway, I'm getting a little off course
> here.  I want to learn one of the two mentioned languages with the end
> goal to be able to make my game.  I know it's a long way off before
> I'll be able to make it so please don't assume that I'm going to jump
> right in expecting to make this in a matter of months.  Besides the
> game, I have all kinds of ideas for small little programs that I would
> like to make.
>   
Sound like reasonable goals to me :)
> I would honestly rather use Python then C++ but I have a few concerns.
>  How hard is it to manage a large project in Python vs. C++?
I have found things that would be a 'large project' in C++ often aren't 
nearly as large in Python.
I think if you have a large project in Python, the equivalent project in 
C++ would be much harder to manage.
you can use packages and such to keep your code manageable.  It's 
probably a good idea to keep your code separated
from the get-go when you reach the time to make your game, because it'll 
eventually get to the point where you'll need to break it apart,
so you'd be doing yourself a favor.
>   If I do decide to use Python I would be using Pygame for the graphics end of
> things.  From what I can tell, Pygame does not work with the current
> release of Python, that's one of the things that causes me to worry.
> If I finish this game and release it, are people going to constantly
> be having to upgrade Python and Pygame for it to keep working?  And
> how much really changes between releases?
>
> Python has built in access to a windowing toolkit (Tkinter), C++ can
> of course use the native windows/linux/mac API but that seems like
> more of a hassle to me.  Once the C++ program has been compiled it's
> much easier to distribute.  C++ has a much higher learning curve and
> development time then Python does.  Python has a much nicer community
> built around it then C++ from what I can see though.
>   
Okay, first thing to note:  a lot of Python developers prefer wxPython 
to Tkinter.
There is an equivalent library in C++, since wxPython is really just a 
light wrapper around wxWindows.
There's a big community around that project, and I doubt it would be too 
much harder to learn wxWindows vs wxPython.
(Trying not to sound too biased toward Python :) )

Now to address your concern about Python and Pygame:
If your program works with a certain version of Python and Pygame,
say  Python 2.4.4 and pygame 1.7,
it will continue to work for Python 2.x.  Python versions maintain 
backward compatibility very well,
but in Python 3000, they're going to break backward compatibility.
I believe the same is the case in Pygame versions (unless they make the 
1.8 release use NumPy instead of Numeric,
which would require a few changes to some people's code, likely only a 
line or two.)
So once you write your game, people will be able to upgrade and it will 
continue working.
But there's no reason for them to upgrade unless they need the new 
features of the new versions.

Also, something that should really ease your concerns:
You can create .exes with Python that will contain a static instance of 
whatever modules you had installed
at the point when you run py2exe (or some other packaging program) that 
are used in your game.
So if you use Numeric version 2.55 and Python 2.4.3 and Pygame 1.7, then 
those versions of the packages
will be included in a file you can distribute.  Well, it's not a single 
file, but a zipped collection of files.
In that case, people don't even need Python installed on their computer 
to run your game!
It also doesn't interfere with any Python versions they may have 
installed on their computer.

So in that case you don't have to worry at all about people upgrading 
libraries, just like you wouldn't if you were to make
a binary in C++.
> So as you can see I feel that each language has it's own pro's and
> con's and I might end up learning them both eventually.  Do you all
> think Python will work for what I want right now?  My biggest concern
> with Python is the upkeep involved in trying to distribute your
> applications.  Do updates to Python usually cause issues?  Why would
> something like Pygame work with Python 2.4 but not 2.5?
>   
As an introductory language to Computer Science I'd recommend Python.
You spend less time trying to understand the language itself and more 
time learning abstract concepts like
how a merge sort works, inheritance, classes, 'self', and things like that.
Once you understand all of these things, C++ will be greatly easier to 
pick up, as should most Object-Oriented languages be.
I think if you start with C++, you'll get discouraged.
Perhaps not, but that's how it worked with me.

A few years ago, I tried to learn C++, and I failed miserably.
Then, later that year, I learned Java in a Computer Science class in 
High School.  I hated that but I slightly understood it.
My Stepdad started getting into Python around that time (he'd been a 
professional  C programmer for 15+ years).
I decided to pick it up after a while talking to him, and I found it 
much less difficult to learn.
And now I'm half-way through with my second year in College as a  
Computer Science major ^_^.

Of course this wouldn't apply to everybody, and the fact that I was 
fairly young when I tried to learn C++ I'm sure had an effect.
But I think if I hadn't picked up Python, I wouldn't be a Computer 
Science major now.
As it turns out, all of the classes at my school are in C++.  But 
despite the fact that I came here with barely any C++ experience,
I had _programming_ experience, and that, as they say, made all the 
difference.

To address some of your other questions:
No, updates to Python don't usually cause issues.  With the exception of 
Python 3000, they don't break backwards compatibility
as far as I know.

My understanding:
Pygame 1.7 works in both Python 2.4 and 2.5.  The problem is that no one 
has made binaries for Windows.
So there's no installer for 1.7 and 2.5, but it's possible.  No one took 
the time, because 2.5 came out around the time when pygame 1.8 was set 
to come out,
so everyone assumed that was a natural time to transition.  Obviously if 
I'm wrong feel free to correct me.
> I'm sorry if this is a horribly dumb question but I've been looking
> around and I can't find the answer to these on my own.  Thank you all
> for any help you can give me.
>   
No, there are no dumb questions on the Tutor list, just questions that 
are poorly asked :)
And your questions all made sense, so I was happy to reply.

In conclusion,
Python + Pygame would be great for a turn-based strategy game.  It's not 
something that requires extremely fast graphics processing,
so the speed hit from using P&P versus C++ and SDL would be easily made 
up, and surpassed, by the faster development time of using P&P.

And the Tutor list would be happy to help you on your quest to learn 
Python, if that's what you choose.
If you were thinking of making a First Person Shooter, my recommendation 
might be different.
But given your goal, I think Python's the better language to achieve 
that, and in a realistic time-frame.

One thing you might strive toward, depending how much time you have to 
devote to learning Python,
is that in 3 months or so, the Pyweek game programming competition is 
coming up.
I find that, by them giving you only a week to make a game, it really 
opens your eyes to the design issues
that will present themselves whenever you begin to make your turn-based 
strategy game.
Even if you don't finish a game (I've competed in 3 Pyweeks so far, and 
haven't ever completed a game enough
that I would submit a final entry), it's a great learning experience.

Sorry for the long-winded reply ;)

Hope That Helps,
-Luke


From tpc at cryptic.com  Mon Jan 15 11:08:10 2007
From: tpc at cryptic.com (tpc at cryptic.com)
Date: Mon, 15 Jan 2007 02:08:10 -0800
Subject: [Tutor] question about object oriented programming and inheritance
	using datetime module
Message-ID: <bae1efdf0701150208p366c67d3oe0f689687a2d4044@mail.gmail.com>

hey guys, I've been experimenting with Python's datetime module, and I
created a function that, given a person's birthdate, calculates how old that
person is.  Now I want to create a class called age_calculator that does
much the same thing.  My class inherits from the date class, but I have to
type 'from datetime import date' before I can initialize the class
definition.  Is there some way to avoid this ?

Also, once I type the import statement and initialize my class definition, I
can create an instance of age_calculator.  The instance of age_calculator
stores the given birthdate, and gives me a infinite loop traceback when I
call self.today().  If I don't inherit from date, I would need to put the
import statement somewhere inside a method, and I don't recall ever seeing
that done.  Part of me feels like that's not as elegant as defining an
age_calculator class that inherits from datetime.date, but I'm not sure how
to do this.  For what it's worth, here's my pseudocode (that inherits from
date module) and working code (that does not inherit from date module):

from datetime import date

class age_calculator(date):
    def __init__(self, year, month, day):
        time_delta = self.today() - self
        number_of_years = time_delta.days / 365
        return number_of_years

class age_calculator:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def calculate_age(self):
        from datetime import date
        birth_date = date(self.year, self.month, self.day)
        date_today = date.today()
        time_delta = date_today - birth_date
        number_of_years = time_delta.days / 365
        return number_of_years

age_calculator(1964, 9, 27).calculate_age()
42
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070115/4e2dbd7a/attachment.htm 

From rabidpoobear at gmail.com  Mon Jan 15 11:24:39 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 15 Jan 2007 04:24:39 -0600
Subject: [Tutor] question about object oriented programming and
 inheritance using datetime module
In-Reply-To: <bae1efdf0701150208p366c67d3oe0f689687a2d4044@mail.gmail.com>
References: <bae1efdf0701150208p366c67d3oe0f689687a2d4044@mail.gmail.com>
Message-ID: <45AB5667.50705@gmail.com>

tpc at cryptic.com wrote:
> hey guys, I've been experimenting with Python's datetime module, and I 
> created a function that, given a person's birthdate, calculates how 
> old that person is.  Now I want to create a class called 
> age_calculator that does much the same thing.  My class inherits from 
> the date class, but I have to type 'from datetime import date' before 
> I can initialize the class definition.  Is there some way to avoid 
> this ? 
No.
In order to use class inheritance syntax,
class some_class(some_object):

some_object must be defined.
Otherwise you'll get a variable not defined error.
You could make your own class called 'date' and inherit from that,
but what would be the point of that?
>
> Also, once I type the import statement and initialize my class 
> definition, I can create an instance of age_calculator.  The instance 
> of age_calculator stores the given birthdate, and gives me a infinite 
> loop traceback when I call self.today().  If I don't inherit from 
> date, I would need to put the import statement somewhere inside a 
> method, and I don't recall ever seeing that done.
What makes you think you'd have to import within a method?
Import datetime.date into the global namespace.
That's perfectly alright.
Especially since your class depends on it being available.
>   Part of me feels like that's not as elegant as defining an 
> age_calculator class that inherits from datetime.date, but I'm not 
> sure how to do this.  For what it's worth, here's my pseudocode (that 
> inherits from date module) and working code (that does not inherit 
> from date module):
The way you'd go about doing this is to make an extra function that is 
unique to your inherited class (for example, calculate_age).
>
> from datetime import date
>
> class age_calculator(date):
>     def __init__(self, year, month, day):
>         time_delta = self.today() - self
>         number_of_years = time_delta.days / 365
>         return number_of_years
This init method is overriding the init of the inherited date class.
The reason today() doesn't work is probably because of this.
>
> class age_calculator:
>     def __init__(self, year, month, day):
>         self.year = year
>         self.month = month
>         self.day = day
>
>     def calculate_age(self):
>         from datetime import date
>         birth_date = date( self.year, self.month, self.day)
>         date_today = date.today()
>         time_delta = date_today - birth_date
>         number_of_years = time_delta.days / 365
>         return number_of_years
>
Just move the import outside of the class.
from datetime import date
class age_calculator:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def calculate_age(self):
        birth_date = date( self.year, self.month, self.day)
        date_today = date.today()
        time_delta = date_today - birth_date
        number_of_years = time_delta.days / 365
        return number_of_years

I don't think you really want to inherit from date.
HTH,
-Luke

From kent37 at tds.net  Mon Jan 15 13:05:54 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 15 Jan 2007 07:05:54 -0500
Subject: [Tutor] question about object oriented programming and
 inheritance using datetime module
In-Reply-To: <bae1efdf0701150208p366c67d3oe0f689687a2d4044@mail.gmail.com>
References: <bae1efdf0701150208p366c67d3oe0f689687a2d4044@mail.gmail.com>
Message-ID: <45AB6E22.7030503@tds.net>

tpc at cryptic.com wrote:
> hey guys, I've been experimenting with Python's datetime module, and I 
> created a function that, given a person's birthdate, calculates how old 
> that person is.  Now I want to create a class called age_calculator that 
> does much the same thing.  

Why? You have a perfectly good function that does what you want, there 
is no need to turn it into a class. One of the strengths of Python is 
that not everything needs to be a class.

> My class inherits from the date class, but I 
> have to type 'from datetime import date' before I can initialize the 
> class definition.  Is there some way to avoid this ? 

No, and really there is no reason to want to avoid this. You have to 
import any external module that you want to use directly. Imports are 
very common in Python code and there is no reason not to use them.

Inheriting from date isn't a very good idea. You should inherit from 
date if your class will be a specialized kind of date. I guess you could 
think of your class as adding an age() method to date, but you are 
thinking of it as a calculator. Also date objects are immutable which 
makes it harder to create a subclass of date. (You have to override 
__new__() rather than __init__(), but explaining that will probably just 
confuse you at this point.)

There are a few things in your code that are a bit confused - you need 
to call the base class __init__() in your __init__() method, and 
__init__() does not return a value. You should probably read up a bit 
more on classes in Python, either a book or one of the on-line tutorials.

> 
> Also, once I type the import statement and initialize my class 
> definition, I can create an instance of age_calculator.  The instance of 
> age_calculator stores the given birthdate, and gives me a infinite loop 
> traceback when I call self.today().  If I don't inherit from date, I 
> would need to put the import statement somewhere inside a method, and I 
> don't recall ever seeing that done.

It is OK to put an import inside a function or method, but why do you 
think you need to do this?

>  Part of me feels like that's not as 
> elegant as defining an age_calculator class that inherits from 
> datetime.date, but I'm not sure how to do this.  For what it's worth, 
> here's my pseudocode (that inherits from date module) and working code 
> (that does not inherit from date module):
> 
> from datetime import date
> 
> class age_calculator(date):
>     def __init__(self, year, month, day):
>         time_delta = self.today() - self
>         number_of_years = time_delta.days / 365
>         return number_of_years

I'm not sure why this gives an infinite loop (not even sure what an 
"infinite loop traceback" is), but you have not initialized the base 
class so the year, month, day parameters are not used at all.

> 
> class age_calculator:
>     def __init__(self, year, month, day):
>         self.year = year
>         self.month = month
>         self.day = day
> 
>     def calculate_age(self):
>         from datetime import date
>         birth_date = date( self.year, self.month, self.day)
>         date_today = date.today()
>         time_delta = date_today - birth_date
>         number_of_years = time_delta.days / 365
>         return number_of_years

This is better, but compare it to your functional version and you should 
see why the function is preferred.

Kent

> 
> age_calculator(1964, 9, 27).calculate_age()
> 42
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



From python-tutor at ccoker.net  Mon Jan 15 18:53:30 2007
From: python-tutor at ccoker.net (Chuck Coker)
Date: Mon, 15 Jan 2007 09:53:30 -0800
Subject: [Tutor] Is Python the language for me?
In-Reply-To: <45AAA785.5070809@gmail.com>
References: <26e972870701140747p63eb896by35ddfe433d92bebc@mail.gmail.com>
	<45AAA785.5070809@gmail.com>
Message-ID: <45ABBF9A.2050703@ccoker.net>

Andy,

Disclaimer: I'm a Python newbie, although I've been developing
software for many years.

(In my humble opinion,) Luke makes some critically important points
here. The first one has to do with programming ~concepts~.

LP> As an introductory language to Computer Science I'd recommend
LP> Python. You spend less time trying to understand the language
LP> itself and more time learning abstract concepts like how a merge
LP> sort works, inheritance, classes, 'self', and things like that.
LP> Once you understand all of these things, C++ will be greatly
LP> easier to pick up, as should most Object-Oriented languages be. I
LP> think if you start with C++, you'll get discouraged. Perhaps not,
LP> but that's how it worked with me.
...
LP> As it turns out, all of the classes at my school are in C++. But
LP> despite the fact that I came here with barely any C++ experience,
LP> I had _programming_ experience, and that, as they say, made all
LP> the difference.

I went from C to C++ and had an extremely difficult time with shifting
my thinking to object orientation.

Once I learned the basics of O-O programming, I've found it very easy
to shift from one language to another. As a contract developer for
hire, and in my work as an employee at Tyrell Software, I frequently
run into situations where, for whatever reason, I need to use a
language that I know nothing about.

Example: On my current project at Tyrell Software, the decision was
made to use a load-testing package named The Grinder. (I highly
recommend The Grinder: http://grinder.sourceforge.net/) The
load-testing part of the project was handed to me. I knew I would have
some questions about Python, so I asked who our resident Python Guru
was. They told me, "You are, now." Sometimes you need to learn fast.

Having learned the basic concepts, when going to a new language, I
have to devote much of my learning time to language syntax issues,
rather than learning the basics all over again.

Don't let anyone tell you that language X is superior to language Y.
In one particular instance that may be so, but in the grand scheme of
things it all evens out. Different languages do different things
better and worse than other languages, but the O-O concepts remain the
same. (This week, I'm being paid to write Python code, so Python
is clearly the superior language. :-) )

LP> ... you can use packages and such to keep your code manageable.
LP> It's probably a good idea to keep your code separated from the
LP> get-go when you reach the time to make your game, because it'll
LP> eventually get to the point where you'll need to break it apart,
LP> so you'd be doing yourself a favor.

Packages, modules, libraries -- whatever you want to call them -- are
the way to go. If you put a little bit of thought into them when
writing them, most things can be reused at some future time. Most code
you write will be code that you will write over and over.

Try to keep your pieces small and generic, except, or course, where
you need to do a specific step that applies to your current project
only.

Good luck on your project.

Chuck

-- 
======================================================================
Chuck Coker, Software Developer                python-tutor at ccoker.net
Tyrell Software Corporation                      http://www.tyrell.com
Office: +1 949 458 1911 x 203                    Cell: +1 714 326 5939
======================================================================


From carroll at tjc.com  Mon Jan 15 19:26:59 2007
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 15 Jan 2007 10:26:59 -0800 (PST)
Subject: [Tutor] Is Python the language for me?
In-Reply-To: <45AAA785.5070809@gmail.com>
Message-ID: <Pine.LNX.4.44.0701151023080.26786-100000@violet.rahul.net>

On Sun, 14 Jan 2007, Luke Paireepinart wrote:

> Okay, first thing to note:  a lot of Python developers prefer wxPython 
> to Tkinter.

I'd second this.  I've never used wxPython, because the documentation is 
not (at least to me) well suited to learning it (as opposed to using it 
once you already understand the basics).

However, the recently published "wxPython in Action," 
http://www.manning.com/rappin/ , has changed that for me.  It's not 
perfect, but it's very very good.  It has made wxPython accessible to me.

I've only used wxPython for a few toy demos to try out a few features, but 
I'm now at the point that I don't plan on using Tkinter any more, and 
that's all I've used for GUI apps for the past two years.



From kent37 at tds.net  Mon Jan 15 19:27:22 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 15 Jan 2007 13:27:22 -0500
Subject: [Tutor] Is Python the language for me?
In-Reply-To: <26e972870701140747p63eb896by35ddfe433d92bebc@mail.gmail.com>
References: <26e972870701140747p63eb896by35ddfe433d92bebc@mail.gmail.com>
Message-ID: <45ABC78A.8060605@tds.net>

Andy wrote:

> So as you can see I feel that each language has it's own pro's and
> con's and I might end up learning them both eventually.  Do you all
> think Python will work for what I want right now?

You don't say, but it sounds like you are just starting out with 
programming. I strongly second what Luke said - Python is a great 
language to start with, much easier than C++, and if you sometime decide 
to learn C++ it will be much easier when you already know how to program.

>  My biggest concern
> with Python is the upkeep involved in trying to distribute your
> applications.  Do updates to Python usually cause issues?  Why would
> something like Pygame work with Python 2.4 but not 2.5?

Point upgrades such as 2.4 to 2.5 generally keep a high level of 
backward compatibility for Python code, so a Python program that runs 
under 2.4 will most likely run the same under 2.5. However, point 
upgrades do not retain binary compatibility for compiled extensions such 
as pygame; these extensions need to be rebuilt for the new version. On 
Windows most Python programmers are not willing / interested / able to 
compile the extensions themselves, so it is common for binary installers 
to be distributed for Windows versions of extensions. When a new Python 
comes out, these have to be updated. The pace of the updates varies 
widely depending on how active the extension project is and how much the 
developers care about Windows. For some users the availability of a key 
extension is what gates the upgrade.

Kent


From alan.gauld at btinternet.com  Tue Jan 16 01:33:20 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 16 Jan 2007 00:33:20 -0000
Subject: [Tutor] Change the font size of the lines and rectangle on
	aTkinter Canvas
References: <b4e894c70701141310o29b3f8f2p4371fec8478c88@mail.gmail.com>
Message-ID: <eoh6gh$uaj$1@sea.gmane.org>


"Asrarahmed Kadri" <ajkadri at googlemail.com> wrote

> I want to provide with a functionality of changing the font size, in 
> this
> case the width of the lines.
Its not really the font size. fonts only apply to text, its only
the line width you want to change. However todo that I
think the easiest way is just to elete the existing line
(and maybe the whole graph) and redraw with the new
parameters. Provideed the data has been precalculated
then this should be a rapid operation.


> Is it possible to do it dynamically; I mean the graph is
> already drawn, now with a Menu, suppose I want to
> provide the user with options of 50%, 100%
> and 200% font size.

You will need to store the line thicknesses in variables
so that the drawing routine can be parameter driven. Then
simply delete the existing graph and redraw it with the
new thickness - remember you may need to rescale
your axis to cater for thicker/thinner lines.

If you are using a filled Rectangle rather than a real line
(which is what I would actually expect to see in a bar chart)
then obviously the line thickness simply involves setting
the difference in the y coordinates appropriately.

Alan G. 



From rabidpoobear at gmail.com  Tue Jan 16 02:07:01 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 15 Jan 2007 19:07:01 -0600
Subject: [Tutor] [Fwd: Re: Is Python the language for me?]
Message-ID: <45AC2535.3030603@gmail.com>

Alan accidentally e-mailed me directly.. forwarding to list! :)
-------------- next part --------------
An embedded message was scrubbed...
From: "Alan Gauld" <alan.gauld at freenet.co.uk>
Subject: Re: Is Python the language for me?
Date: Tue, 16 Jan 2007 00:49:54 -0000
Size: 4626
Url: http://mail.python.org/pipermail/tutor/attachments/20070115/7e3802ef/attachment.mht 

From thomas.coopman at gmail.com  Tue Jan 16 10:01:10 2007
From: thomas.coopman at gmail.com (Thomas Coopman)
Date: Tue, 16 Jan 2007 10:01:10 +0100
Subject: [Tutor] import and unittest
Message-ID: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>

Hi,

the documentation of pyunit
say that it is good to place the unittest in a seperate module.
I wondered if it was possible to do something like this:

src/
    -a_module/
        -sub_module/
test/
    -a_module/
        -sub_module/

So the test are in a complete different directory than the code and the test
dir is a complete copy
of the src dir but with unittest instead of code.

I have something like this but I don't know how to organize the imports in
the tests and I don't know
if this is a good idea.  What do you think?

Thanks

-- 
Thomas Coopman
Thomas.coopman at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070116/694ac548/attachment-0001.html 

From ajkadri at googlemail.com  Tue Jan 16 10:37:24 2007
From: ajkadri at googlemail.com (Asrarahmed Kadri)
Date: Tue, 16 Jan 2007 09:37:24 +0000
Subject: [Tutor] Change the font size of the lines and rectangle on
	aTkinter Canvas
In-Reply-To: <eoh6gh$uaj$1@sea.gmane.org>
References: <b4e894c70701141310o29b3f8f2p4371fec8478c88@mail.gmail.com>
	<eoh6gh$uaj$1@sea.gmane.org>
Message-ID: <b4e894c70701160137y6e27ee37y26d621dde103597e@mail.gmail.com>

I want to change the coordinates because I was under the wrong impression;
when I gave some thought then only I realised that the COORDINATES need to
be changed in order to increase the dimensions of the GRAPH and in turn the
entire frame, canvas, and the toplevel window that is holding the frame and
the canvas..

Is there a method that redraws the toplevel windows that is holding the
widgets....

If yes, then can you suggest me how to do it..

Thanks in anticipation.

Regards,
Asrarahmed Kadri


On 1/16/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>
> "Asrarahmed Kadri" <ajkadri at googlemail.com> wrote
>
> > I want to provide with a functionality of changing the font size, in
> > this
> > case the width of the lines.
> Its not really the font size. fonts only apply to text, its only
> the line width you want to change. However todo that I
> think the easiest way is just to elete the existing line
> (and maybe the whole graph) and redraw with the new
> parameters. Provideed the data has been precalculated
> then this should be a rapid operation.
>
>
> > Is it possible to do it dynamically; I mean the graph is
> > already drawn, now with a Menu, suppose I want to
> > provide the user with options of 50%, 100%
> > and 200% font size.
>
> You will need to store the line thicknesses in variables
> so that the drawing routine can be parameter driven. Then
> simply delete the existing graph and redraw it with the
> new thickness - remember you may need to rescale
> your axis to cater for thicker/thinner lines.
>
> If you are using a filled Rectangle rather than a real line
> (which is what I would actually expect to see in a bar chart)
> then obviously the line thickness simply involves setting
> the difference in the y coordinates appropriately.
>
> Alan G.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
To HIM you shall return.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070116/c9860c00/attachment.htm 

From klappnase at freenet.de  Tue Jan 16 10:52:22 2007
From: klappnase at freenet.de (Michael Lange)
Date: Tue, 16 Jan 2007 10:52:22 +0100
Subject: [Tutor] Change the font size of the lines and rectangle on
 aTkinter Canvas
In-Reply-To: <eoh6gh$uaj$1@sea.gmane.org>
References: <b4e894c70701141310o29b3f8f2p4371fec8478c88@mail.gmail.com>
	<eoh6gh$uaj$1@sea.gmane.org>
Message-ID: <20070116105222.3c84ffb1.klappnase@freenet.de>

On Tue, 16 Jan 2007 00:33:20 -0000
"Alan Gauld" <alan.gauld at btinternet.com> wrote:

> 
> "Asrarahmed Kadri" <ajkadri at googlemail.com> wrote
> 
> > I want to provide with a functionality of changing the font size, in 
> > this
> > case the width of the lines.
> Its not really the font size. fonts only apply to text, its only
> the line width you want to change. However todo that I
> think the easiest way is just to elete the existing line
> (and maybe the whole graph) and redraw with the new
> parameters. Provideed the data has been precalculated
> then this should be a rapid operation.
> 

I am not sure if the OP meant to increase the graph elements according
to the font size, so the graph does not look tiny next to a huge font.

Anyway, there is no need to delete and recreate the items, just calculate
the new coordinates and pass them to Canvas.coords()

> 
> > Is it possible to do it dynamically; I mean the graph is
> > already drawn, now with a Menu, suppose I want to
> > provide the user with options of 50%, 100%
> > and 200% font size.
> 
> You will need to store the line thicknesses in variables
> so that the drawing routine can be parameter driven. Then
> simply delete the existing graph and redraw it with the
> new thickness - remember you may need to rescale
> your axis to cater for thicker/thinner lines.
> 

This is probably not necessary either, you can query the size of canvas elements
dynamically, use Canvas.bbox() to query width and height of rectangles or
Canvas.itemcget(item, 'width') and again Canvas.bbox() for line elements.

> If you are using a filled Rectangle rather than a real line
> (which is what I would actually expect to see in a bar chart)
> then obviously the line thickness simply involves setting
> the difference in the y coordinates appropriately.
> 

If you only want to be able to resize the graph elements into half and double size
it is probably easiest to use the Canvas.scale() method for this, like

>>> from Tkinter import *
>>> c=Canvas()
>>> c.pack(fill='both', expand=1)
>>> r = c.create_rectangle(20, 20, 70, 30, fill='red')
>>> c.scale(r, 20, 20, 2, 2)
>>> c.scale(r, 20, 20, 0.5, 0.5)

However, text, image and window items cannot be scaled.
If you want to "scale" text items, it might be the best to pre-define
e.g. three pixel-sized fonts, like

fonts = {'small':'helvetica -10', 'normal':'helvetica -12', 'big':'helvetica -14'}

and then provide a callback that will both change the font size for the
text elements and scale the graph elements (and the x- and y-axis).

I hope this helps

Michael




From alan.gauld at btinternet.com  Tue Jan 16 10:59:49 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 16 Jan 2007 09:59:49 -0000
Subject: [Tutor] Change the font size of the lines and rectangle on
	aTkinter Canvas
References: <b4e894c70701141310o29b3f8f2p4371fec8478c88@mail.gmail.com><eoh6gh$uaj$1@sea.gmane.org>
	<20070116105222.3c84ffb1.klappnase@freenet.de>
Message-ID: <eoi7mn$iuf$1@sea.gmane.org>


"Michael Lange" <klappnase at freenet.de> wrote 

> If you only want to be able to resize the graph elements 
> into half and double size it is probably easiest to use the 
> Canvas.scale() method for this, like
> 
>>>> from Tkinter import *
>>>> c=Canvas()
>>>> c.pack(fill='both', expand=1)
>>>> r = c.create_rectangle(20, 20, 70, 30, fill='red')
>>>> c.scale(r, 20, 20, 2, 2)
>>>> c.scale(r, 20, 20, 0.5, 0.5)
> 

Neat! I haven't noticed scale() before.
Thanks for pointing it out.

Alan G.


From akap at isd.dp.ua  Tue Jan 16 10:49:45 2007
From: akap at isd.dp.ua (Alexander Kapshuk)
Date: Tue, 16 Jan 2007 11:49:45 +0200
Subject: [Tutor] python query
Message-ID: <70831DC71E5D814C9D1FA8A96653215E083A6F64@server.isd.dp.ua>

Dear All,

 

My name is Alexander Kapshuk. I'm interested in learning to program in
Python. I have very little programming experience. I've learnt some
basics of programming with Logo. 

 

I've downloaded Python 2.5 for Windows XP Professional.

 

I would appreciate any advice on what to do next. What books/tutorials
to use? 

 

I understand that learning a programming language involves practice. So,
I suppose, I could use a book/tutorial with loads of practical code
samples to try out.

 

Any other practical advice you may deem feasible would be welcome.

 

Thanking you in advance.

 

Alexander Kapshuk.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070116/61a79210/attachment.html 

From alan.gauld at btinternet.com  Tue Jan 16 11:06:37 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 16 Jan 2007 10:06:37 -0000
Subject: [Tutor] import and unittest
References: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>
Message-ID: <eoi83f$kj5$1@sea.gmane.org>


"Thomas Coopman" <thomas.coopman at gmail.com> wrote
.
> I wondered if it was possible to do something like this:
>
> src/
>    -a_module/
>        -sub_module/
> test/
>    -a_module/
>        -sub_module/
>

I don;t see any reason why not although its slightly more work.
Personally I tend to keep the tests with the code, but thats
mainly because tools such as editors tend to remember the last
folder opened and its a pain navigating between the two folders.

The other system I have used(in C++ not Python) is to have
a test folder inside each src folder like:

src/
   mod1/
       f1.py
       test/
          testf1.py
    mod2/
       f2.py
       f3.py
       test/
           testf1.py
           testf2.py

etc.

This minimises navigation and keeps the tests separate.
Its also relatively easy to filter out the tests when it comes
time to package upp the code for distribution (assuming
you want to lose them!)

> I have something like this but I don't know how to organize the 
> imports in
> the tests and I don't know if this is a good idea.  What do you 
> think?

I think in Python you should create a package structure for
your code so that import can find the modules more easily.
But I've never tried this in Python, my Python projects are rarely
big enough to warrant it.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From thomas.coopman at gmail.com  Tue Jan 16 15:27:18 2007
From: thomas.coopman at gmail.com (thomas coopman)
Date: Tue, 16 Jan 2007 15:27:18 +0100
Subject: [Tutor] import and unittest
In-Reply-To: <eoi83f$kj5$1@sea.gmane.org>
References: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>
	<eoi83f$kj5$1@sea.gmane.org>
Message-ID: <20070116152718.38fd8f7d@localhost>

On Tue, 16 Jan 2007 10:06:37 -0000
"Alan Gauld" <alan.gauld at btinternet.com> wrote:

> 
> "Thomas Coopman" <thomas.coopman at gmail.com> wrote
> .
> > I wondered if it was possible to do something like this:
> >
> > src/
> >    -a_module/
> >        -sub_module/
> > test/
> >    -a_module/
> >        -sub_module/
> >
> 
> I don;t see any reason why not although its slightly more work.
> Personally I tend to keep the tests with the code, but thats
> mainly because tools such as editors tend to remember the last
> folder opened and its a pain navigating between the two folders.
> 
> The other system I have used(in C++ not Python) is to have
> a test folder inside each src folder like:
> 
> src/
>    mod1/
>        f1.py
>        test/
>           testf1.py
>     mod2/
>        f2.py
>        f3.py
>        test/
>            testf1.py
>            testf2.py
> 
> etc.
> 
> This minimises navigation and keeps the tests separate.
> Its also relatively easy to filter out the tests when it comes
> time to package upp the code for distribution (assuming
> you want to lose them!)

I think I will use something like this.

> 
> > I have something like this but I don't know how to organize the 
> > imports in
> > the tests and I don't know if this is a good idea.  What do you 
> > think?
> 
> I think in Python you should create a package structure for
> your code so that import can find the modules more easily.
> But I've never tried this in Python, my Python projects are rarely
> big enough to warrant it.
> 
> 
Thanks.

From emilia12 at mail.bg  Tue Jan 16 15:18:06 2007
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Tue, 16 Jan 2007 16:18:06 +0200
Subject: [Tutor] it is about definitions
Message-ID: <1168957086.7d91ed87005f7@mail.bg>


is there a difference between:

class foo:

and

class foo():

or between these function definitions:

def bar():

and

def bar:

?

thanks in advance
E.


-----------------------------

??????? ???? ?? ???????????? On-line ?????????! 
????????????? .EU ?????? ?? ???????????? ???? ?? 15,90 ??.! 
www.SuperHosting.bg - ????????? ??????? ??????? 


From carloslara at web.de  Tue Jan 16 15:35:29 2007
From: carloslara at web.de (Carlos)
Date: Tue, 16 Jan 2007 15:35:29 +0100
Subject: [Tutor] Clustering?
In-Reply-To: <mailman.60.1168945211.11058.tutor@python.org>
References: <mailman.60.1168945211.11058.tutor@python.org>
Message-ID: <45ACE2B1.3090509@web.de>

Hello to everybody,

I have a question that I think is a little related to clustering, I have 
a list of lists, like this:

List = [[1,5],[6,8],[48,10],[99,56]]

The list is composed by a large number of lists not just four, and each 
'interior' list contains two numbers that are the location of an object 
in a plane, so they are X and Y coordinates, my question is:

Can I use this list to evaluate how many points are in a given range? 
Thats is taking the highest and lowest values for X an Y and, lets say 
divide that range in 10 regions, then get the number of objects on each 
region. Is this possible? and if yes, how canI do it? I ask this because 
as you know my python skills are not that great :)

Thanks in advance for your help,
Carlos


From andreas at kostyrka.org  Tue Jan 16 15:41:32 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Tue, 16 Jan 2007 15:41:32 +0100
Subject: [Tutor] it is about definitions
In-Reply-To: <1168957086.7d91ed87005f7@mail.bg>
References: <1168957086.7d91ed87005f7@mail.bg>
Message-ID: <20070116144132.GD27576@andi-lap.la.revver.com>

* emilia12 at mail.bg <emilia12 at mail.bg> [070116 15:19]:
> 
> is there a difference between:
> 
> class foo:
> 
> and
> 
> class foo():
This is a SyntaxError.
> 
> or between these function definitions:
> 
> def bar():
> 
> and
> 
> def bar:
This too.

Andreas

From Mike.Hansen at atmel.com  Tue Jan 16 16:18:21 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Tue, 16 Jan 2007 08:18:21 -0700
Subject: [Tutor] python query
References: <70831DC71E5D814C9D1FA8A96653215E083A6F64@server.isd.dp.ua>
Message-ID: <57B026980605A64F9B23484C5659E32E4C79CC@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Alexander Kapshuk
> Sent: Tuesday, January 16, 2007 2:50 AM
> To: tutor at python.org
> Subject: Re: [Tutor] python query
> 
> Dear All,
> 
>  
> 
> My name is Alexander Kapshuk. I'm interested in learning to 
> program in Python. I have very little programming experience. 
> I've learnt some basics of programming with Logo. 
> 
>  
> 
> I've downloaded Python 2.5 for Windows XP Professional.
> 
>  
> 
> I would appreciate any advice on what to do next. What 
> books/tutorials to use? 
> 
>  
> 
> I understand that learning a programming language involves 
> practice. So, I suppose, I could use a book/tutorial with 
> loads of practical code samples to try out.
> 
>  
> 
> Any other practical advice you may deem feasible would be welcome.
> 
>  
> 
> Thanking you in advance.
> 
>  
> 
> Alexander Kapshuk.

Here's some good books to read.

http://www.python.org/infogami-faq/tutor/tutor-what-are-some-good-books-
on-python/

Feel free to post questions to this list too.

Mike
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS

From alan.gauld at btinternet.com  Tue Jan 16 10:56:27 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Tue, 16 Jan 2007 09:56:27 +0000 (GMT)
Subject: [Tutor] Change the font size of the lines and rectangle on
	aTkinter Canvas
In-Reply-To: <b4e894c70701160137y6e27ee37y26d621dde103597e@mail.gmail.com>
Message-ID: <975506.14477.qm@web86103.mail.ird.yahoo.com>


--- Asrarahmed Kadri <ajkadri at googlemail.com> wrote:

> Is there a method that redraws the toplevel windows that is
> holding the widgets....

Yes, you can issue an update() command to any widget.
Usually you don't need to as Tkinter figures out when 
things have changed and updates itself, but 
occasionally you may need to fo it manually.

Alan G.


		
___________________________________________________________ 
The all-new Yahoo! Mail goes wherever you go - free your email address from your Internet provider. http://uk.docs.yahoo.com/nowyoucan.html

From kent37 at tds.net  Tue Jan 16 16:26:02 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 16 Jan 2007 10:26:02 -0500
Subject: [Tutor] python query
In-Reply-To: <70831DC71E5D814C9D1FA8A96653215E083A6F64@server.isd.dp.ua>
References: <70831DC71E5D814C9D1FA8A96653215E083A6F64@server.isd.dp.ua>
Message-ID: <45ACEE8A.3010302@tds.net>

Alexander Kapshuk wrote:
> Dear All,
> 
>  
> 
> My name is Alexander Kapshuk. I?m interested in learning to program in 
> Python. I have very little programming experience. I?ve learnt some 
> basics of programming with Logo.
> 
> I?ve downloaded Python 2.5 for Windows XP Professional.
> 
> I would appreciate any advice on what to do next. What books/tutorials 
> to use?

There are quite a few beginners tutorials available online, there is a 
list here:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Kent


From kent37 at tds.net  Tue Jan 16 16:29:02 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 16 Jan 2007 10:29:02 -0500
Subject: [Tutor] import and unittest
In-Reply-To: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>
References: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>
Message-ID: <45ACEF3E.9050106@tds.net>

Thomas Coopman wrote:
> Hi,
> 
> the documentation of pyunit 
> say that it is good to place the unittest in a seperate module.
> I wondered if it was possible to do something like this:
> 
> src/
>     -a_module/
>         -sub_module/
> test/
>     -a_module/
>         -sub_module/
> 
> So the test are in a complete different directory than the code and the 
> test dir is a complete copy
> of the src dir but with unittest instead of code.
> 
> I have something like this but I don't know how to organize the imports 
> in the tests and I don't know
> if this is a good idea.  What do you think?

I have tried this but I think it is more trouble than it is worth having 
an extra set of directories to navigate. I put the tests in the same 
directory as the module under test. The tests for module.py are in 
moduletest.py. By putting 'test' at the end, the tests are listed next 
to the module under test in directory listings, which I like.

I use ant (a Java tool) for most of my packaging and it is easy to 
filter files by name so I don't need an extra directory for that.

Kent


From andreengels at gmail.com  Tue Jan 16 16:35:20 2007
From: andreengels at gmail.com (Andre Engels)
Date: Tue, 16 Jan 2007 16:35:20 +0100
Subject: [Tutor] Clustering?
In-Reply-To: <45ACE2B1.3090509@web.de>
References: <mailman.60.1168945211.11058.tutor@python.org>
	<45ACE2B1.3090509@web.de>
Message-ID: <6faf39c90701160735n2edde26am359cedc2dac57952@mail.gmail.com>

2007/1/16, Carlos <carloslara at web.de>:
>
> Hello to everybody,
>
> I have a question that I think is a little related to clustering, I have
> a list of lists, like this:
>
> List = [[1,5],[6,8],[48,10],[99,56]]
>
> The list is composed by a large number of lists not just four, and each
> 'interior' list contains two numbers that are the location of an object
> in a plane, so they are X and Y coordinates, my question is:
>
> Can I use this list to evaluate how many points are in a given range?
> Thats is taking the highest and lowest values for X an Y and, lets say
> divide that range in 10 regions, then get the number of objects on each
> region. Is this possible? and if yes, how canI do it? I ask this because
> as you know my python skills are not that great :)
>

First, this feels like a list of tuples rather than a list of lists;
however, tuples and lists don't differ that much in their behaviour, so
there's nothing really lost.

And yes, it is possible. An inline if would be the way I would resolve that:

def withinrange(list,xmin,xmax,ymin,ymax):
    # Get the elements of list for which the first part of the pair is
between xmin and xmax
    # (inclusive) and the second between ymin and ymax.
    return [c for c in list if xmin <= c[0] <= xmax and ymin <= c[1] <=
ymax]

The longer but clearer method of doing the same would be:

def withinrange(list,xmin,xmax,ymin,ymax):
    templist = []
    for c in list:
        if xmin <= c[0] <= xmax and ymin <= c[1] <= ymax:
            templist.append(c)
    return templist

-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070116/6a460e22/attachment.htm 

From duncan at thermal.esa.int  Tue Jan 16 14:53:15 2007
From: duncan at thermal.esa.int (Duncan Gibson)
Date: Tue, 16 Jan 2007 14:53:15 +0100
Subject: [Tutor] import and unittest
In-Reply-To: <20070116152718.38fd8f7d@localhost>
References: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>
	<eoi83f$kj5$1@sea.gmane.org> <20070116152718.38fd8f7d@localhost>
Message-ID: <20070116145315.2b2aff20.duncan@thermal.esa.int>


> I wondered if it was possible to do something like this:
>
> src/
>    -a_module/
>        -sub_module/
> test/
>    -a_module/
>        -sub_module/

Why not really keep the test code with the main code?

# module code here
#

if __name__ == '__main__':

    import unittest

    class TestModuleCode(unittest.TestCase):
        """ test harness for Module code """

        def setUp(self):
            """ boiler plate for multiple tests """
            pass

        def testSomething
            """ ensure something happens as expected """
            pass

    unittest.main()


I even have some files where I test for command line parameters
and if so I process those. If not, I run the unittests.

Cheers
Duncan


From dyoo at hkn.eecs.berkeley.edu  Tue Jan 16 17:17:06 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 16 Jan 2007 08:17:06 -0800 (PST)
Subject: [Tutor] it is about definitions
In-Reply-To: <20070116144132.GD27576@andi-lap.la.revver.com>
References: <1168957086.7d91ed87005f7@mail.bg>
	<20070116144132.GD27576@andi-lap.la.revver.com>
Message-ID: <Pine.LNX.4.64.0701160811001.21814@hkn.eecs.berkeley.edu>



On Tue, 16 Jan 2007, Andreas Kostyrka wrote:

> * emilia12 at mail.bg <emilia12 at mail.bg> [070116 15:19]:
>>
>> is there a difference between:
>>
>> class foo:
>>
>> and
>>
>> class foo():
> This is a SyntaxError.


Hi Andreas,

We should ask Emilia why she's asking this question. This particular 
problem sounds way too close to a homework question for my comfort.  A 
more cautious approach might be better.

We can point out:

http://www.python.org/doc/tut/node11.html#SECTION0011310000000000000000
http://www.python.org/doc/tut/node11.html#SECTION0011500000000000000000


If Emilia is a CS student, then pointing out the grammar at:

http://www.python.org/doc/ref/class.html#tok-inheritance

would probably be helpful too.


Best of wishes!

From kent37 at tds.net  Tue Jan 16 17:17:55 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 16 Jan 2007 11:17:55 -0500
Subject: [Tutor] it is about definitions
In-Reply-To: <20070116144132.GD27576@andi-lap.la.revver.com>
References: <1168957086.7d91ed87005f7@mail.bg>
	<20070116144132.GD27576@andi-lap.la.revver.com>
Message-ID: <45ACFAB3.2080402@tds.net>

Andreas Kostyrka wrote:
> * emilia12 at mail.bg <emilia12 at mail.bg> [070116 15:19]:
>> is there a difference between:
>>
>> class foo:
>>
>> and
>>
>> class foo():
> This is a SyntaxError.

In Python 2.5 it is allowed and creates an old-style class, the same as 
if the parentheses are omitted.

Kent


From joe.abbey at gmail.com  Tue Jan 16 17:28:49 2007
From: joe.abbey at gmail.com (Joe Abbey)
Date: Tue, 16 Jan 2007 11:28:49 -0500
Subject: [Tutor] Array indexing
Message-ID: <b2a052580701160828g2ba0ee60w9eef307660168ac7@mail.gmail.com>

Hello,

I'm using Active Python v2.4.3.11 on a Windows XP machine.

Probably more relevant is that I'm just learning Python, as in I've been
writing Python for less than 24 hours.

While trying to implement a PE parser, I ran into the following problem:

#************** START CODE*******************
data = file.read(128);
directoryTable = struct.unpack('LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', data);
i=0;
print "Export table           0x%08X + 0x%08x" % (directoryTable[i+=1],
directoryTable[i+=1]);
print "Import table           0x%08X + 0x%08x" % (directoryTable[i+=1],
directoryTable[i+=1]);
#************** END CODE*******************

This code throws a syntax error at the first i+=1 on "line 4".

Why is this the case?

It seems like it would be very useful to be able to increment an index after
referencing into an array.

Is my approach busted?  Is there a better way to reference elements?

The "fix" I'm currently using is to write the index I want:

(directoryTable[0], directoryTable[1])

I was hoping someone on this list could point me in the right direction.

Thanks in advance!

Cheers,

Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070116/2c03f3b3/attachment.html 

From dyoo at hkn.eecs.berkeley.edu  Tue Jan 16 18:29:03 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 16 Jan 2007 09:29:03 -0800 (PST)
Subject: [Tutor] Array indexing
In-Reply-To: <b2a052580701160828g2ba0ee60w9eef307660168ac7@mail.gmail.com>
References: <b2a052580701160828g2ba0ee60w9eef307660168ac7@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0701160917550.11397@hkn.eecs.berkeley.edu>

> While trying to implement a PE parser, I ran into the following problem:
>
> #************** START CODE*******************
> data = file.read(128);
> directoryTable = struct.unpack('LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', data);
> i=0;
> print "Export table           0x%08X + 0x%08x" % (directoryTable[i+=1],
> directoryTable[i+=1]);
> print "Import table           0x%08X + 0x%08x" % (directoryTable[i+=1],
> directoryTable[i+=1]);
> #************** END CODE*******************
>
> This code throws a syntax error at the first i+=1 on "line 4".


Hi Joe,

Yes.  Python's assignments aren't expressions --- in Python, assignments 
are meant to visually stand out.  Unfortunately, this means you can't put 
the assignment within the array indexing expression.


There are a few workarounds.  One is to treat the directoryTable as a 
stream of values that we can iterate across.  For example:

##################################
>>> values = (3, 1, 4, 1, 5)
>>> i = iter(values)
>>> i
<tupleiterator object at 0x6dd50>
##################################

'i' here is an "iterator" that we can repeatedly use to get sequential 
elements:

#############
>>> i.next()
3
>>> i.next()
1
>>> i.next()
4
#############

In some sense, this should allow you to do what you had in your original 
code, since i.next() will both give you the value and, internally, move 
the iterator forward.


See:

     http://www.python.org/doc/tut/node11.html#SECTION0011900000000000000000

for a quick-and-dirty introduction to iterators.


Best of wishes!

From klappnase at freenet.de  Tue Jan 16 18:50:06 2007
From: klappnase at freenet.de (Michael Lange)
Date: Tue, 16 Jan 2007 18:50:06 +0100
Subject: [Tutor] Change the font size of the lines and rectangle on
 aTkinter Canvas
In-Reply-To: <975506.14477.qm@web86103.mail.ird.yahoo.com>
References: <b4e894c70701160137y6e27ee37y26d621dde103597e@mail.gmail.com>
	<975506.14477.qm@web86103.mail.ird.yahoo.com>
Message-ID: <20070116185006.50a69e76.klappnase@freenet.de>

On Tue, 16 Jan 2007 09:56:27 +0000 (GMT)
ALAN GAULD <alan.gauld at btinternet.com> wrote:

> 
> --- Asrarahmed Kadri <ajkadri at googlemail.com> wrote:
> 
> > Is there a method that redraws the toplevel windows that is
> > holding the widgets....
> 
> Yes, you can issue an update() command to any widget.
> Usually you don't need to as Tkinter figures out when 
> things have changed and updates itself, but 
> occasionally you may need to fo it manually.
> 

Or, if you mean to change the toplevel's size, use Toplevel.configure(width=..., height=...)

Michael

From dkuhlman at rexx.com  Tue Jan 16 18:55:27 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Tue, 16 Jan 2007 09:55:27 -0800
Subject: [Tutor] Array indexing
In-Reply-To: <b2a052580701160828g2ba0ee60w9eef307660168ac7@mail.gmail.com>
References: <b2a052580701160828g2ba0ee60w9eef307660168ac7@mail.gmail.com>
Message-ID: <20070116175527.GA60221@cutter.rexx.com>

On Tue, Jan 16, 2007 at 11:28:49AM -0500, Joe Abbey wrote:
> Hello,
> 
> I'm using Active Python v2.4.3.11 on a Windows XP machine.
> 
> Probably more relevant is that I'm just learning Python, as in I've been
> writing Python for less than 24 hours.
> 
> While trying to implement a PE parser, I ran into the following problem:
> 
> #************** START CODE*******************
> data = file.read(128);
> directoryTable = struct.unpack('LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', data);
> i=0;
> print "Export table           0x%08X + 0x%08x" % (directoryTable[i+=1],
> directoryTable[i+=1]);
> print "Import table           0x%08X + 0x%08x" % (directoryTable[i+=1],
> directoryTable[i+=1]);
> #************** END CODE*******************
> 
> This code throws a syntax error at the first i+=1 on "line 4".
> 
> Why is this the case?
> 

In Python, "i += 1" is a statement.  You have used in as an
expression.  In Python, an expression returns a value; a statement
does not.

> It seems like it would be very useful to be able to increment an index after
> referencing into an array.
> 

What you are asking for is viewed by some as useful.  But, I think
it is too confusing.  Should the variable be incremented before or
after it is used to index into the array?  C/C++ gives you a
choice: you can use either "i++" or "++i", which makes code harder
to read, I think.  And, what about:

    x = y[i+=1] + z[i]

Has the second use of "i" been incremented or not.

> Is my approach busted?  Is there a better way to reference elements?
> 

Instead of:

    x = directoryTable[i] + directoryTable[i+=1]);

use something like:

    x = directoryTable[i] + directoryTable[i+1]

And, by the way, you do not need all those semicolons at the end of
each line.  In Python, the semicolon is a statement separator, not
a statement terminator.  It is more Pythonic to use a semicolon
between statements only when there are more than one statement on a
line.  And writing more than one statement on a line is usually
discouraged anyway.

> The "fix" I'm currently using is to write the index I want:
> 
> (directoryTable[0], directoryTable[1])

Or, if you need an index variable:

    directoryTable[i], directoryTable[i+1])

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From carloslara at web.de  Tue Jan 16 19:05:03 2007
From: carloslara at web.de (Carlos)
Date: Tue, 16 Jan 2007 19:05:03 +0100
Subject: [Tutor] Clustering?
In-Reply-To: <6faf39c90701160735n2edde26am359cedc2dac57952@mail.gmail.com>
References: <mailman.60.1168945211.11058.tutor@python.org>	
	<45ACE2B1.3090509@web.de>
	<6faf39c90701160735n2edde26am359cedc2dac57952@mail.gmail.com>
Message-ID: <45AD13CF.5060902@web.de>


Hallo ,

Andre thanks a lot for your help, seems to me like  my script can work 
with your function.

I found this searching the internet:

cluster 1.1.1b2
python-cluster is a "simple" package that allows to create several 
groups (clusters) of objects from a list

>>> from cluster import *
>>> data = [12,34,23,32,46,96,13]
>>> cl = HierarchicalClustering(data, lambda x,y: abs(x-y))
>>> cl.getlevel(10)     # get clusters of items closer than 10
[96, 46, [12, 13, 23, 34, 32]]
>>> cl.getlevel(5)      # get clusters of items closer than 5
[96, 46, [12, 13], 23, [34, 32]]


I would like to give it a try because I have the impression that it can 
be helpful too. My problem now is the lambda function, I was wondering 
if someone could be so kind as to give me an example that could work in 
my list with nested tuples.

Thanks again!
Carlos



Andre Engels wrote:
> 2007/1/16, Carlos <carloslara at web.de <mailto:carloslara at web.de>>:
>
>     Hello to everybody,
>
>     I have a question that I think is a little related to clustering,
>     I have
>     a list of lists, like this:
>
>     List = [[1,5],[6,8],[48,10],[99,56]]
>
>     The list is composed by a large number of lists not just four, and
>     each
>     'interior' list contains two numbers that are the location of an
>     object
>     in a plane, so they are X and Y coordinates, my question is:
>
>     Can I use this list to evaluate how many points are in a given range?
>     Thats is taking the highest and lowest values for X an Y and, lets say
>     divide that range in 10 regions, then get the number of objects on
>     each
>     region. Is this possible? and if yes, how canI do it? I ask this
>     because
>     as you know my python skills are not that great :)
>
>
> First, this feels like a list of tuples rather than a list of lists; 
> however, tuples and lists don't differ that much in their behaviour, 
> so there's nothing really lost.
>
> And yes, it is possible. An inline if would be the way I would resolve 
> that:
>
> def withinrange(list,xmin,xmax,ymin,ymax):
>     # Get the elements of list for which the first part of the pair is 
> between xmin and xmax
>     # (inclusive) and the second between ymin and ymax.
>     return [c for c in list if xmin <= c[0] <= xmax and ymin <= c[1] 
> <= ymax]
>
> The longer but clearer method of doing the same would be:
>
> def withinrange(list,xmin,xmax,ymin,ymax):
>     templist = []
>     for c in list:
>         if xmin <= c[0] <= xmax and ymin <= c[1] <= ymax:
>             templist.append(c)
>     return templist
>
> -- 
> Andre Engels, andreengels at gmail.com <mailto:andreengels at gmail.com>
> ICQ: 6260644  --  Skype: a_engels
> ------------------------------------------------------------------------
>
> No virus found in this incoming message.
> Checked by AVG Free Edition.
> Version: 7.5.432 / Virus Database: 268.16.12/630 - Release Date: 1/15/2007 8:28 PM
>   


From joe.abbey at gmail.com  Tue Jan 16 19:29:38 2007
From: joe.abbey at gmail.com (Joe Abbey)
Date: Tue, 16 Jan 2007 13:29:38 -0500
Subject: [Tutor] Array indexing
In-Reply-To: <20070116175527.GA60221@cutter.rexx.com>
References: <b2a052580701160828g2ba0ee60w9eef307660168ac7@mail.gmail.com>
	<20070116175527.GA60221@cutter.rexx.com>
Message-ID: <b2a052580701161029h680e372fw1839bcd05f123834@mail.gmail.com>

On 1/16/07, Dave Kuhlman <dkuhlman at rexx.com> wrote:
>
> On Tue, Jan 16, 2007 at 11:28:49AM -0500, Joe Abbey wrote:
> > Hello,
> >
> > I'm using Active Python v2.4.3.11 on a Windows XP machine.
> >
> > Probably more relevant is that I'm just learning Python, as in I've been
> > writing Python for less than 24 hours.
> >
> > While trying to implement a PE parser, I ran into the following problem:
> >
> > #************** START CODE*******************
> > data = file.read(128);
> > directoryTable = struct.unpack('LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL',
> data);
> > i=0;
> > print "Export table           0x%08X + 0x%08x" % (directoryTable[i+=1],
> > directoryTable[i+=1]);
> > print "Import table           0x%08X + 0x%08x" % (directoryTable[i+=1],
> > directoryTable[i+=1]);
> > #************** END CODE*******************
> >
> > This code throws a syntax error at the first i+=1 on "line 4".
> >
> > Why is this the case?
> >
>
> In Python, "i += 1" is a statement.  You have used in as an
> expression.  In Python, an expression returns a value; a statement
> does not.
>
> > It seems like it would be very useful to be able to increment an index
> after
> > referencing into an array.
> >
>
> What you are asking for is viewed by some as useful.  But, I think
> it is too confusing.  Should the variable be incremented before or
> after it is used to index into the array?  C/C++ gives you a
> choice: you can use either "i++" or "++i", which makes code harder
> to read, I think.  And, what about:
>
>     x = y[i+=1] + z[i]
>
> Has the second use of "i" been incremented or not.
>
> > Is my approach busted?  Is there a better way to reference elements?
> >
>
> Instead of:
>
>     x = directoryTable[i] + directoryTable[i+=1]);
>
> use something like:
>
>     x = directoryTable[i] + directoryTable[i+1]
>
> And, by the way, you do not need all those semicolons at the end of
> each line.  In Python, the semicolon is a statement separator, not
> a statement terminator.  It is more Pythonic to use a semicolon
> between statements only when there are more than one statement on a
> line.  And writing more than one statement on a line is usually
> discouraged anyway.
>
> > The "fix" I'm currently using is to write the index I want:
> >
> > (directoryTable[0], directoryTable[1])
>
> Or, if you need an index variable:
>
>     directoryTable[i], directoryTable[i+1])
>
> Dave
>
>
> --
> Dave Kuhlman
> http://www.rexx.com/~dkuhlman
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


Thank you Danny for the iterator tutorial. I'll check the link.

Thanks Dave for the language lesson.  As you could tell from my code
snippet, C\C++ is what I have programmed the most in.

For this case I believe the iterator example would be most preferred.

#************** START CODE*******************
dTable = iterator(directoryTable)
print "Export table           0x%08X + 0x%08x" % (dTable.next(), dTable.next
())
#************** END CODE*******************

But for now the explicit indexing will work fine :)

Thanks!

Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070116/26e8ede5/attachment-0001.htm 

From carroll at tjc.com  Tue Jan 16 20:14:46 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 16 Jan 2007 11:14:46 -0800 (PST)
Subject: [Tutor] question about object oriented programming and
 inheritance using datetime module
In-Reply-To: <45AB6E22.7030503@tds.net>
Message-ID: <Pine.LNX.4.44.0701161035320.19717-100000@violet.rahul.net>

On Mon, 15 Jan 2007, Kent Johnson wrote:

> tpc at cryptic.com wrote:
> 
> > My class inherits from the date class, but I 
> > have to type 'from datetime import date' before I can initialize the 
> > class definition.  Is there some way to avoid this ? 
> 
> No, and really there is no reason to want to avoid this. You have to 
> import any external module that you want to use directly. Imports are 
> very common in Python code and there is no reason not to use them.

I had a similar issue when I started Python, so I think I know what tpc
may be after.

My thought was that I did not want to do the import if the class was not 
actually going to be used.

I was really thinking about it the wrong way, though.  Really, I would not 
want to do the import unless the class was going to be *defined* for use.  
The right approach here is to put the class into a module, and the import 
statement into the new module as well.

Then, a program that needs to use the class imports the module; and that 
module, only if it is imported, imports the classes on which it depends.

In this case, tpc's class might be defined in a MyDateStuff.py module,
which contains:



################
import datetime

class age_calculator(datetime.date):
   etc.

################

Then, when he imports MyDateStuff, it imports datetime and defines 
age_calculator.

I second Kent's concerns over this, though.  It sounds like age_calculator
is really a method that uses datetime.date; not a subclass of
datetime.date.

The question you should ask is: will an age_calculator object actually 
also be a date object?  If so, subclassing makes sense.  Otherwise, think 
of using a method.

Put another way, you should think of a statement like 

   class age_calculator(datetime.date):

as meaning "define a new class named age_calculator; an age_calculator
object is a type of date object."

An example is if you wanted to create a "birthdate" class, which was just 
like a regular date, but also included the birthstone that corresponded to 
the date.  We could create a "birthdate" module that included a 
"Birthdate" class:

###############

import datetime

class Birthdate(datetime.date):

    def __init__(self, year, month, day):
        stones = ["Garnet", "Amethyst", "Aquamarine",
          "Diamond", "Emerald", "Perl",
          "Ruby", "Python", "Sapphire",
          "Opal", "Topaz", "Turquoise"]
        self.birthstone = stones[month-1]

###############

We could create a Birthdate object like this:

>>> import birthdate
>>> z = birthdate.Birthdate(1971, 7, 12)

Note, it has the birthstone for July:

>>> z.birthstone
'Ruby'

It also has inherited the other attributes and methods of the standard
datetime.date class on which it was based:

>>> z.isoformat()
'1971-07-12'

Because a birthdate is after all, just a particular kind of date; and the 
Birthdate class is just a particular kind of date class.

But in your case, with a name like "age_calculator", it doesn't sound like 
an "age_calculator" is a kind of date.  It sounds like a thing that 
calculates ages.


From kent37 at tds.net  Tue Jan 16 20:53:25 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 16 Jan 2007 14:53:25 -0500
Subject: [Tutor] question about object oriented programming and
 inheritance using datetime module
In-Reply-To: <Pine.LNX.4.44.0701161035320.19717-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0701161035320.19717-100000@violet.rahul.net>
Message-ID: <45AD2D35.7050805@tds.net>

Terry Carroll wrote:
> An example is if you wanted to create a "birthdate" class, which was just 
> like a regular date, but also included the birthstone that corresponded to 
> the date.  We could create a "birthdate" module that included a 
> "Birthdate" class:
> 
> ###############
> 
> import datetime
> 
> class Birthdate(datetime.date):
> 
>     def __init__(self, year, month, day):
>         stones = ["Garnet", "Amethyst", "Aquamarine",
>           "Diamond", "Emerald", "Perl",
>           "Ruby", "Python", "Sapphire",
>           "Opal", "Topaz", "Turquoise"]
>         self.birthstone = stones[month-1]

I think you are missing the line
   datetime.date.__init__(self, year, month, day)

somewhere in here.

I am very surprised that this works, my understanding was that 
datetime.date was immutable and required overriding __new__() rather 
than __init__(). But it does work...

Kent


From rdm at rcblue.com  Tue Jan 16 20:53:22 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 16 Jan 2007 11:53:22 -0800
Subject: [Tutor] How to convert a long decimal into a string?
Message-ID: <7.0.1.0.2.20070116112235.03ac4668@rcblue.com>

Here's a function I wrote some time ago, and just discovered that in 
one important category of cases, long numbers with a decimal point, 
it doesn't do what I intended.

=====================================================
def numberRounding(n, significantDigits=4):
	"""
	Rounds a number (float or integer, negative or positive) to any number of
	significant digits. If an integer, there is no limitation on it's size.
	"""
	import decimal
	def d(x):
		return decimal.Decimal(str(x))
	decimal.getcontext().prec = significantDigits
	return d(n)/1
======================================================

Now, print 
numberRounding(232.3452345230987987098709879087098709870987098745234, 
30) prints
232.345234523

whereas if the first argument is enclosed in quotes, it does what I 
indended. Thus:
print 
numberRounding('232.3452345230987987098709879087098709870987098745234', 
30) prints
232.345234523098798709870987909 .

So my question is, how can I revise numberRounding() so that it is 
not necessary to employ the quotes. Or alternatively, is there a way 
to non-manually put quotes around an argument that is a long decimal? 
If have no idea at all about the second. As for the first, I believe 
I could devise an algorithm for first converting n to an int (for 
example, multiplying the above n by 1000), converting to a string, 
putting the decimal point back in between indices 2 and 3, then using 
that string as n (thereby avoiding the use of quotes around n as the 
first argument). But I have the feeling that Python must have a way 
already built in. Does it?

Thanks,

Dick Moores


From kent37 at tds.net  Tue Jan 16 21:16:07 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 16 Jan 2007 15:16:07 -0500
Subject: [Tutor] How to convert a long decimal into a string?
In-Reply-To: <7.0.1.0.2.20070116112235.03ac4668@rcblue.com>
References: <7.0.1.0.2.20070116112235.03ac4668@rcblue.com>
Message-ID: <45AD3287.6010101@tds.net>

Dick Moores wrote:
> Here's a function I wrote some time ago, and just discovered that in 
> one important category of cases, long numbers with a decimal point, 
> it doesn't do what I intended.
> 
> =====================================================
> def numberRounding(n, significantDigits=4):
> 	"""
> 	Rounds a number (float or integer, negative or positive) to any number of
> 	significant digits. If an integer, there is no limitation on it's size.
> 	"""
> 	import decimal
> 	def d(x):
> 		return decimal.Decimal(str(x))
> 	decimal.getcontext().prec = significantDigits
> 	return d(n)/1
> ======================================================
> 
> Now, print 
> numberRounding(232.3452345230987987098709879087098709870987098745234, 
> 30) prints
> 232.345234523

The problem is that 
232.3452345230987987098709879087098709870987098745234 is a float which 
cannot represent this number exactly. Just typing it at the interpreter 
prompt shows the problem:
 >>> 232.3452345230987987098709879087098709870987098745234
232.34523452309881
 >>> str(_)
'232.345234523'

So the precision you want is lost immediately when the constant is created.
> 
> whereas if the first argument is enclosed in quotes, it does what I 
> indended. Thus:
> print 
> numberRounding('232.3452345230987987098709879087098709870987098745234', 
> 30) prints
> 232.345234523098798709870987909 .
> 
> So my question is, how can I revise numberRounding() so that it is 
> not necessary to employ the quotes. 

You can't. A float simply can't represent the number you want and the 
function has no way to access the textual representation of the number.

 > Or alternatively, is there a way
> to non-manually put quotes around an argument that is a long decimal? 
No

Kent


From rdm at rcblue.com  Tue Jan 16 21:28:26 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 16 Jan 2007 12:28:26 -0800
Subject: [Tutor] How to convert a long decimal into a string?
In-Reply-To: <45AD3287.6010101@tds.net>
References: <7.0.1.0.2.20070116112235.03ac4668@rcblue.com>
	<45AD3287.6010101@tds.net>
Message-ID: <7.0.1.0.2.20070116122645.067fcb98@rcblue.com>

At 12:16 PM 1/16/2007, Kent Johnson wrote:
>Dick Moores wrote:
> > Here's a function I wrote some time ago, and just discovered that in
> > one important category of cases, long numbers with a decimal point,
> > it doesn't do what I intended.
> >
> > =====================================================
> > def numberRounding(n, significantDigits=4):
> >       """
> >       Rounds a number (float or integer, negative or positive) to 
> any number of
> >       significant digits. If an integer, there is no limitation 
> on it's size.
> >       """
> >       import decimal
> >       def d(x):
> >               return decimal.Decimal(str(x))
> >       decimal.getcontext().prec = significantDigits
> >       return d(n)/1
> > ======================================================
> >
> > Now, print
> > numberRounding(232.3452345230987987098709879087098709870987098745234,
> > 30) prints
> > 232.345234523
>
>The problem is that
>232.3452345230987987098709879087098709870987098745234 is a float which
>cannot represent this number exactly. Just typing it at the interpreter
>prompt shows the problem:
>  >>> 232.3452345230987987098709879087098709870987098745234
>232.34523452309881
>  >>> str(_)
>'232.345234523'
>
>So the precision you want is lost immediately when the constant is created.
> >
> > whereas if the first argument is enclosed in quotes, it does what I
> > indended. Thus:
> > print
> > numberRounding('232.3452345230987987098709879087098709870987098745234',
> > 30) prints
> > 232.345234523098798709870987909 .
> >
> > So my question is, how can I revise numberRounding() so that it is
> > not necessary to employ the quotes.
>
>You can't. A float simply can't represent the number you want and the
>function has no way to access the textual representation of the number.
>
>  > Or alternatively, is there a way
> > to non-manually put quotes around an argument that is a long decimal?
>No

Thanks, Kent. So I go with working up "an algorithm for first 
converting n to an int (for
example, multiplying the above n by 1000), converting to a string,
putting the decimal point back in between indices 2 and 3, then using
that string as n (thereby avoiding the use of quotes around n as the
first argument)."

Dick


>Kent
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



From carroll at tjc.com  Tue Jan 16 21:40:43 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 16 Jan 2007 12:40:43 -0800 (PST)
Subject: [Tutor] How to convert a long decimal into a string?
In-Reply-To: <7.0.1.0.2.20070116112235.03ac4668@rcblue.com>
Message-ID: <Pine.LNX.4.44.0701161234240.19717-100000@violet.rahul.net>

On Tue, 16 Jan 2007, Dick Moores wrote:

> Here's a function I wrote some time ago, and just discovered that in 
> one important category of cases, long numbers with a decimal point, 
> it doesn't do what I intended.
> 
> =====================================================
> def numberRounding(n, significantDigits=4):
> 	"""
> 	Rounds a number (float or integer, negative or positive) to any number of
> 	significant digits. If an integer, there is no limitation on it's size.
> 	"""
> 	import decimal
> 	def d(x):
> 		return decimal.Decimal(str(x))
> 	decimal.getcontext().prec = significantDigits
> 	return d(n)/1
> ======================================================
> 
> Now, print 
> numberRounding(232.3452345230987987098709879087098709870987098745234, 
> 30) prints
> 232.345234523
> 
> whereas if the first argument is enclosed in quotes, it does what I 
> indended. Thus:
> print 
> numberRounding('232.3452345230987987098709879087098709870987098745234', 
> 30) prints
> 232.345234523098798709870987909 .
> 
> So my question is, how can I revise numberRounding() so that it is 
> not necessary to employ the quotes.

I'm guessing that you can't.

When you do:

numberRounding(232.3452345230987987098709879087098709870987098745234,30)

you are calling numberRounding with a first argument of a floating point,
whose value is set from
232.3452345230987987098709879087098709870987098745234, but is going to be 
cut down immediately to the amount of precision that you have on your 
machine.  For me, that's 232.34523452309881, well short of 30.

So it's the same as calling:

numberRounding(232.34523452309881,30)

By the time your function gets control, you're already down to the 
less-precise value.

That's probably why a direct decimal conversion from float is not allowed,
to avoid the illusion of more precision than there really is.



From kent37 at tds.net  Tue Jan 16 21:45:01 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 16 Jan 2007 15:45:01 -0500
Subject: [Tutor] How to convert a long decimal into a string?
In-Reply-To: <7.0.1.0.2.20070116122645.067fcb98@rcblue.com>
References: <7.0.1.0.2.20070116112235.03ac4668@rcblue.com>
	<45AD3287.6010101@tds.net>
	<7.0.1.0.2.20070116122645.067fcb98@rcblue.com>
Message-ID: <45AD394D.20608@tds.net>

Dick Moores wrote:
> Thanks, Kent. So I go with working up "an algorithm for first 
> converting n to an int (for
> example, multiplying the above n by 1000), converting to a string,
> putting the decimal point back in between indices 2 and 3, then using
> that string as n (thereby avoiding the use of quotes around n as the
> first argument)."

I really don't know what you mean by this. You are lost as soon as you 
write 232.3452345230987987098709879087098709870987098745234 without 
quotes, there is no float literal with that value.

You could pass the integer 
2323452345230987987098709879087098709870987098745234
as the argument if you always have the implied decimal point in the same 
place.

Kent


From python at venix.com  Tue Jan 16 21:47:04 2007
From: python at venix.com (Python)
Date: Tue, 16 Jan 2007 15:47:04 -0500
Subject: [Tutor] How to convert a long decimal into a string?
In-Reply-To: <7.0.1.0.2.20070116122645.067fcb98@rcblue.com>
References: <7.0.1.0.2.20070116112235.03ac4668@rcblue.com>
	<45AD3287.6010101@tds.net>
	<7.0.1.0.2.20070116122645.067fcb98@rcblue.com>
Message-ID: <1168980424.27224.184.camel@www.venix.com>

On Tue, 2007-01-16 at 12:28 -0800, Dick Moores wrote:
> So I go with working up "an algorithm for first 
> converting n to an int (for
> example, multiplying the above n by 1000), converting to a string,
> putting the decimal point back in between indices 2 and 3, then using
> that string as n (thereby avoiding the use of quotes around n as the
> first argument)." 

This seems like a lot of effort for not much reward.  Where is n coming
from?  If you already have something that holds the required level of
precision, why does it need to be transformed?  Could it already be a
string?  If n is entered through raw_input, then you received it as a
string.

I don't want to push you in the wrong direction, but it seems like there
must be a better way.

-- 
Lloyd Kvam
Venix Corp


From rdm at rcblue.com  Tue Jan 16 22:57:47 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 16 Jan 2007 13:57:47 -0800
Subject: [Tutor] How to convert a long decimal into a string?
In-Reply-To: <1168980424.27224.184.camel@www.venix.com>
References: <7.0.1.0.2.20070116112235.03ac4668@rcblue.com>
	<45AD3287.6010101@tds.net>
	<7.0.1.0.2.20070116122645.067fcb98@rcblue.com>
	<1168980424.27224.184.camel@www.venix.com>
Message-ID: <7.0.1.0.2.20070116133743.07ab0968@rcblue.com>

At 12:47 PM 1/16/2007, you wrote:
>On Tue, 2007-01-16 at 12:28 -0800, Dick Moores wrote:
> > So I go with working up "an algorithm for first
> > converting n to an int (for
> > example, multiplying the above n by 1000), converting to a string,
> > putting the decimal point back in between indices 2 and 3, then using
> > that string as n (thereby avoiding the use of quotes around n as the
> > first argument)."
>
>This seems like a lot of effort for not much reward.  Where is n coming
>from?  If you already have something that holds the required level of
>precision, why does it need to be transformed?  Could it already be a
>string?  If n is entered through raw_input, then you received it as a
>string.
>
>I don't want to push you in the wrong direction, but it seems like there
>must be a better way.

LLoyd, Yes, that's right, isn't it. And functions I would use that 
feed into numberRounding() would be things such as my decPow(), which 
returns a string:   (All corrective comments on it are welcome!)
==============================
def decPow(n, power, precision=40):
         """
         Raise any number n (as a string) to any integral power,
         to any degree of precision.
         """
         import decimal
         def d(x):
                 return decimal.Decimal(str(x))

         if power == 0:
                 return 1
         elif power > 0:
                 decimal.getcontext().prec = precision
                 product = d(n)
                 for k in range(1,power):
                         product = product * d(n)
                 return product
         elif power < 0:
                 decimal.getcontext().prec = precision
                 quotient = 1/d(n)
                 for k in range(1, -(power)):
                         quotient = quotient / d(n)
                 return quotient
================================

Still, I'd like to see if can write that algorithm. ;)

Thanks very much,

Dick




From pytutor.20.247ob at spamgourmet.com  Tue Jan 16 23:08:07 2007
From: pytutor.20.247ob at spamgourmet.com (pytutor.20.247ob at spamgourmet.com)
Date: Tue, 16 Jan 2007 22:08:07 +0000 (GMT)
Subject: [Tutor] Subprocess popen problem depending on how I start program
Message-ID: <20070116220807.72165.qmail@web23408.mail.ird.yahoo.com>

Hi,
I'm writing a program that downloads audio streams from the net, to do
this I use mplayer and tcpdump, which I kick off as detached processes
(if thats the correct terminology), I do it this way because i'm using
pygtk and I dont want the program to wait for the processes to finish
otherwise the app would appear to freeze.
I have written 2 modules, one contains a class and methods that do all
the work, the other is the gui module, I've got it working fairly well
at least when I start the program from within a bash shell (Im using
Ubuntu Linux BTW) The modules both have a line '#!/usr/bin/env python'
at the top and are set as executable too so I can run them from a bash
shell.
Now I have one eye on distributing the modules in the future I'm
thinking how people will start the app, and I discover that if I use
the 'run application' program (alt F2 in most linux's I think) to call
the module it starts ok and works normally until I attempt to use the
part that starts the subprocess in the background, it just does not
work and the gui continues to respond as if nothing ever happened. When
I check the processes running I can see that it has not started a sub
shell to run the command. also tried other things like creating an
application launcher, this will work if I tick 'run in terminal' but
not otherwise.
I've also started learning about distutils and installed the modules on
my system using it, then created a python script (made it executable)
and tried using this to start the program, same problem.

I'm scratching around trying to find an answer but I'm at a loss now so
would sure appreciate some help, thanks.

Wayne..
ps. sorry if it's wordy, I want to give enough info. if you need
anymore info just say.


	
	
		
___________________________________________________________ 
New Yahoo! Mail is the ultimate force in competitive emailing. Find out more at the Yahoo! Mail Championships. Plus: play games and win prizes. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 

From tsila.hassine at gmail.com  Tue Jan 16 23:51:00 2007
From: tsila.hassine at gmail.com (Tsila Hassine)
Date: Tue, 16 Jan 2007 23:51:00 +0100
Subject: [Tutor] dealing with 406 HTTP response
Message-ID: <da5291e90701161451xf44cfc9x64942e17866d9781@mail.gmail.com>

Dear pythoners,

has anybody dealt with a 406 reponse through  a urllib.FancyURLopener class
?
I have a code that downloads images from websites and soemsites respond with
an 406 which I don't know how to handle

thanks!
Tsila
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070116/52085d56/attachment.htm 

From alan.gauld at btinternet.com  Wed Jan 17 00:28:14 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 16 Jan 2007 23:28:14 -0000
Subject: [Tutor] Clustering?
References: <mailman.60.1168945211.11058.tutor@python.org>	<45ACE2B1.3090509@web.de><6faf39c90701160735n2edde26am359cedc2dac57952@mail.gmail.com>
	<45AD13CF.5060902@web.de>
Message-ID: <eojn2g$vd3$1@sea.gmane.org>


"Carlos" <carloslara at web.de> wrote

>>> from cluster import *
>>> data = [12,34,23,32,46,96,13]
>>> cl = HierarchicalClustering(data, lambda x,y: abs(x-y))
>>> cl.getlevel(10)     # get clusters of items closer than 10
 [96, 46, [12, 13, 23, 34, 32]]

> I would like to give it a try because I have the impression that it 
> can
> be helpful too. My problem now is the lambda function, I was 
> wondering
> if someone could be so kind as to give me an example that could work 
> in
> my list with nested tuples.

lambda is just a shorthand way of writing a simple function.
You don't need to use lambda. The above line could have
been done thisaway:

>>> def f(x,y): return abs(x-y)
>>> cl = HierarchicalClustering(data, f)

So provided you can write a function to do what you want you
don't need the lambda if it confuses you.

In a general sense:

def f(p): return expression

is the same as

f = lambda p: expression

So anywhere that a function name is nmeeded you can
put a lambda.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From dyoo at hkn.eecs.berkeley.edu  Wed Jan 17 00:52:50 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 16 Jan 2007 15:52:50 -0800 (PST)
Subject: [Tutor] dealing with 406 HTTP response
In-Reply-To: <da5291e90701161451xf44cfc9x64942e17866d9781@mail.gmail.com>
References: <da5291e90701161451xf44cfc9x64942e17866d9781@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0701161535300.4975@hkn.eecs.berkeley.edu>



On Tue, 16 Jan 2007, Tsila Hassine wrote:

> has anybody dealt with a 406 reponse through a urllib.FancyURLopener 
> class ? I have a code that downloads images from websites and soemsites 
> respond with an 406 which I don't know how to handle

Hi Tsila,

Have you looked at the description of a 406 error?

     http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

What's going on is that FancyURLOpener doesn't specify the types it can 
accept, so by default, the types of things are quite limited.


You'll want to look into the addheader() method of your FancyURLOpener to 
reassure the web server that you will accept anything from them, by adding 
a permissive Accept: header.  For example:

     opener.addheader('Accept', '*/*')

should add a 'Accept:' header that eats everything.


But for some reason, it appears that this method isn't documented in the 
Standard Library!

    http://www.python.org/doc/lib/urlopener-objs.html

does anyone know what's going on there?  Documentation on addheader can be 
found here:

http://pydoc.org/2.4.1/urllib.html#FancyURLopener-addheader

but the method should really be included in the API docs.

I'll send a ping to the Documentation folks and see if this will be 
amended.


Good luck!

From rdm at rcblue.com  Wed Jan 17 02:09:24 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 16 Jan 2007 17:09:24 -0800
Subject: [Tutor] How to convert a long decimal into a string?
Message-ID: <7.0.1.0.2.20070116170813.0385ed60@rcblue.com>

At 12:45 PM 1/16/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>Thanks, Kent. So I go with working up "an algorithm for first 
>>converting n to an int (for
>>example, multiplying the above n by 1000), converting to a string,
>>putting the decimal point back in between indices 2 and 3, then using
>>that string as n (thereby avoiding the use of quotes around n as the
>>first argument)."
>
>I really don't know what you mean by this. You are lost as soon as 
>you write 232.3452345230987987098709879087098709870987098745234 
>without quotes, there is no float literal with that value.
>
>You could pass the integer 
>2323452345230987987098709879087098709870987098745234
>as the argument if you always have the implied decimal point in the 
>same place.

You're right, of course. As usual. Just one of those "You can't get 
there from here" things. But I don't really need to, as Lloyd pointed out.

Thanks,

Dick





From dyoo at hkn.eecs.berkeley.edu  Wed Jan 17 02:18:25 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 16 Jan 2007 17:18:25 -0800 (PST)
Subject: [Tutor] dealing with 406 HTTP response (fwd)
Message-ID: <Pine.LNX.4.64.0701161718140.10579@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Wed, 17 Jan 2007 02:08:48 +0100
From: Tsila Hassine <tsila.hassine at gmail.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] dealing with 406 HTTP response

Danny - thanks! it works though I am not sure I fully understand what i did
:-)

I am iverriding teh opener class with my fancy one, then creatign an opener
instance of it, and then i am specifying the addheader method you mentioned.
is that the right way to do it (well - it works) - and what did i just do in
terms of class overriding ?

thanks a lot for your help!
Tsila

On 1/17/07, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
>
> On Tue, 16 Jan 2007, Tsila Hassine wrote:
>
>> has anybody dealt with a 406 reponse through a urllib.FancyURLopener
>> class ? I have a code that downloads images from websites and soemsites
>> respond with an 406 which I don't know how to handle
>
> Hi Tsila,
>
> Have you looked at the description of a 406 error?
>
>      http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
>
> What's going on is that FancyURLOpener doesn't specify the types it can
> accept, so by default, the types of things are quite limited.
>
>
> You'll want to look into the addheader() method of your FancyURLOpener to
> reassure the web server that you will accept anything from them, by adding
> a permissive Accept: header.  For example:
>
>      opener.addheader('Accept', '*/*')
>
> should add a 'Accept:' header that eats everything.
>
>
> But for some reason, it appears that this method isn't documented in the
> Standard Library!
>
>     http://www.python.org/doc/lib/urlopener-objs.html
>
> does anyone know what's going on there?  Documentation on addheader can be
> found here:
>
> http://pydoc.org/2.4.1/urllib.html#FancyURLopener-addheader
>
> but the method should really be included in the API docs.
>
> I'll send a ping to the Documentation folks and see if this will be
> amended.
>
>
> Good luck!
>

From carroll at tjc.com  Wed Jan 17 02:32:50 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 16 Jan 2007 17:32:50 -0800 (PST)
Subject: [Tutor] mutability, __new__
In-Reply-To: <45AD2D35.7050805@tds.net>
Message-ID: <Pine.LNX.4.44.0701161726110.27231-100000@violet.rahul.net>

[hijacking the "question about object oriented programming and 
inheritance using datetime module" thread here....]

On Tue, 16 Jan 2007, Kent Johnson wrote:

> I think you are missing the line
>    datetime.date.__init__(self, year, month, day)
> somewhere in here.

Yeah; sloppy of me.

> I am very surprised that this works, my understanding was that 
> datetime.date was immutable and required overriding __new__() rather 
> than __init__(). But it does work...

Yeah, come to think of it, that is interesting.

A quick test shows that datetime.date is apparently immutable, because it 
can be used as a dictionary key.

But if it's immutable, then __init__ shouldn't work, and, as you say, you 
gotta go with __new__.

I have to admit, I don't completely comprehend the use of __new__, but the 
discussion at http://www.python.org/download/releases/2.2.3/descrintro/ 
explained quite a lot.

How can you find if a particular object is immutable or not?  Or, 
relatedly, if you wanted to define an object that was immutable, how would 
you do it?


From dyoo at hkn.eecs.berkeley.edu  Wed Jan 17 03:27:31 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 16 Jan 2007 18:27:31 -0800 (PST)
Subject: [Tutor] dealing with 406 HTTP response (fwd)
In-Reply-To: <Pine.LNX.4.64.0701161718140.10579@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0701161718140.10579@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.64.0701161812070.1684@hkn.eecs.berkeley.edu>

> Danny - thanks! it works though I am not sure I fully understand what i 
> did :-)


Hi Tsila,

When you have time, you may want to take a closer look at how HTTP works. 
Here's one place you can look:

     http://www.jmarshall.com/easy/http/

If you are writing applications for HTTP, you should have a good idea of 
basic fundamentals.  Otherwise, your code may look weird.


> I am iverriding teh opener class with my fancy one, then creatign an 
> opener instance of it, and then i am specifying the addheader method you 
> mentioned. is that the right way to do it (well - it works) - and what 
> did i just do in terms of class overriding ?

Without seeing what you're doing in terms of code, I can't say anything 
really concrete.  I do not know what you mean by "overriding", because I 
don't know what your understanding is.  In other words, I don't know if 
we've come to terms yet.  Show the group the code you've written, and we 
can continue from there.


(I hesitate to say anything because what you're saying about class 
overriding sorta sounds like you've done inheritance, but other things 
that you say aren't meshing with what I'm expecting.  Better to see what's 
actually happening rather than take a guess...)


By the way, when you reply to messages on Tutor, please use your email 
client's "Reply to All" feature.  It'll keep the rest of the group in the 
loop and give others the chance to respond.

From vgvr620034 at gmail.com  Wed Jan 17 07:57:27 2007
From: vgvr620034 at gmail.com (raghu raghu)
Date: Wed, 17 Jan 2007 12:27:27 +0530
Subject: [Tutor] Difference between 'yield' and 'print'
Message-ID: <bedebdfb0701162257w567d8d8jcbb3c790c877dc01@mail.gmail.com>

Is there any difference between yield and print in python script?i have
written a script based on fibonacci series where in i used yield and print
in two different scripts:
the script is given below:
def fib(n):
    a,b = 0,1
    while a<=n:
       print a
       a,b = b,a+b

for x in fib(4):
    print  x. When i executed this script i am getting this error:
Typeerror:"nonetype" is not iterable
But the same script if 'print' is replaced with 'yield' inside while loop it
is executing properly without any type errors
could any one reply why print cant be used instead of yield and why error is
generated?

-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070117/796957ce/attachment.html 

From rabidpoobear at gmail.com  Wed Jan 17 09:04:12 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 17 Jan 2007 02:04:12 -0600
Subject: [Tutor] Difference between 'yield' and 'print'
In-Reply-To: <bedebdfb0701162257w567d8d8jcbb3c790c877dc01@mail.gmail.com>
References: <bedebdfb0701162257w567d8d8jcbb3c790c877dc01@mail.gmail.com>
Message-ID: <45ADD87C.7060205@gmail.com>

raghu raghu wrote:
> Is there any difference between yield and print in python script?i 
> have written a script based on fibonacci series where in i used yield 
> and print in two different scripts:
> the script is given below:
> def fib(n):
>     a,b = 0,1
>     while a<=n:
>        print a
>        a,b = b,a+b
>       
> for x in fib(4):
>     print  x. When i executed this script i am getting this error: 
> Typeerror:"nonetype" is not iterable
> But the same script if 'print' is replaced with 'yield' inside while 
> loop it is executing properly without any type errors
> could any one reply why print cant be used instead of yield and why 
> error is generated?


the version of the function you created, fib(n) with the print, takes an 
argument 'n' and outputs the fibonacci sequence.
It does not return anything.

'for x in fib(4):'
is equivalent to saying:
'for x in none:'
which doesn't work because you can't iterate over nothing.



Refer to http://docs.python.org/ref/yield.html for information about yield.
Disclaimer: The following information I'm going to present you I came up 
with after reading that short explanation of 'yield' so it may not be 
exactly correct.
Also, I didn't check any code samples to see if they executed correctly.  :)


The reason the script works with 'yield' is because the fib(n) function 
then becomes a generator function.
The way I understand it (I don't know that much about generators)

By saying

def some_function(n):
    a = 0
    while a <= n:
       yield a
       a += 1

and looping over (what you'd think would be ) the returned value of the 
function call
for x in some_function(5):
    print x

what's really happening is that, the first time the loop is run,
the body of some_function is executed, until it gets to the first 
'yield' statement.
this value is then yielded ('returned' in a sense) but the function 
object is not destroyed.
The yielded value is assigned to x.  after the body of the for loop 
executes,
the function object is resumed at the first 'yield'.
It's the same for every case, where it resumes execution at the last 
'yield' until there are no more values to yield.


So the first time through the 'for' loop,
a is set to 0
the inner while loop starts, a is < 5.
the value 0 is returned and bound to x
we print x

now the for loop starts over, some_function is resumed at where the 
'yield' was,
a is incremented, it's now 1
1 < 5, while loop starts again, the value of a (1) is returned.
etc, etc, etc.

until:
the for loop starts over, some_function is resumed where the 'yield' was,
a is incremented, it's now 6.
while loop repeats, a is not < n, the function ends, not returning a value.

so the end result is
012345

The basic idea, i think, is calling 'some_function(5)' creates a 
generator object (an instance of some 'generator' class?)
which has a method called next().

So you could think of the loop like this:
gen = some_function(5) #create the generator
while 1:
    try:
       print gen.next()
    except: #we ran out of things to generate (the generator stopped 
yielding results -- supposedly it raises an error here?)
       print "End of generator."
       break

Anyway, I've never used them but that sounds like a reasonable way for 
them to work.
If you'd like a better explanation you might poke around Alan Gauld's 
tutorial, he probably has a section on generators.

HTH,
-Luke

From andreengels at gmail.com  Wed Jan 17 10:21:57 2007
From: andreengels at gmail.com (Andre Engels)
Date: Wed, 17 Jan 2007 10:21:57 +0100
Subject: [Tutor] possible import locations
Message-ID: <6faf39c90701170121o6d108cc1m8cbb49b180dcf7ee@mail.gmail.com>

Is it possible to see from a python program where it searches for possible
imports? Is it possible to import from another location than those? (Of
course with an "if so, how" attached).

The issue is that the company I work for is switching providers. With the
old provider (as well as in my local setting), Python automatically searched
for imports in the current directory (the one where the program was run).
With the new one, this does not seem to be the case, so I am getting
ImportErrors all over the place.

-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070117/a696a514/attachment.htm 

From zebra05 at gmail.com  Wed Jan 17 11:58:47 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Wed, 17 Jan 2007 12:58:47 +0200
Subject: [Tutor] Perfect Python web stack?
Message-ID: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>

Ok pythonistas!

Please help me to decide. I might have asked some of you before, so please
bear with me.

I want to build a database driven python web app and i need to decide, so
please vote on the best components (im developing on XP SP2):

1) MySQL vs PostGRES
2) Lighttpd + FastCGI vs Apache + mod_python
3) Pylons + Cheetah + Kid/Mochikit/Dojo vs Django/Turbogears

This is not to light fires, its for my sole information :-)

Thanks in advance, gurus.

"Shortash"

-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070117/d6b24ce3/attachment.html 

From kent37 at tds.net  Wed Jan 17 12:00:24 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 17 Jan 2007 06:00:24 -0500
Subject: [Tutor] Difference between 'yield' and 'print'
In-Reply-To: <45ADD87C.7060205@gmail.com>
References: <bedebdfb0701162257w567d8d8jcbb3c790c877dc01@mail.gmail.com>
	<45ADD87C.7060205@gmail.com>
Message-ID: <45AE01C8.7090904@tds.net>

Luke Paireepinart wrote:

> Refer to http://docs.python.org/ref/yield.html for information about yield.
> Disclaimer: The following information I'm going to present you I came up 
> with after reading that short explanation of 'yield' so it may not be 
> exactly correct.

There is a longer explanation here:
http://www.python.org/doc/2.2.3/whatsnew/node5.html

> So you could think of the loop like this:
> gen = some_function(5) #create the generator
> while 1:
>     try:
>        print gen.next()
>     except: #we ran out of things to generate (the generator stopped 
> yielding results -- supposedly it raises an error here?)
>        print "End of generator."
>        break
> 
> Anyway, I've never used them but that sounds like a reasonable way for 
> them to work.

Yes, that is pretty much what is going on. The generatory will raise 
StopIteration when there are no more values.

Kent



From thomas.coopman at gmail.com  Wed Jan 17 13:57:01 2007
From: thomas.coopman at gmail.com (thomas coopman)
Date: Wed, 17 Jan 2007 13:57:01 +0100
Subject: [Tutor] import and unittest
In-Reply-To: <eoi83f$kj5$1@sea.gmane.org>
References: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>
	<eoi83f$kj5$1@sea.gmane.org>
Message-ID: <20070117135701.5e1b2c72@localhost>

On Tue, 16 Jan 2007 10:06:37 -0000
"Alan Gauld" <alan.gauld at btinternet.com> wrote:

> 
> "Thomas Coopman" <thomas.coopman at gmail.com> wrote
> .
> > I wondered if it was possible to do something like this:
> >
> > src/
> >    -a_module/
> >        -sub_module/
> > test/
> >    -a_module/
> >        -sub_module/
> >
> 
> I don;t see any reason why not although its slightly more work.
> Personally I tend to keep the tests with the code, but thats
> mainly because tools such as editors tend to remember the last
> folder opened and its a pain navigating between the two folders.
> 
> The other system I have used(in C++ not Python) is to have
> a test folder inside each src folder like:
> 
> src/
>    mod1/
>        f1.py
>        test/
>           testf1.py
>     mod2/
>        f2.py
>        f3.py
>        test/
>            testf1.py
>            testf2.py
> 
> etc.
> 
> This minimises navigation and keeps the tests separate.
> Its also relatively easy to filter out the tests when it comes
> time to package upp the code for distribution (assuming
> you want to lose them!)
> 
> > I have something like this but I don't know how to organize the 
> > imports in
> > the tests and I don't know if this is a good idea.  What do you 
> > think?
> 
> I think in Python you should create a package structure for
> your code so that import can find the modules more easily.
> But I've never tried this in Python, my Python projects are rarely
> big enough to warrant it.
> 
> 

well, I still have problems with import

suppose I have something like this:

M/
  __init__.py
  A/
    __init__.py
    One.py
  B/
    __init__.py
    Two.py

One.py
    #!/usr/bin/python

    from M.B import Two

Two.py
    #!/usr/bin/python

    from M.A import One


when I try to run One.py or Two.py I get import errors and I don't know
how to fix them.  I tried to set the __all__ variable in the __init__
files but nothing worked so far.

I would like to run the files from anywhere for example.
What am I doing wrong?
I read the information about modules on python.org
(http://www.python.org/doc/2.0.1/tut/node8.html) but I don't find a
solution

Thanks

From kent37 at tds.net  Wed Jan 17 12:07:19 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 17 Jan 2007 06:07:19 -0500
Subject: [Tutor] possible import locations
In-Reply-To: <6faf39c90701170121o6d108cc1m8cbb49b180dcf7ee@mail.gmail.com>
References: <6faf39c90701170121o6d108cc1m8cbb49b180dcf7ee@mail.gmail.com>
Message-ID: <45AE0367.5050105@tds.net>

Andre Engels wrote:
> Is it possible to see from a python program where it searches for 
> possible imports? Is it possible to import from another location than 
> those? (Of course with an "if so, how" attached).
> 
> The issue is that the company I work for is switching providers. With 
> the old provider (as well as in my local setting), Python automatically 
> searched for imports in the current directory (the one where the program 
> was run). With the new one, this does not seem to be the case, so I am 
> getting ImportErrors all over the place.

sys.path is a list of locations that will be searched for imports. You 
can add new entries to it with the usual list operations.

If you want to add '.' to sys.path always you could do this in a 
sitecustomize.py module.
- Create a directory Lib\site-packages if it doesn't already exist
- Create a file site-packages\sitecustomize.py
- Put your custom startup stuff in sitecustomize.py

Is your new provider using a different OS? I remember a discussion long 
ago about the current directory being in sys.path or not and it seemed 
to vary depending on OS.

Kent


From kent37 at tds.net  Wed Jan 17 13:25:04 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 17 Jan 2007 07:25:04 -0500
Subject: [Tutor] import and unittest
In-Reply-To: <20070117135701.5e1b2c72@localhost>
References: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>	<eoi83f$kj5$1@sea.gmane.org>
	<20070117135701.5e1b2c72@localhost>
Message-ID: <45AE15A0.8000201@tds.net>

thomas coopman wrote:
> On Tue, 16 Jan 2007 10:06:37 -0000
> "Alan Gauld" <alan.gauld at btinternet.com> wrote:
> 
>> "Thomas Coopman" <thomas.coopman at gmail.com> wrote
>> .
>>> I wondered if it was possible to do something like this:
>>>
>>> src/
>>>    -a_module/
>>>        -sub_module/
>>> test/
>>>    -a_module/
>>>        -sub_module/
>>>
>> I don;t see any reason why not although its slightly more work.
>> Personally I tend to keep the tests with the code, but thats
>> mainly because tools such as editors tend to remember the last
>> folder opened and its a pain navigating between the two folders.
>>
>> The other system I have used(in C++ not Python) is to have
>> a test folder inside each src folder like:
>>
>> src/
>>    mod1/
>>        f1.py
>>        test/
>>           testf1.py
>>     mod2/
>>        f2.py
>>        f3.py
>>        test/
>>            testf1.py
>>            testf2.py
>>
>> etc.
>>
>> This minimises navigation and keeps the tests separate.
>> Its also relatively easy to filter out the tests when it comes
>> time to package upp the code for distribution (assuming
>> you want to lose them!)
>>
>>> I have something like this but I don't know how to organize the 
>>> imports in
>>> the tests and I don't know if this is a good idea.  What do you 
>>> think?
>> I think in Python you should create a package structure for
>> your code so that import can find the modules more easily.
>> But I've never tried this in Python, my Python projects are rarely
>> big enough to warrant it.
>>
>>
> 
> well, I still have problems with import
> 
> suppose I have something like this:
> 
> M/
>   __init__.py
>   A/
>     __init__.py
>     One.py
>   B/
>     __init__.py
>     Two.py
> 
> One.py
>     #!/usr/bin/python
> 
>     from M.B import Two
> 
> Two.py
>     #!/usr/bin/python
> 
>     from M.A import One
> 
> 
> when I try to run One.py or Two.py I get import errors and I don't know
> how to fix them.  I tried to set the __all__ variable in the __init__
> files but nothing worked so far.

What error do you get?

It's better to avoid this kind of circular import if you can. Rather 
than having One depend on Two and Two depend on One, look for some piece 
you can factor out into a new module that both One and Two use (or it 
may only be needed by One or Two).

There are several problems with circular imports, but the technical 
problem you are having is probably like this:

module One starts to execute
One imports Two
Two starts to execute
Two imports One
-- Note that at this point, the body of One has not executed, so 
anything defined in One after the import of Two is not yet defined.
Two tries to use something in One. Since One is not fully defined, it 
gets an AttributeError.

Anyway, try to split up your modules or post the exact error you get.

Kent


From thomas.coopman at gmail.com  Wed Jan 17 13:39:25 2007
From: thomas.coopman at gmail.com (Thomas Coopman)
Date: Wed, 17 Jan 2007 13:39:25 +0100
Subject: [Tutor] import and unittest
In-Reply-To: <45AE15A0.8000201@tds.net>
References: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>
	<eoi83f$kj5$1@sea.gmane.org> <20070117135701.5e1b2c72@localhost>
	<45AE15A0.8000201@tds.net>
Message-ID: <72ba78340701170439i7efb5132yd5d5fc294093add4@mail.gmail.com>

On 1/17/07, Kent Johnson <kent37 at tds.net> wrote:
>
> thomas coopman wrote:
> > On Tue, 16 Jan 2007 10:06:37 -0000
> > "Alan Gauld" <alan.gauld at btinternet.com> wrote:
> >
> >> "Thomas Coopman" <thomas.coopman at gmail.com> wrote
> >> .
> >>> I wondered if it was possible to do something like this:
> >>>
> >>> src/
> >>>    -a_module/
> >>>        -sub_module/
> >>> test/
> >>>    -a_module/
> >>>        -sub_module/
> >>>
> >> I don;t see any reason why not although its slightly more work.
> >> Personally I tend to keep the tests with the code, but thats
> >> mainly because tools such as editors tend to remember the last
> >> folder opened and its a pain navigating between the two folders.
> >>
> >> The other system I have used(in C++ not Python) is to have
> >> a test folder inside each src folder like:
> >>
> >> src/
> >>    mod1/
> >>        f1.py
> >>        test/
> >>           testf1.py
> >>     mod2/
> >>        f2.py
> >>        f3.py
> >>        test/
> >>            testf1.py
> >>            testf2.py
> >>
> >> etc.
> >>
> >> This minimises navigation and keeps the tests separate.
> >> Its also relatively easy to filter out the tests when it comes
> >> time to package upp the code for distribution (assuming
> >> you want to lose them!)
> >>
> >>> I have something like this but I don't know how to organize the
> >>> imports in
> >>> the tests and I don't know if this is a good idea.  What do you
> >>> think?
> >> I think in Python you should create a package structure for
> >> your code so that import can find the modules more easily.
> >> But I've never tried this in Python, my Python projects are rarely
> >> big enough to warrant it.
> >>
> >>
> >
> > well, I still have problems with import
> >
> > suppose I have something like this:
> >
> > M/
> >   __init__.py
> >   A/
> >     __init__.py
> >     One.py
> >   B/
> >     __init__.py
> >     Two.py
> >
> > One.py
> >     #!/usr/bin/python
> >
> >     from M.B import Two
> >
> > Two.py
> >     #!/usr/bin/python
> >
> >     from M.A import One
> >
> >
> > when I try to run One.py or Two.py I get import errors and I don't know
> > how to fix them.  I tried to set the __all__ variable in the __init__
> > files but nothing worked so far.
>
> What error do you get?
>
> It's better to avoid this kind of circular import if you can. Rather
> than having One depend on Two and Two depend on One, look for some piece
> you can factor out into a new module that both One and Two use (or it
> may only be needed by One or Two).
>
> There are several problems with circular imports, but the technical
> problem you are having is probably like this:
>
> module One starts to execute
> One imports Two
> Two starts to execute
> Two imports One
> -- Note that at this point, the body of One has not executed, so
> anything defined in One after the import of Two is not yet defined.
> Two tries to use something in One. Since One is not fully defined, it
> gets an AttributeError.
>
> Anyway, try to split up your modules or post the exact error you get.
>
> Kent
>
>
Well I don't really
need the circular imports but I would like to know how to do the
imports correct.
Suppose that in the example that I showed only One needs Two.

So then we have this:

M/
__init__.py
A/
__init__.py
One.py
B/
__init__.py
Two.py

One.py
#!/usr/bin/python

from M.B import Two


when I run this I get this error:
ImportError: No Module named M.B


-- 
Thomas Coopman
Thomas.coopman at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070117/ad0f88b4/attachment.html 

From kent37 at tds.net  Wed Jan 17 13:50:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 17 Jan 2007 07:50:18 -0500
Subject: [Tutor] import and unittest
In-Reply-To: <72ba78340701170439i7efb5132yd5d5fc294093add4@mail.gmail.com>
References: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>	
	<eoi83f$kj5$1@sea.gmane.org>
	<20070117135701.5e1b2c72@localhost>	 <45AE15A0.8000201@tds.net>
	<72ba78340701170439i7efb5132yd5d5fc294093add4@mail.gmail.com>
Message-ID: <45AE1B8A.70601@tds.net>

Thomas Coopman wrote:
> Well I don't really 
> need the circular imports but I would like to know how to do the imports correct. 
> 
> Suppose that in the example that I showed only One needs Two.
> 
> So then we have this:
> 
> M/
> __init__.py
> A/
> __init__.py
> One.py
> B/
> __init__.py
> Two.py
> 
> One.py
> #!/usr/bin/python
> 
> from M.B import Two
> 
> 
> when I run this I get this error:
> ImportError: No Module named M.B

Is the directory containing M in sys.path?

Kent


From vgvr620034 at gmail.com  Wed Jan 17 13:58:53 2007
From: vgvr620034 at gmail.com (raghu raghu)
Date: Wed, 17 Jan 2007 18:28:53 +0530
Subject: [Tutor] Query about getattr used as a dispatcher
Message-ID: <bedebdfb0701170458x692cd2e2i9206f4822a50a859@mail.gmail.com>

i am following 'dive into python' for learning. i come across a term
getattr() which gives reference about a function.Its written it can be used
as a dispatcher. Below example given for that builtin function:
import statsout
  def output(data,format='text'):
        output_function = getattr(statsout,"output_%s"  % format)
        return output_function(data)
Actually i installed python 2.5 i ran this script and its showing error it
could not import statsout.why is it so?could any one explain this script
briefly. i dont know whether i am following the right book. as i am a
beginner is it right  to follow this book?or is there any other book which
is best for beginners?

-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070117/672e59bf/attachment-0001.htm 

From thomas.coopman at gmail.com  Wed Jan 17 14:04:35 2007
From: thomas.coopman at gmail.com (Thomas Coopman)
Date: Wed, 17 Jan 2007 14:04:35 +0100
Subject: [Tutor] import and unittest
In-Reply-To: <45AE1B8A.70601@tds.net>
References: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>
	<eoi83f$kj5$1@sea.gmane.org> <20070117135701.5e1b2c72@localhost>
	<45AE15A0.8000201@tds.net>
	<72ba78340701170439i7efb5132yd5d5fc294093add4@mail.gmail.com>
	<45AE1B8A.70601@tds.net>
Message-ID: <72ba78340701170504w6f6558efi60e4051be6321da@mail.gmail.com>

On 1/17/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Thomas Coopman wrote:
> > Well I don't really
> > need the circular imports but I would like to know how to do the imports
> correct.
> >
> > Suppose that in the example that I showed only One needs Two.
> >
> > So then we have this:
> >
> > M/
> > __init__.py
> > A/
> > __init__.py
> > One.py
> > B/
> > __init__.py
> > Two.py
> >
> > One.py
> > #!/usr/bin/python
> >
> > from M.B import Two
> >
> >
> > when I run this I get this error:
> > ImportError: No Module named M.B
>
> Is the directory containing M in sys.path?
>
> Kent
>
>
When I run One.py from in the directory A, doesn't look python in it's
parent directory when it can't find the module?
And if that's not the case where and what should I add to the sys.pathvariable?


-- 
Thomas Coopman
Thomas.coopman at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070117/27dd427a/attachment.html 

From kent37 at tds.net  Wed Jan 17 14:11:59 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 17 Jan 2007 08:11:59 -0500
Subject: [Tutor] import and unittest
In-Reply-To: <72ba78340701170504w6f6558efi60e4051be6321da@mail.gmail.com>
References: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>	
	<eoi83f$kj5$1@sea.gmane.org> <20070117135701.5e1b2c72@localhost>	
	<45AE15A0.8000201@tds.net>	
	<72ba78340701170439i7efb5132yd5d5fc294093add4@mail.gmail.com>	
	<45AE1B8A.70601@tds.net>
	<72ba78340701170504w6f6558efi60e4051be6321da@mail.gmail.com>
Message-ID: <45AE209F.1070400@tds.net>

Thomas Coopman wrote:
> When I run One.py from in the directory A, doesn't look python in it's 
> parent directory when it can't find the module?
> And if that's not the case where and what should I add to the sys.path 
> variable?

No, Python won't look in parent directories for imports. Try running 
One.py from the parent dir of M by typing
 > python M/A/One.py

or add the parent dir of M to sys.path.

Kent


From thomas.coopman at gmail.com  Wed Jan 17 14:32:36 2007
From: thomas.coopman at gmail.com (Thomas Coopman)
Date: Wed, 17 Jan 2007 14:32:36 +0100
Subject: [Tutor] import and unittest
In-Reply-To: <45AE209F.1070400@tds.net>
References: <72ba78340701160101y2857a24blb4094255efafd3df@mail.gmail.com>
	<eoi83f$kj5$1@sea.gmane.org> <20070117135701.5e1b2c72@localhost>
	<45AE15A0.8000201@tds.net>
	<72ba78340701170439i7efb5132yd5d5fc294093add4@mail.gmail.com>
	<45AE1B8A.70601@tds.net>
	<72ba78340701170504w6f6558efi60e4051be6321da@mail.gmail.com>
	<45AE209F.1070400@tds.net>
Message-ID: <72ba78340701170532xacd530fk3f964a7dbaa08290@mail.gmail.com>

On 1/17/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Thomas Coopman wrote:
> > When I run One.py from in the directory A, doesn't look python in it's
> > parent directory when it can't find the module?
> > And if that's not the case where and what should I add to the sys.path
> > variable?
>
> No, Python won't look in parent directories for imports. Try running
> One.py from the parent dir of M by typing
> > python M/A/One.py
>
> or add the parent dir of M to sys.path.
>
> Kent
>
> when I try to run it from the parent dir of M, I still get the error,
where and when should I add the the parent dir to sys.path?

when I try from M.A import One in a shell executed in the parent dir of M
than it works.

The thing is that I would like to run One.py from anywhere and not just from
that one directory.
-- 
Thomas Coopman
Thomas.coopman at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070117/a100bc35/attachment.html 

From challman at gmail.com  Wed Jan 17 15:21:38 2007
From: challman at gmail.com (Chris Hallman)
Date: Wed, 17 Jan 2007 09:21:38 -0500
Subject: [Tutor] help with telnet error
Message-ID: <9f68812f0701170621x699cd58v5df9284fdd8ed0f@mail.gmail.com>

I'm working on a program that telnets to multiple devices to test their
backup ISDN BRI connections. I'm trying to build in error recovery with
try/except logic, but I'm having trouble getting it to work. This first
example uses a host name that isn't in our DNS (yes, this does happen):

>>> import telnetlib
>>> host = "s3793ap01"
>>> telnetlib.Telnet(host)

Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    telnetlib.Telnet(host)
  File "c:\python25\lib\telnetlib.py", line 208, in __init__
    self.open(host, port)
  File "c:\python25\lib\telnetlib.py", line 225, in open
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
gaierror: (11001, 'getaddrinfo failed')
>>>
>>>
>>>
>>>
>>> try:
    telnetlib.Telnet(host)
except gaierror, e:
    print "error found", e




Traceback (most recent call last):
  File "<pyshell#16>", line 3, in <module>
    except gaierror, e:
NameError: name 'gaierror' is not defined
>>>
>>>
>>>
>>> try:
    telnetlib.Telnet(host)
except IOError, e:
    print "error found", e




Traceback (most recent call last):
  File "<pyshell#22>", line 2, in <module>
    telnetlib.Telnet(host)
  File "c:\python25\lib\telnetlib.py", line 208, in __init__
    self.open(host, port)
  File "c:\python25\lib\telnetlib.py", line 225, in open
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
gaierror: (11001, 'getaddrinfo failed')


As you can see, I'm not sure how to handle the error. Any ideas?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070117/4b2cdc02/attachment.htm 

From Mike.Hansen at atmel.com  Wed Jan 17 15:29:14 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Wed, 17 Jan 2007 07:29:14 -0700
Subject: [Tutor] Perfect Python web stack?
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
Message-ID: <57B026980605A64F9B23484C5659E32E4C7A9C@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of OkaMthembo
> Sent: Wednesday, January 17, 2007 3:59 AM
> To: tutor
> Subject: [Tutor] Perfect Python web stack?
> 
> Ok pythonistas!
> 
> Please help me to decide. I might have asked some of you 
> before, so please bear with me.
> 
> I want to build a database driven python web app and i need 
> to decide, so please vote on the best components (im 
> developing on XP SP2): 
> 
> 1) MySQL vs PostGRES
> 2) Lighttpd + FastCGI vs Apache + mod_python
> 3) Pylons + Cheetah + Kid/Mochikit/Dojo vs Django/Turbogears
> 
> This is not to light fires, its for my sole information :-)
> 
> Thanks in advance, gurus.
> 
> "Shortash"

I think I recently read the you need to purchase MySQL to get a binary
for Windows, but don't quote me. 

Postgre + Apache + Cheetah + Dojo is working for me. Sometime soon, I
want to experiment with Django.

I'm not familiar with Lighttpd, FastCGI, mod_python, Pylons, or Kid.
When I was looking for a JavaScript toolkit, I took a look at Mochikit
and Dojo. I was able to understand Dojo better although I hear that
Mochikit is more Python-like. <shrug />

Mike 
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS

From kent37 at tds.net  Wed Jan 17 15:37:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 17 Jan 2007 09:37:48 -0500
Subject: [Tutor] help with telnet error
In-Reply-To: <9f68812f0701170621x699cd58v5df9284fdd8ed0f@mail.gmail.com>
References: <9f68812f0701170621x699cd58v5df9284fdd8ed0f@mail.gmail.com>
Message-ID: <45AE34BC.7040607@tds.net>

Chris Hallman wrote:
> 
> I'm working on a program that telnets to multiple devices to test their 
> backup ISDN BRI connections. I'm trying to build in error recovery with 
> try/except logic, but I'm having trouble getting it to work. This first 
> example uses a host name that isn't in our DNS (yes, this does happen):
> 
>  >>> import telnetlib
>  >>> host = "s3793ap01"
>  >>> telnetlib.Telnet(host)
> 
> Traceback (most recent call last):
>   File "<pyshell#30>", line 1, in <module>
>     telnetlib.Telnet(host)
>   File "c:\python25\lib\telnetlib.py", line 208, in __init__
>     self.open(host, port)
>   File "c:\python25\lib\telnetlib.py", line 225, in open
>     for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
> gaierror: (11001, 'getaddrinfo failed')
>  >>>
>  >>>
>  >>>
>  >>>
>  >>> try:
>     telnetlib.Telnet(host)
> except gaierror, e:
>     print "error found", e
> 
> 
>    
> 
> Traceback (most recent call last):
>   File "<pyshell#16>", line 3, in <module>
>     except gaierror, e:
> NameError: name 'gaierror' is not defined

gaierror is defined in the socket module. Add
   import socket

then use
   except socket.gaierror, e:

Kent


From cbc at unc.edu  Wed Jan 17 15:41:32 2007
From: cbc at unc.edu (Chris Calloway)
Date: Wed, 17 Jan 2007 09:41:32 -0500
Subject: [Tutor] Query about getattr used as a dispatcher
In-Reply-To: <bedebdfb0701170458x692cd2e2i9206f4822a50a859@mail.gmail.com>
References: <bedebdfb0701170458x692cd2e2i9206f4822a50a859@mail.gmail.com>
Message-ID: <45AE359C.8070104@unc.edu>

raghu raghu wrote:
> Actually i installed python 2.5 i ran this script and its showing error 
> it could not import statsout. why is it so?

statsout is a *hypothetical* module used for an example only. The 
statsout module does not actually exist. When Dive Into Python wants you 
to type in an example, it will shown either as lines at the Python 
interpreter prompt (>>>), or it will be an example in a Python source 
file included with the Dive Into Python examples bundle. If you look at 
the example using the imaginary statsout module in section 4.12, which 
is not included in any Python source file in the Dive Into Python 
examples bundle, you will see the example is not referenced in a file, 
nor is it shown as being typed at the Python interpreter prompt.

If, however, you had an actual statsout module in your sys.path, you 
could import it. And it that module had top level functions functions 
that took one argument and had function names like "output_text" and 
"output_pdf" and "output_html," then the example would work if you typed 
it in. The example is just showing a hypothetical case of a very simple 
dispatcher. The example is asking you to imagine *if* you had a statsout 
module, and *if* that module had functions by those names in it.

Dive Into Python uses the getattr function in the apihelper.py example 
you are currently reading about. In the next chapter, a more complicated 
example is shown where getattr is used in a dispatcher which finds, not 
just a function by name, but a class by name and dispatches that class 
object to create a new object of that class. So the statsout *imaginary* 
example is just preparing you for a more complicated *real life* 
dispatcher example in the next chapter. Hypothetical examples are often 
shown in programming books to prepare you for more complicated real life 
examples.

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599


From zebra05 at gmail.com  Wed Jan 17 15:46:12 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Wed, 17 Jan 2007 16:46:12 +0200
Subject: [Tutor] Perfect Python web stack?
In-Reply-To: <57B026980605A64F9B23484C5659E32E4C7A9C@poccso.US.ad.atmel.com>
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
	<57B026980605A64F9B23484C5659E32E4C7A9C@poccso.US.ad.atmel.com>
Message-ID: <c7c6f3bc0701170646v4b00014cq779265c04b27f1c5@mail.gmail.com>

Thanks, gentlemen. Input appreciated and noted.

"Shortash"

On 1/17/07, Mike Hansen <Mike.Hansen at atmel.com> wrote:
>
>
>
> > -----Original Message-----
> > From: tutor-bounces at python.org
> > [mailto:tutor-bounces at python.org] On Behalf Of OkaMthembo
> > Sent: Wednesday, January 17, 2007 3:59 AM
> > To: tutor
> > Subject: [Tutor] Perfect Python web stack?
> >
> > Ok pythonistas!
> >
> > Please help me to decide. I might have asked some of you
> > before, so please bear with me.
> >
> > I want to build a database driven python web app and i need
> > to decide, so please vote on the best components (im
> > developing on XP SP2):
> >
> > 1) MySQL vs PostGRES
> > 2) Lighttpd + FastCGI vs Apache + mod_python
> > 3) Pylons + Cheetah + Kid/Mochikit/Dojo vs Django/Turbogears
> >
> > This is not to light fires, its for my sole information :-)
> >
> > Thanks in advance, gurus.
> >
> > "Shortash"
>
> I think I recently read the you need to purchase MySQL to get a binary
> for Windows, but don't quote me.
>
> Postgre + Apache + Cheetah + Dojo is working for me. Sometime soon, I
> want to experiment with Django.
>
> I'm not familiar with Lighttpd, FastCGI, mod_python, Pylons, or Kid.
> When I was looking for a JavaScript toolkit, I took a look at Mochikit
> and Dojo. I was able to understand Dojo better although I hear that
> Mochikit is more Python-like. <shrug />
>
> Mike
>
>
> -------------
>
>   NOTICE:  This e-mail transmission and any documents or files attached to
>   it contain information for the sole use of the above-identified
> individual or entity.
>
>   Its contents may be privileged, confidential, and exempt from disclosure
> under the law.
>   Any dissemination, distribution, or copying of this communication is
> strictly prohibited.
>
>   Please notify the sender immediately if you are not the intended
> recipient.
>
> FGNS
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070117/0f7264d0/attachment.html 

From kent37 at tds.net  Wed Jan 17 15:55:04 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 17 Jan 2007 09:55:04 -0500
Subject: [Tutor] Query about getattr used as a dispatcher
In-Reply-To: <bedebdfb0701170458x692cd2e2i9206f4822a50a859@mail.gmail.com>
References: <bedebdfb0701170458x692cd2e2i9206f4822a50a859@mail.gmail.com>
Message-ID: <45AE38C8.2090901@tds.net>

raghu raghu wrote:
> i am following 'dive into python' for learning.  i dont know whether i am following the right book. as i 
> am a beginner is it right  to follow this book?or is there any other 
> book which is best for beginners?

I don't think Dive Into Python is a great book for beginners. In my 
opinion the book is too focused on advanced features.

You might want to try one of these tutorials:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

or one of these books:
http://effbot.org/pyfaq/tutor-what-are-some-good-books-on-python.htm

Kent


From kent37 at tds.net  Wed Jan 17 16:09:02 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 17 Jan 2007 10:09:02 -0500
Subject: [Tutor] Perfect Python web stack?
In-Reply-To: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
Message-ID: <45AE3C0E.6010402@tds.net>

OkaMthembo wrote:
> Ok pythonistas!
> 
> Please help me to decide. I might have asked some of you before, so 
> please bear with me.
> 
> I want to build a database driven python web app and i need to decide, 
> so please vote on the best components (im developing on XP SP2):
> 
> 1) MySQL vs PostGRES
> 2) Lighttpd + FastCGI vs Apache + mod_python
> 3) Pylons + Cheetah + Kid/Mochikit/Dojo vs Django/Turbogears

All of these have their proponents. If you search comp.lang.python you 
will find many discussions. Start here:
http://groups.google.com/group/comp.lang.python/

Kent


From python at venix.com  Wed Jan 17 16:38:53 2007
From: python at venix.com (Python)
Date: Wed, 17 Jan 2007 10:38:53 -0500
Subject: [Tutor] Perfect Python web stack?
In-Reply-To: <c7c6f3bc0701170646v4b00014cq779265c04b27f1c5@mail.gmail.com>
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
	<57B026980605A64F9B23484C5659E32E4C7A9C@poccso.US.ad.atmel.com>
	<c7c6f3bc0701170646v4b00014cq779265c04b27f1c5@mail.gmail.com>
Message-ID: <1169048333.3821.59.camel@www.venix.com>

On Wed, 2007-01-17 at 16:46 +0200, OkaMthembo wrote:
> > 1) MySQL vs PostGRES

PostGRES is a more sophisticated SQL server.  It should probably be the
default choice.

However, I'm primarily using MySQL.  The reasons:
        easy administration - I think supporting dozens of remote
        databases is easier with MySQL.
        
        replication - the loosely coupled MySQL approach to replication
        has been a better fit for my needs.
        
        good performance in the common simple cases

You probably need to work through your requirements and match those
against the different available products.  If you provide a list of
requirements, you might get more meaningful feedback.

-- 
Lloyd Kvam
Venix Corp


From challman at gmail.com  Wed Jan 17 17:39:51 2007
From: challman at gmail.com (Chris Hallman)
Date: Wed, 17 Jan 2007 11:39:51 -0500
Subject: [Tutor] problem with telnetlib, threading class and try/except
Message-ID: <9f68812f0701170839j7dac69aax4a68a6612b32089a@mail.gmail.com>

I'm writing a multithreaded program that initiates a dial backup connection
to check the B channels on ISDN BRI connections. I recently added logic to
check for offline devices (Operation timed out) and DNS errors (getaddrinfo
failed). When it encounters the exception, it doesn't appear to be exiting
(by way of the return command) the thread, hence the error.

The input file contains:

rtr3926
s0877ap01

Here is part of the program:
import os, os.path, random, re, socket, string, sys, telnetlib, threading,
time
from time import strftime
from threading import Thread

class ISDNTest(threading.Thread):
    def __init__(self, host):
        Thread.__init__(self)
        self.host = host
        try:
            self.tn = telnetlib.Telnet(self.host)
        except socket.error, err:
            if "Operation timed out" in err:
                print "1st if", self.host, err #progress checking
                dialTestResult[self.host] = ["", "connection timed out"]
                return
            elif "getaddrinfo failed" in err:
                print "2nd if", self.host, err #progress checking
                dialTestResult[self.host] = ["", "DNS resolution failed"]
                return
        self.status = []
        print self.tn #progress checking

    def run(self):
        connect_status = self.Logon()
...........(much more program not pasted here)

for entry in inFile:
    if entry == '\n':
        continue
    elif "#" in entry:
        continue
    entry = entry.replace("\n", "")
    while count_active() >= Max_Threads:
        time.sleep(1)
    threads = ISDNTest(entry)
    tlist.append(threads)
    threads.start()

for thread in tlist:
    thread.join()


Here is there error:
>pythonw -u "new.isdn.test.py"
<telnetlib.Telnet instance at 0x00B21670>
log me on rtr3926 (progress checking message, this isn't an error)
1st if s0877ap01 (10060, 'Operation timed out') (progress checking message;
this indicates an exception occurred)
log me on s0877ap01 (progress checking message, this isn't an error)
Exception in thread Thread-2:
Traceback (most recent call last):
  File "c:\python25\lib\threading.py", line 460, in __bootstrap
    self.run()
  File "new.isdn.test.py", line 35, in run
    connect_status = self.Logon()
  File "new.isdn.test.py", line 59, in Logon
    self.tn.read_until("Username:", 7)
AttributeError: 'ISDNTest' object has no attribute 'tn'

>Exit code: 0
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070117/5f1724e3/attachment.html 

From nospamformeSVP at gmail.com  Wed Jan 17 18:51:05 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Wed, 17 Jan 2007 12:51:05 -0500
Subject: [Tutor] What is a mixin class?
Message-ID: <eolnmg$epm$1@sea.gmane.org>

I have a vague idea what a mixin class is, I would like to get a better 
handle on it.

It is a term that is used quite often in Python circles, but I can't 
find a definition.

I guess that because of multiple inheritance Python does not need a 
formal way of specifying mixin classes so I presume that there is some 
conventional interpretation/coding that is followed for mixin classes.

So, what constitutes a mixin class and what are the conventional ways to 
denote them in code?

Don.

I notice that Ruby has single inheritance plus mixin classes so maybe 
somebody who knows Ruby could throw some light on in what way a mixin is 
different from normal superclass.


From dkuhlman at rexx.com  Wed Jan 17 18:56:00 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Wed, 17 Jan 2007 09:56:00 -0800
Subject: [Tutor] possible import locations
In-Reply-To: <45AE0367.5050105@tds.net>
References: <6faf39c90701170121o6d108cc1m8cbb49b180dcf7ee@mail.gmail.com>
	<45AE0367.5050105@tds.net>
Message-ID: <20070117175600.GA23726@cutter.rexx.com>

On Wed, Jan 17, 2007 at 06:07:19AM -0500, Kent Johnson wrote:
> Andre Engels wrote:
> > Is it possible to see from a python program where it searches for 
> > possible imports? Is it possible to import from another location than 
> > those? (Of course with an "if so, how" attached).
> > 
> > The issue is that the company I work for is switching providers. With 
> > the old provider (as well as in my local setting), Python automatically 
> > searched for imports in the current directory (the one where the program 
> > was run). With the new one, this does not seem to be the case, so I am 
> > getting ImportErrors all over the place.
> 
> sys.path is a list of locations that will be searched for imports. You 
> can add new entries to it with the usual list operations.
> 
> If you want to add '.' to sys.path always you could do this in a 
> sitecustomize.py module.
> - Create a directory Lib\site-packages if it doesn't already exist
> - Create a file site-packages\sitecustomize.py
> - Put your custom startup stuff in sitecustomize.py

You will also want to read about .pth files.  See this:

    http://docs.python.org/lib/module-site.html

And, of course, you can also read the source.  See site.py, which
on my machine is at:

    /usr/local/lib/python2.5/site.py

> 
> Is your new provider using a different OS? I remember a discussion long 
> ago about the current directory being in sys.path or not and it seemed 
> to vary depending on OS.

Right.  I'm on Linux (Debian GNU/Linux).  '.' is not on my
sys.path, but I can import from the current directory.

However, the empty string ('') is the first item in the list
sys.path.  Does the empty string mean the same thing as the
directory '.'?

Does anyone have a reference to a document that specifies
recommended policy for the use of the .pth files and the
sitecustomize.py file.  For example, in addition to Kent's
recommendation, you could also put sitecustomize.py in your current
directory, where it would only affect programs run from that
directory.  Which is recommended and when?

Also, the .pth file thing seems to be a way to give a package, when
it is installed, to hijack the import path by stuffing paths above
(earlier than) existing paths.  Is there a recommended policy on
this?  If so, where can I read up on it?

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From kent37 at tds.net  Wed Jan 17 19:57:53 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 17 Jan 2007 13:57:53 -0500
Subject: [Tutor] problem with telnetlib, threading class and try/except
In-Reply-To: <9f68812f0701170839j7dac69aax4a68a6612b32089a@mail.gmail.com>
References: <9f68812f0701170839j7dac69aax4a68a6612b32089a@mail.gmail.com>
Message-ID: <45AE71B1.8010500@tds.net>

Chris Hallman wrote:
> 
> I'm writing a multithreaded program that initiates a dial backup 
> connection to check the B channels on ISDN BRI connections. I recently 
> added logic to check for offline devices (Operation timed out) and DNS 
> errors (getaddrinfo failed). When it encounters the exception, it 
> doesn't appear to be exiting (by way of the return command) the thread, 
> hence the error.
> 
> The input file contains:
> 
> rtr3926
> s0877ap01
> 
> Here is part of the program:
> import os, os.path, random, re, socket, string, sys, telnetlib, 
> threading, time
> from time import strftime
> from threading import Thread
> 
> class ISDNTest(threading.Thread):
>     def __init__(self, host):
>         Thread.__init__(self)
>         self.host = host
>         try:
>              self.tn <http://self.tn> = telnetlib.Telnet(self.host)
>         except socket.error, err:
>             if "Operation timed out" in err:
>                 print "1st if", self.host, err #progress checking
>                 dialTestResult[self.host] = ["", "connection timed out"]
>                 return
>             elif "getaddrinfo failed" in err:
>                 print "2nd if", self.host, err #progress checking
>                 dialTestResult[self.host] = ["", "DNS resolution failed"]
>                 return

You need an else: clause here; what if the error doesn't match either of 
your tests?

Kent

>         self.status = []
>         print self.tn <http://self.tn> #progress checking
> 
>     def run(self):
>         connect_status = self.Logon()
> ...........(much more program not pasted here)
> 
> for entry in inFile:
>     if entry == '\n':
>         continue
>     elif "#" in entry:
>         continue
>     entry = entry.replace("\n", "")
>     while count_active() >= Max_Threads:
>         time.sleep(1)
>     threads = ISDNTest(entry)
>     tlist.append(threads)
>     threads.start()
> 
> for thread in tlist:
>     thread.join()
> 
> 
> Here is there error:
>  >pythonw -u "new.isdn.test.py <http://new.isdn.test.py>"
> <telnetlib.Telnet instance at 0x00B21670>
> log me on rtr3926 (progress checking message, this isn't an error)
> 1st if s0877ap01 (10060, 'Operation timed out') (progress checking 
> message; this indicates an exception occurred)
> log me on s0877ap01 (progress checking message, this isn't an error)
> Exception in thread Thread-2:
> Traceback (most recent call last):
>   File "c:\python25\lib\threading.py", line 460, in __bootstrap
>     self.run()
>   File " new.isdn.test.py <http://new.isdn.test.py>", line 35, in run
>     connect_status = self.Logon()
>   File "new.isdn.test.py <http://new.isdn.test.py>", line 59, in Logon
>     self.tn.read_until("Username:", 7)
> AttributeError: 'ISDNTest' object has no attribute 'tn'
> 
>  >Exit code: 0
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



From dkuhlman at rexx.com  Wed Jan 17 20:21:00 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Wed, 17 Jan 2007 11:21:00 -0800
Subject: [Tutor] Perfect Python web stack?
In-Reply-To: <45AE3C0E.6010402@tds.net>
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
	<45AE3C0E.6010402@tds.net>
Message-ID: <20070117192100.GA26119@cutter.rexx.com>

On Wed, Jan 17, 2007 at 10:09:02AM -0500, Kent Johnson wrote:
> OkaMthembo wrote:
> > Ok pythonistas!
> > 
> > Please help me to decide. I might have asked some of you before, so 
> > please bear with me.
> > 
> > I want to build a database driven python web app and i need to decide, 
> > so please vote on the best components (im developing on XP SP2):
> > 
> > 1) MySQL vs PostGRES
> > 2) Lighttpd + FastCGI vs Apache + mod_python
> > 3) Pylons + Cheetah + Kid/Mochikit/Dojo vs Django/Turbogears
> 
> All of these have their proponents. If you search comp.lang.python you 
> will find many discussions. Start here:
> http://groups.google.com/group/comp.lang.python/
> 

For the Web part of the stack, here is another good starting point:

    http://wiki.python.org/moin/WebFrameworks

I'm currently learning Pylons.  The tutorials for Pylons discuss
two object-relational mappers for Python: SQLObject and SQLAlchemy. 
If you want to view your database from a higher, more abstract
level, you might want to look at them, too.  Here are some database
references:

    http://wiki.python.org/moin/DatabaseInterfaces
    http://www.python.org/doc/topics/database/
    http://www.python.org/doc/topics/database/modules/
    http://www.sqlalchemy.org/
    http://www.sqlobject.org/

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From lexicontrol at gmail.com  Wed Jan 17 21:09:57 2007
From: lexicontrol at gmail.com (Vijay Pattisapu)
Date: Wed, 17 Jan 2007 14:09:57 -0600
Subject: [Tutor] Graphics with Python: wxPython vs. tkinter vs. PyCairo vs.
	PyX vs...
Message-ID: <c5dd7a240701171209n5c8a0f94r3d23f7ba023cf3f7@mail.gmail.com>

Hey friends--

I've been looking through the archives and haven't found any
comparative evaluation of Python graphics libraries...

Which is the best (or your favorite), and for what tasks?

Thanks a lot!
Vijay

-- 
3506 Speedway
Austin, TX 78705
Cell: (469)877-9166

From lexicontrol at gmail.com  Wed Jan 17 21:12:05 2007
From: lexicontrol at gmail.com (Vijay Pattisapu)
Date: Wed, 17 Jan 2007 14:12:05 -0600
Subject: [Tutor] Perfect Python web stack?
In-Reply-To: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
Message-ID: <c5dd7a240701171212i1e2fe639i7253942d97e9bd5a@mail.gmail.com>

I personally like Zope's object-oriented database.

-Vijay

On 17/01/07, OkaMthembo <zebra05 at gmail.com> wrote:
> Ok pythonistas!
>
> Please help me to decide. I might have asked some of you before, so please
> bear with me.
>
> I want to build a database driven python web app and i need to decide, so
> please vote on the best components (im developing on XP SP2):
>
> 1) MySQL vs PostGRES
> 2) Lighttpd + FastCGI vs Apache + mod_python
> 3) Pylons + Cheetah + Kid/Mochikit/Dojo vs Django/Turbogears
>
> This is not to light fires, its for my sole information :-)
>
> Thanks in advance, gurus.
>
> "Shortash"
>
> --
> "The Stupidry Foundry"
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
3506 Speedway
Austin, TX 78705
Cell: (469)877-9166

From chris.lasher at gmail.com  Wed Jan 17 21:46:19 2007
From: chris.lasher at gmail.com (Chris Lasher)
Date: Wed, 17 Jan 2007 15:46:19 -0500
Subject: [Tutor] What is a mixin class?
In-Reply-To: <eolnmg$epm$1@sea.gmane.org>
References: <eolnmg$epm$1@sea.gmane.org>
Message-ID: <128a885f0701171246sed23behadfe42cd63387bc@mail.gmail.com>

On 1/17/07, Don Taylor <nospamformeSVP at gmail.com> wrote:
> So, what constitutes a mixin class and what are the conventional ways to
> denote them in code?

A mixin is a specific type of superclass, just called a mixin because
of the concept it represents. A common type of mixin would be a class
that defines some sort of modified functionality intended to be given
to multiple, not necessarily related classes.

Say you wanted all your classes to have a similar looking format when
"print"ed. You could define a mixin class that defined a special
__repr__ method. A detailed  example of this is demonstrated in
/Learning Python/ by Lutz & Ascher.

There's no need to explicitly state that they are a mixin class, but
if you felt the need to, you could either put it in a comment or,
probably even better, in the mixin's docstring.

Chris

From dyoo at hkn.eecs.berkeley.edu  Wed Jan 17 21:57:11 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 17 Jan 2007 12:57:11 -0800 (PST)
Subject: [Tutor] What is a mixin class?
In-Reply-To: <eolnmg$epm$1@sea.gmane.org>
References: <eolnmg$epm$1@sea.gmane.org>
Message-ID: <Pine.LNX.4.64.0701171235550.3381@hkn.eecs.berkeley.edu>



On Wed, 17 Jan 2007, Don Taylor wrote:

> I have a vague idea what a mixin class is, I would like to get a better 
> handle on it.

Hi Don,

This post might help:

     http://mail.python.org/pipermail/tutor/2006-October/050448.html


The core idea is that, since classes themselves are first-class objects, 
we can pass classes around to functions.  More importantly, we can make 
classes on-the-fly.

If we have some class C on hand, we can easily build a subclass.  For 
example:

########################
def do_nothing_mixin(C):
     class S(C):
         pass
     return S
########################

Here, do_nothing_mixing takes in a class C and returns a class S, where S 
is a child subclass of C.  Of course, this example is a bit useless. 
*grin*


But here's a slightly more interesting one:

#######################################
def observer_mixin(C):
     class S(C):
         def __init__(self, *args, **kwargs):
             C.__init__(self, *args, **kwargs)
             self.__listeners = []
         def add_listener(self, l):
             self.__listeners.append(l)
         def notify(self, obj):
             for l in self.__listeners:
                 l.notified(obj)
     return S
#######################################


This captures most of the "Observer" design pattern (without 
thread-safety, but it wouldn't be hard to add that feature in).

We can now add observer capabilities to an arbitrary class:

#######################################################################
class Person:
     def __init__(self, name):
         self.name = name
     def notified(self, obj):
         print "Oh, I %s have been notified about %r" % (self.name, obj)

Announcer = observer_mixin(Person)

ann = Announcer("bart")
others = [Person("Lisa"), Person("Marge"), Person("Homer")]
for o in others:
     ann.add_listener(o)

ann.notify("donut")
#######################################################################

Note here that we have a pre-existing Person class, and we create a new 
kind of Person called an Announcer.  This Announcer is a person, but can 
also act as an observer.


> It is a term that is used quite often in Python circles, but I can't
> find a definition.

One definition (not the only possible one) could be:

     mixin: a function that takes in an input class and produces
     an output class that's guaranteed to be a subclass of the input.

There are other ways to get mixin-like functionality, which is why it's 
necessary to come to terms.



> I notice that Ruby has single inheritance plus mixin classes so maybe 
> somebody who knows Ruby could throw some light on in what way a mixin is 
> different from normal superclass.

'modules' in Ruby are injectable into the definitions of other classes. 
The mechanism, then, is slightly different than what's presented here, but 
the end effect is pretty similar.


If you have more questions, please feel free to ask.

From kent37 at tds.net  Wed Jan 17 21:59:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 17 Jan 2007 15:59:58 -0500
Subject: [Tutor] What is a mixin class?
In-Reply-To: <eolnmg$epm$1@sea.gmane.org>
References: <eolnmg$epm$1@sea.gmane.org>
Message-ID: <45AE8E4E.7040302@tds.net>

(resending to the whole list)

Don Taylor wrote:
> I have a vague idea what a mixin class is, I would like to get a better 
> handle on it.
> 
> It is a term that is used quite often in Python circles, but I can't 
> find a definition.
> 
> I guess that because of multiple inheritance Python does not need a 
> formal way of specifying mixin classes so I presume that there is some 
> conventional interpretation/coding that is followed for mixin classes.
> 
> So, what constitutes a mixin class and what are the conventional ways to 
> denote them in code?
> 
> Don.
> 
> I notice that Ruby has single inheritance plus mixin classes so maybe 
> somebody who knows Ruby could throw some light on in what way a mixin is 
> different from normal superclass.

A mixin is a class that is not intended to stand on its own, rather it
adds some behaviour to the class that it is mixed in to. Some discussion
here:
http://en.wikipedia.org/wiki/Mixin
http://c2.com/cgi/wiki?Mixin

This page
http://c2.com/cgi/wiki?MixinsForPython
points to SocketServer.ForkingMixin and SocketServer.ThreadingMixin as
examples from the Python standard library.

HTH,
Kent



From john at fouhy.net  Thu Jan 18 00:57:34 2007
From: john at fouhy.net (John Fouhy)
Date: Thu, 18 Jan 2007 12:57:34 +1300
Subject: [Tutor] Graphics with Python: wxPython vs. tkinter vs. PyCairo
	vs. PyX vs...
In-Reply-To: <c5dd7a240701171209n5c8a0f94r3d23f7ba023cf3f7@mail.gmail.com>
References: <c5dd7a240701171209n5c8a0f94r3d23f7ba023cf3f7@mail.gmail.com>
Message-ID: <5e58f2e40701171557j2ebf9369p8ffc85060412e64b@mail.gmail.com>

On 18/01/07, Vijay Pattisapu <lexicontrol at gmail.com> wrote:
> Hey friends--
>
> I've been looking through the archives and haven't found any
> comparative evaluation of Python graphics libraries...
>
> Which is the best (or your favorite), and for what tasks?

I only have experience with Tkinter and wxPython.

Tkinter is easy, and feels much more pythonic than wxPython.  However,
Tkinter doesn't have a wide range of widgets available (although Pmw
does a good job of faking some more).  Also, Tkinter doesn't use
native widgets, so it will be slower and Tkinter apps will look
foreign and ugly on most systems.

wxPython uses native widgets, so it looks nice.  The biggest problem
with wxPython is that it has evolved from a bare wrapper around C++ to
something more pythonic, but it hasn't left much behind.  There are
several programming styles (explicit IDs? implicit IDs? no IDs?
Keyword arguments or positional arguments?) and several ways of
positioning widgets (sizers, which are like pack/grid, or explicit
positioning, or one or two other methods).

The upshot is that you can write nice pythonic code, but a lot of the
examples you will find will be in a different style, and many of the
experienced coders are used to an older style of wx coding.

But wxPython is better than Tkinter for apps you're going to spend
time on, or show to other people.

-- 
John.

From nospamformeSVP at gmail.com  Thu Jan 18 04:01:18 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Wed, 17 Jan 2007 22:01:18 -0500
Subject: [Tutor] What is a mixin class?
In-Reply-To: <eolnmg$epm$1@sea.gmane.org>
References: <eolnmg$epm$1@sea.gmane.org>
Message-ID: <eomnu5$oaq$1@sea.gmane.org>

Don Taylor wrote:
> I have a vague idea what a mixin class is, I would like to get a better 
> handle on it.
> 

Thanks for the information and the links, I have a much better idea 
about mix-ins now.  I also found the following informative:

http://www.linuxjournal.com/article/4540
and
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498124

Don.


From vgvr620034 at gmail.com  Thu Jan 18 04:15:04 2007
From: vgvr620034 at gmail.com (raghu raghu)
Date: Thu, 18 Jan 2007 08:45:04 +0530
Subject: [Tutor] Beginners
Message-ID: <bedebdfb0701171915i397a02bau58dbc2569d81c40e@mail.gmail.com>

can i follow 'Learning Python' by oreily. Is it good for beginners? can any
one suggest me i am planning to buy  a  hard copy (text book)

-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070118/39a83842/attachment.htm 

From wescpy at gmail.com  Thu Jan 18 07:31:06 2007
From: wescpy at gmail.com (wesley chun)
Date: Wed, 17 Jan 2007 22:31:06 -0800
Subject: [Tutor] Beginners
In-Reply-To: <bedebdfb0701171915i397a02bau58dbc2569d81c40e@mail.gmail.com>
References: <bedebdfb0701171915i397a02bau58dbc2569d81c40e@mail.gmail.com>
Message-ID: <78b3a9580701172231g2d96badbg6be12b6ec4877653@mail.gmail.com>

On 1/17/07, raghu raghu <vgvr620034 at gmail.com> wrote:
> can i follow 'Learning Python' by oreily. Is it good for beginners? can any
> one suggest me i am planning to buy  a  hard copy (text book)


what is your programming background, what languages do you know
already?  or are you completely new to programming?  the books we
recommend are based on where you are coming from -- that will help you
find the right book for your needs.

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From vgvr620034 at gmail.com  Thu Jan 18 07:44:08 2007
From: vgvr620034 at gmail.com (raghu raghu)
Date: Thu, 18 Jan 2007 12:14:08 +0530
Subject: [Tutor] Beginners
In-Reply-To: <78b3a9580701172231g2d96badbg6be12b6ec4877653@mail.gmail.com>
References: <bedebdfb0701171915i397a02bau58dbc2569d81c40e@mail.gmail.com>
	<78b3a9580701172231g2d96badbg6be12b6ec4877653@mail.gmail.com>
Message-ID: <bedebdfb0701172244k5c673215v94c38fb32a8a5e26@mail.gmail.com>

I dont have any programming background, i know only c language.

On 1/18/07, wesley chun <wescpy at gmail.com> wrote:
>
> On 1/17/07, raghu raghu <vgvr620034 at gmail.com> wrote:
> > can i follow 'Learning Python' by oreily. Is it good for beginners? can
> any
> > one suggest me i am planning to buy  a  hard copy (text book)
>
>
> what is your programming background, what languages do you know
> already?  or are you completely new to programming?  the books we
> recommend are based on where you are coming from -- that will help you
> find the right book for your needs.
>
> cheers,
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>     http://corepython.com
>
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
>



-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070118/f5c0b6f1/attachment.html 

From paulino1 at sapo.pt  Thu Jan 18 10:23:17 2007
From: paulino1 at sapo.pt (Paulino)
Date: Thu, 18 Jan 2007 09:23:17 +0000
Subject: [Tutor] Graphics with Python: wxPython vs. tkinter vs.,
 PyCairo vs.	PyX vs...
In-Reply-To: <mailman.8678.1169102651.32030.tutor@python.org>
References: <mailman.8678.1169102651.32030.tutor@python.org>
Message-ID: <45AF3C85.2070401@sapo.pt>

There is also PyQt4 which is my favorite. I'm a beginner in programming 
I tryed first PyQt and I gave up because it seemed so complicated. Then 
I've played a litle with tkinter which I think is very poor. I moved to 
wxpython which as a learning curve similar to that of tkinter, but a 
wider set of widgets available.

Then o tryed again PyQt and it wasn't complicated anymore! PyQt as a 
even wider set of wigets than wxpy but the BIG advantage is QtDesigner 
which you can use to design your interfaces and then you only have to 
code the methods to the actions you want the widgets to perform.

Good luck

Paulino

> Date: Wed, 17 Jan 2007 14:09:57 -0600
> From: "Vijay Pattisapu" <lexicontrol at gmail.com>
> Subject: [Tutor] Graphics with Python: wxPython vs. tkinter vs.
> 	PyCairo vs.	PyX vs...
> To: tutor at python.org
> Message-ID:
> 	<c5dd7a240701171209n5c8a0f94r3d23f7ba023cf3f7 at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Hey friends--
>
> I've been looking through the archives and haven't found any
> comparative evaluation of Python graphics libraries...
>
> Which is the best (or your favorite), and for what tasks?
>
> Thanks a lot!
> Vijay
>
>   


From johan at accesstel.co.za  Thu Jan 18 12:37:57 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Thu, 18 Jan 2007 13:37:57 +0200
Subject: [Tutor] Division doesn't work
Message-ID: <20070118113223.DB070163C0@mail.accesstel.co.za>

Hi all,
 
In my script I want to convert 14105 bytes to kilobytes and and this is what
I do:
 
>>> s = 14105
>>> print '%0.2f' % (s/1024)
13.00 
 
This not correct and I don't know why. The answer is 13.77.
 
Any pointers please that would help my in the right direction?
 
Thanks
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date: 2007/01/16
04:36 PM
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070118/426944f4/attachment.htm 

From geoframer at gmail.com  Thu Jan 18 13:09:48 2007
From: geoframer at gmail.com (Geoframer)
Date: Thu, 18 Jan 2007 13:09:48 +0100
Subject: [Tutor] Division doesn't work
In-Reply-To: <20070118113223.DB070163C0@mail.accesstel.co.za>
References: <20070118113223.DB070163C0@mail.accesstel.co.za>
Message-ID: <5d8e35a70701180409w7091c353k1b3779699d506f3a@mail.gmail.com>

You assign s as an integer... it should be a float to get the right
result...

So either define s as

s = 14105.0

or as

s = float(14105)

it'll then result in the right answer :

In [17]: s=14105.0
In [18]: s/1024
Out[18]: 13.7744140625

In [19]: s = float(14105)
In [20]: s/1024
Out[20]: 13.7744140625

HTH - Geofram

On 1/18/07, Johan Geldenhuys <johan at accesstel.co.za> wrote:
>
>  Hi all,
>
> In my script I want to convert 14105 bytes to kilobytes and and this is
> what I do:
>
> >>> s = 14105
> >>> print '%0.2f' % (s/1024)
> 13.00
>
> This not correct and I don't know why. The answer is 13.77.
>
> Any pointers please that would help my in the right direction?
>
> Thanks
>
> Johan
>
> --
> No virus found in this outgoing message.
> Checked by AVG Free Edition.
> Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date:
> 2007/01/16 04:36 PM
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070118/313ad464/attachment.html 

From geoframer at gmail.com  Thu Jan 18 13:14:02 2007
From: geoframer at gmail.com (Geoframer)
Date: Thu, 18 Jan 2007 13:14:02 +0100
Subject: [Tutor] Division doesn't work
In-Reply-To: <5d8e35a70701180409w7091c353k1b3779699d506f3a@mail.gmail.com>
References: <20070118113223.DB070163C0@mail.accesstel.co.za>
	<5d8e35a70701180409w7091c353k1b3779699d506f3a@mail.gmail.com>
Message-ID: <5d8e35a70701180414w22af9f84pff0c3f7b4892fc57@mail.gmail.com>

Or actually an even easier way is to just to divide bij a float and the end
result will also be a float.

So in your case divide bij 1024.0  ;-)

In [21]: s=14105

In [22]: s/1024.0
Out[22]: 13.7744140625

HTH - Geofram


On 1/18/07, Geoframer <geoframer at gmail.com> wrote:
>
> You assign s as an integer... it should be a float to get the right
> result...
>
> So either define s as
>
> s = 14105.0
>
> or as
>
> s = float(14105)
>
> it'll then result in the right answer :
>
> In [17]: s=14105.0
> In [18]: s/1024
> Out[18]: 13.7744140625
>
> In [19]: s = float(14105)
> In [20]: s/1024
> Out[20]: 13.7744140625
>
> HTH - Geofram
>
> On 1/18/07, Johan Geldenhuys <johan at accesstel.co.za> wrote:
>
> >  Hi all,
> >
> > In my script I want to convert 14105 bytes to kilobytes and and this is
> > what I do:
> >
> > >>> s = 14105
> > >>> print '%0.2f' % (s/1024)
> > 13.00
> >
> > This not correct and I don't know why. The answer is 13.77.
> >
> > Any pointers please that would help my in the right direction?
> >
> > Thanks
> >
> > Johan
> >
> > --
> > No virus found in this outgoing message.
> > Checked by AVG Free Edition.
> > Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date:
> > 2007/01/16 04:36 PM
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070118/b41cb037/attachment.htm 

From johan at accesstel.co.za  Thu Jan 18 13:16:36 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Thu, 18 Jan 2007 14:16:36 +0200
Subject: [Tutor] Division doesn't work
In-Reply-To: <5d8e35a70701180409w7091c353k1b3779699d506f3a@mail.gmail.com>
Message-ID: <20070118121103.49A3D16302@mail.accesstel.co.za>

Thanks at lot. Something as simple as that...
 
J

   _____  

From: Geoframer [mailto:geoframer at gmail.com] 
Sent: 18 January 2007 02:10 PM
To: Johan Geldenhuys
Cc: tutor at python.org
Subject: Re: [Tutor] Division doesn't work


You assign s as an integer... it should be a float to get the right
result...

So either define s as 

s = 14105.0

or as

s = float(14105)

it'll then result in the right answer :

In [17]: s=14105.0
In [18]: s/1024
Out[18]: 13.7744140625

In [19]: s = float(14105)
In [20]: s/1024
Out[20]: 13.7744140625

HTH - Geofram


On 1/18/07, Johan Geldenhuys <HYPERLINK
"mailto:johan at accesstel.co.za"johan at accesstel.co.za> wrote: 

Hi all,
 
In my script I want to convert 14105 bytes to kilobytes and and this is what
I do:
 
>>> s = 14105
>>> print '%0.2f' % (s/1024)
13.00 
 
This not correct and I don't know why. The answer is 13.77.
 
Any pointers please that would help my in the right direction?
 
Thanks
 
Johan



--
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date: 2007/01/16
04:36 PM



_______________________________________________
Tutor maillist  -  HYPERLINK "mailto:Tutor at python.org"Tutor at python.org
HYPERLINK "http://mail.python.org/mailman/listinfo/tutor"
\nhttp://mail.python.org/mailman/listinfo/tutor






--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date: 2007/01/16
04:36 PM



-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date: 2007/01/16
04:36 PM
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070118/014b0252/attachment.html 

From paulino1_at_sapo.pt at .SYNTAX-ERROR  Thu Jan 18 14:08:32 2007
From: paulino1_at_sapo.pt at .SYNTAX-ERROR (Paulino)
Date: Thu, 18 Jan 2007 13:08:32 +0000
Subject: [Tutor] Redirect from a CGI script
Message-ID: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt>

How can i redirect to another URL from a python CGI script.

Is's suposed to be as simply as:

print "Location : http://newurl "
It's not working.

this simple code does't work - <redir.pyw>
'print "Content-Type:text/html\n\n"
'print "Location : /cgi-bin/ecodiv.pyw "
'print

I use CGIHTTPServer, the server script is as follows:

'from BaseHTTPServer import HTTPServer
'from CGIHTTPServer import CGIHTTPRequestHandler
'HTTPServer(("localhost", 80), CGIHTTPRequestHandler).serve_forever()

instead of redirecting, it only prints 'Location : /cgi-bin/ecodiv.pyw' inthe
browser

Paulino


___________________________________________________________________

O SAPO j? est? livre de v?rus com a Panda Software, fique voc? tamb?m!
Clique em: http://antivirus.sapo.pt


From andreengels at gmail.com  Thu Jan 18 14:26:48 2007
From: andreengels at gmail.com (Andre Engels)
Date: Thu, 18 Jan 2007 14:26:48 +0100
Subject: [Tutor] Redirect from a CGI script
In-Reply-To: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt>
References: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt>
Message-ID: <6faf39c90701180526x74c9ce20v3d7e59a6b2983fc9@mail.gmail.com>

2007/1/18, Paulino <paulino1_at_sapo.pt at .syntax-error>:
>
> How can i redirect to another URL from a python CGI script.
>
> Is's suposed to be as simply as:
>
> print "Location : http://newurl "
> It's not working.
>
> this simple code does't work - <redir.pyw>
> 'print "Content-Type:text/html\n\n"
> 'print "Location : /cgi-bin/ecodiv.pyw "
> 'print
>
> I use CGIHTTPServer, the server script is as follows:
>
> 'from BaseHTTPServer import HTTPServer
> 'from CGIHTTPServer import CGIHTTPRequestHandler
> 'HTTPServer(("localhost", 80), CGIHTTPRequestHandler).serve_forever()
>
> instead of redirecting, it only prints 'Location : /cgi-bin/ecodiv.pyw'
> inthe
> browser



I haven't tested it, but I think I had a similar error recently, and that
was solved by removing the \n\n at the end of the Content-Type line. You
could try that.




-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070118/66d73d74/attachment.htm 

From kent37 at tds.net  Thu Jan 18 14:32:23 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 18 Jan 2007 08:32:23 -0500
Subject: [Tutor] Division doesn't work
In-Reply-To: <20070118113223.DB070163C0@mail.accesstel.co.za>
References: <20070118113223.DB070163C0@mail.accesstel.co.za>
Message-ID: <45AF76E7.20706@tds.net>

Johan Geldenhuys wrote:
> Hi all,
>  
> In my script I want to convert 14105 bytes to kilobytes and and this is 
> what I do:
>  
>> >> s = 14105
>> >> print '%0.2f' % (s/1024)
> 13.00 
>  
> This not correct and I don't know why. The answer is 13.77.
>  
> Any pointers please that would help my in the right direction?

As well as the solutions Geofram has given, you can change the behaviour 
of addition like this:

In [2]: from __future__ import division

In [3]: 14105/1024
Out[3]: 13.7744140625

Then the old-style integer division is done with //:
In [4]: 14105//1024
Out[4]: 13

More info here:
http://www.python.org/doc/2.2.3/whatsnew/node7.html

Kent


From kent37 at tds.net  Thu Jan 18 14:37:36 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 18 Jan 2007 08:37:36 -0500
Subject: [Tutor] Redirect from a CGI script
In-Reply-To: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt>
References: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt>
Message-ID: <45AF7820.2080707@tds.net>

Paulino wrote:
> How can i redirect to another URL from a python CGI script.
> 
> Is's suposed to be as simply as:
> 
> print "Location : http://newurl "
> It's not working.
> 
> this simple code does't work - <redir.pyw>
> 'print "Content-Type:text/html\n\n"

Try it without the two extra newlines. A blank line in the output 
signals the end of the HTTP headers and the start of the content, so the 
following line is considered part of the content and is displayed by the 
browser.

Kent

> 'print "Location : /cgi-bin/ecodiv.pyw "
> 'print
> 
> I use CGIHTTPServer, the server script is as follows:
> 
> 'from BaseHTTPServer import HTTPServer
> 'from CGIHTTPServer import CGIHTTPRequestHandler
> 'HTTPServer(("localhost", 80), CGIHTTPRequestHandler).serve_forever()
> 
> instead of redirecting, it only prints 'Location : /cgi-bin/ecodiv.pyw' inthe
> browser
> 
> Paulino
> 
> 
> ___________________________________________________________________
> 
> O SAPO j? est? livre de v?rus com a Panda Software, fique voc? tamb?m!
> Clique em: http://antivirus.sapo.pt
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From me_zara at dea.spamcon.org  Thu Jan 18 14:16:07 2007
From: me_zara at dea.spamcon.org (Zara)
Date: Thu, 18 Jan 2007 14:16:07 +0100
Subject: [Tutor] Division doesn't work
References: <20070118113223.DB070163C0@mail.accesstel.co.za>
	<5d8e35a70701180409w7091c353k1b3779699d506f3a@mail.gmail.com>
Message-ID: <tmsuq21u38338tmbl3s103kstv2mlbptpq@4ax.com>

On Thu, 18 Jan 2007 13:09:48 +0100, Geoframer <geoframer at gmail.com>
wrote:

>You assign s as an integer... it should be a float to get the right
>result...
<...>


Yes, that is the wordt defect of Python: its inability to read
programmer mind and detect the rteal programmer intentions.


Zara


From dyoo at hkn.eecs.berkeley.edu  Thu Jan 18 15:07:01 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 18 Jan 2007 06:07:01 -0800 (PST)
Subject: [Tutor] Division doesn't work
In-Reply-To: <20070118121103.49A3D16302@mail.accesstel.co.za>
References: <20070118121103.49A3D16302@mail.accesstel.co.za>
Message-ID: <Pine.LNX.4.64.0701180601100.27407@hkn.eecs.berkeley.edu>



On Thu, 18 Jan 2007, Johan Geldenhuys wrote:

> Thanks at lot. Something as simple as that...

No, don't feel bad about it: integer division is a bad "gotcha!" in 
Python.  Integer division is known to be suprising, and it'll eventually 
be replaced by true division in Python 3:

     http://www.python.org/dev/peps/pep-0238/

Till then, just tread more careful when using division.  (But you knew 
division was wacky anyway... *grin*)

From wescpy at gmail.com  Thu Jan 18 20:38:17 2007
From: wescpy at gmail.com (wesley chun)
Date: Thu, 18 Jan 2007 11:38:17 -0800
Subject: [Tutor] Beginners
In-Reply-To: <bedebdfb0701172244k5c673215v94c38fb32a8a5e26@mail.gmail.com>
References: <bedebdfb0701171915i397a02bau58dbc2569d81c40e@mail.gmail.com>
	<78b3a9580701172231g2d96badbg6be12b6ec4877653@mail.gmail.com>
	<bedebdfb0701172244k5c673215v94c38fb32a8a5e26@mail.gmail.com>
Message-ID: <78b3a9580701181138t73212f2as5764d04ab892112d@mail.gmail.com>

> I dont have any programming background, i know only c language.


you say you don't have any programming experience but that you know
C... i'm not sure what you mean by that.  how many years have you been
using C?

From hugonz-lists at h-lab.net  Thu Jan 18 21:10:36 2007
From: hugonz-lists at h-lab.net (=?UTF-8?B?SHVnbyBHb256w6FsZXogTW9udGV2ZXJkZQ==?=)
Date: Thu, 18 Jan 2007 14:10:36 -0600
Subject: [Tutor] Perfect Python web stack?
In-Reply-To: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
Message-ID: <45AFD43C.50901@h-lab.net>

Hi,

Check the thread in the archive. This has been discussed recently.

I have been exploring Django, and since I don't want to go into SQL now, 
I like it. It generates DB code from your model and you don't have to do 
  SQL. It helps to do your app FAST!

But that's just my opinion.

Hugo

OkaMthembo wrote:
> Please help me to decide. I might have asked some of you before, so 
> please bear with me.

From pytutor.20.247ob at spamgourmet.com  Thu Jan 18 21:12:00 2007
From: pytutor.20.247ob at spamgourmet.com (pytutor.20.247ob at spamgourmet.com)
Date: Thu, 18 Jan 2007 20:12:00 +0000 (GMT)
Subject: [Tutor] Correct Way to Start a Python Program Under Linux
Message-ID: <151966.26025.qm@web23402.mail.ird.yahoo.com>

Hi,
Please help I'm at my wits end...

My program comprises of 2 modules and runs a gui written in pygtk2, I
have at the beginning of each:

#!/bin/env python

I made it executable (chmod a+x)

I can run them from a terminal window like

$ /path/to/file.py

this works fine and dandy no probs at all but ultimately I want to
share this program and I want people to launch the program directly
from a menu and not a shell.

now if I create a file launcher on the task bar that points directly to
the same file it runs and seems to be ok except..
my program uses subprocess.Popen({command string}, etc)
and these calls to Popen do not work, only if I run the program from a
shell window.

So am I doing something wrong please tell me? 
I have spent hours and hours debugging and changing the code in
different ways and always the same, I cannot get a subprocess to spawn
into another process unless I run the program from a shell window
,please help!

Wayne.


		
___________________________________________________________ 
What kind of emailer are you? Find out today - get a free analysis of your email personality. Take the quiz at the Yahoo! Mail Championship. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 

From tinoloc at gmail.com  Thu Jan 18 22:15:37 2007
From: tinoloc at gmail.com (Tino Dai)
Date: Thu, 18 Jan 2007 16:15:37 -0500
Subject: [Tutor] Variables of Variables
Message-ID: <e033edfb0701181315k27ce76e5ld742f85a4c65e8fd@mail.gmail.com>

Hi Everybody,

     Is there a way to do variables of variables in python. For example in
perl:

$foo = 'bar'
$$foo = '5'

and $bar will have a value of 5. I have been search high and low for a
simple way to do this in python?

-Thanks,
Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070118/558cdae2/attachment.html 

From john at fouhy.net  Thu Jan 18 22:55:55 2007
From: john at fouhy.net (John Fouhy)
Date: Fri, 19 Jan 2007 10:55:55 +1300
Subject: [Tutor] Variables of Variables
In-Reply-To: <e033edfb0701181315k27ce76e5ld742f85a4c65e8fd@mail.gmail.com>
References: <e033edfb0701181315k27ce76e5ld742f85a4c65e8fd@mail.gmail.com>
Message-ID: <5e58f2e40701181355k22d939c9lcd3b4687222d6f98@mail.gmail.com>

On 19/01/07, Tino Dai <tinoloc at gmail.com> wrote:
> Hi Everybody,
>
>      Is there a way to do variables of variables in python. For example in
> perl:
>
> $foo = 'bar'
> $$foo = '5'
>
> and $bar will have a value of 5. I have been search high and low for a
> simple way to do this in python?

In the context of objects, you can do this with setattr() and getattr().

eg:
>>> class MyClass(object):
...  pass
...
>>> m = MyClass()
>>> m.a = 3
>>> getattr(m, 'a')
3
>>> m.b
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'MyClass' object has no attribute 'b'
>>> setattr(m, 'b', 7)
>>> m.b
7
>>> delattr(m, 'b')
>>> m.b
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'MyClass' object has no attribute 'b'

Obviously, anywhere you see a string in that example, you could
substitute a variable with a string value.

You can't do this if you aren't working with objects.
(well, maybe you could if you used some black magic.. but you should
generally avoid that)

However, the other question you should ask yourself is: should you be
using a dictionary instead?  Rather than storing your data as
variables, you could store it in a dictionary.  Then you can
dynamically access data however you like..

-- 
John.

From dyoo at hkn.eecs.berkeley.edu  Fri Jan 19 00:20:03 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 18 Jan 2007 15:20:03 -0800 (PST)
Subject: [Tutor] Variables of Variables
In-Reply-To: <5e58f2e40701181355k22d939c9lcd3b4687222d6f98@mail.gmail.com>
References: <e033edfb0701181315k27ce76e5ld742f85a4c65e8fd@mail.gmail.com>
	<5e58f2e40701181355k22d939c9lcd3b4687222d6f98@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0701181514020.4796@hkn.eecs.berkeley.edu>

> Rather than storing your data as variables, you could store it in a 
> dictionary.  Then you can dynamically access data however you like..

Suggesting a dictionary here is right.

The technique in the original poster's question is deprecated and widely 
known to be a Bad Idea in Perl.  See Mark Jason Dominus's "Why it's stupid 
to use a variable as a variable name':

     http://perl.plover.com/varvarname.html

So trying to simulate soft references in Python is damaging: we should do 
what we can to keep the idea from propagating.  *grin*

From alan.gauld at btinternet.com  Fri Jan 19 00:59:50 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 18 Jan 2007 23:59:50 -0000
Subject: [Tutor] Perfect Python web stack?
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
Message-ID: <eop1lp$ksa$1@sea.gmane.org>


"OkaMthembo" <zebra05 at gmail.com> wrote

> Please help me to decide. I might have asked some
> of you before, so please bear with me.
>
> I want to build a database driven python web app
> and i need to decide, so please vote on the best
> components

"Best" will depend on many things. For the database itself that
would be including things like:
1) How busy the site will be - transaction volumes
2) Your past experience
3) Your development environment
4) The sophistication of your queries
5) The variety of your data types
6) Your need for other access to the database
    - eg MIS reporting packages, backup facilities,
      client-server access etc

> 1) MySQL vs PostGRES

Postgres gets better write ups from database afficianados
but MySql has a big following. Personally I use either sqlite
for small jobs or Interbase (aka FireBird as freeware) for more 
complex jobs.

> 2) Lighttpd + FastCGI vs Apache + mod_python

No experience of any of these. Lighttpd looks interesting
though.

> 3) Pylons + Cheetah + Kid/Mochikit/Dojo vs Django/Turbogears

Don't know Pylons but Cheetah/Kid/Mochikit are all part
of TurboGears which i am using and so far finding quite
easy and intuitive. I chose TurboGears over Django primarily
because I like its modular "best of breed" approach and
on my initial look I preferred the style of the Kid templates
to the Django ones...

No expert, but HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Fri Jan 19 01:05:33 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 19 Jan 2007 00:05:33 -0000
Subject: [Tutor] Perfect Python web stack?
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com><45AE3C0E.6010402@tds.net>
	<20070117192100.GA26119@cutter.rexx.com>
Message-ID: <eop20g$m1v$1@sea.gmane.org>


"Dave Kuhlman" <dkuhlman at rexx.com> wrote

> I'm currently learning Pylons.  The tutorials for Pylons discuss
> two object-relational mappers for Python: SQLObject and SQLAlchemy.
> If you want to view your database from a higher, more abstract
> level, you might want to look at them, too.

FWIW.

Both of these are standard in TurboGears too.

SQL Alchemy seems to get the expert users vote. SQLObjects seems
to be older and works OK for the simple stuff I've been playing with
so far.

Alan G. 



From Barry.Carroll at psc.com  Fri Jan 19 01:08:41 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Thu, 18 Jan 2007 16:08:41 -0800
Subject: [Tutor] Telepathic Python (was: Division doesn't work)
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A8F@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> Date: Thu, 18 Jan 2007 14:16:07 +0100
> From: Zara <me_zara at dea.spamcon.org>
> Subject: Re: [Tutor] Division doesn't work
> To: tutor at python.org
> Message-ID: <tmsuq21u38338tmbl3s103kstv2mlbptpq at 4ax.com>
> Content-Type: text/plain; charset=us-ascii
> 
> On Thu, 18 Jan 2007 13:09:48 +0100, Geoframer <geoframer at gmail.com>
> wrote:
> 
> >You assign s as an integer... it should be a float to get the right
> >result...
> <...>
> 
> 
> Yes, that is the wordt defect of Python: its inability to read
> programmer mind and detect the rteal programmer intentions.
> 
> 
> Zara
Hi, Zara.

All programming languages seem to share that drawback, as do all
computing machines.  They always do exactly what we tell them to do,
instead of what we want to do.  Drat!

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




From alan.gauld at btinternet.com  Fri Jan 19 01:18:46 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 19 Jan 2007 00:18:46 -0000
Subject: [Tutor] What is a mixin class?
References: <eolnmg$epm$1@sea.gmane.org>
Message-ID: <eop2p9$odt$1@sea.gmane.org>


"Don Taylor" <nospamformeSVP at gmail.com> wrote

>I have a vague idea what a mixin class is, I would like to get a 
>better
> handle on it.

The mixin style of OOP comes from the old (1970's vintage) Flavors
version of Lisp. In Flavors the metaphor was to start with the Vanilla
flavor and mix-in other flavours as you needed.

In Flavors it was common to define lots of small abstract classes
(mixins) and then the application xclass would inherit from as
many mixins as needed. I have seen classes with as many
as 30 or more mixins and absolutely no methods of their own,
they were all inherited.

For this style to work well requires that mixins are type neutral.
Or more specifically they use "Duck Typing", or are protocol based.
That makes languages like Python natural homes for mixins.

Although mixins can inherit from other base classes it is
traditional that they stand alone so that thee is no risk of
double inheritance of a base class and subsequent confusion
in the class dispatch table.

Mixins are particularly uiseful as a way to add common functionality
to groups of classes that are otherwise not related in a type 
heirarchy.
Error or Security logging is a common application where you can
simply create logging versions of non logging classes by defining
the logging version to inherit from the original class and the logging
mixin. Once that is done you can use the new class exactly like
the old one and get logging without having to write any new code.

The downside is that the heavy use of mixins can be confusing
to debug, introduce unexpected side effects, introduce unexpected
dependency loops and spread bugs across lots of classes - making
them hard to pin down...

> I guess that because of multiple inheritance Python does not need a
> formal way of specifying mixin classes so I presume that there is 
> some
> conventional interpretation/coding that is followed for mixin 
> classes.

The original mixins were simply abstract classes in Lisp. Modern
languages wishing to use the concept sometimes add explicit
support for mixin type classes, or more usually just rely on
conventions - such as expecting them to be pure abstract classes.

> So, what constitutes a mixin class and what are the conventional 
> ways to
> denote them in code?

Normally I just mention that its intended as a mixin in the doc 
string.
Mixin programming is really more a style of OO programming
using multiple inheritance rather than anything special about
the classes themselves.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Fri Jan 19 01:27:45 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 19 Jan 2007 00:27:45 -0000
Subject: [Tutor] Correct Way to Start a Python Program Under Linux
References: <151966.26025.qm@web23402.mail.ird.yahoo.com>
Message-ID: <eop3a4$pq4$1@sea.gmane.org>


<pytutor.20.247ob at spamgourmet.com> wrote

> I can run them from a terminal window like
>
> $ /path/to/file.py
>
> this works fine and dandy no probs at all but ultimately I want to
> share this program and I want people to launch the program directly
> from a menu and not a shell.

That should be straightforward too.

> now if I create a file launcher on the task bar that points directly 
> to
> the same file it runs and seems to be ok except..

I'm not sure what you mean by a filelauncher.
In my window manager I just add the file path to my menu
by editing a dialog box or config file. which environment are you 
using?

> my program uses subprocess.Popen({command string}, etc)
> and these calls to Popen do not work, only if I run the program from 
> a
> shell window.

How do you know it doesn't work? Do you get an error or just silence?
If you launch a program that writes to stdout then you had better
be sure it has a stdout to write to! Are you sure its not just
dumping its output to /dev/null? OTOH it could also be that the import
path is not set correctly(try checking your PYTHONPATH environment
variable)
Can you give us a bit more info about what you mean by the
statement that it doesn't work?

> So am I doing something wrong please tell me?

It sounds like it should be OK, but we need a bit more info
as above...

As a check try writing a very simple program with no external
dependencies and see if it works...


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From zebra05 at gmail.com  Fri Jan 19 13:44:57 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Fri, 19 Jan 2007 14:44:57 +0200
Subject: [Tutor] Perfect Python web stack?
In-Reply-To: <eop20g$m1v$1@sea.gmane.org>
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
	<45AE3C0E.6010402@tds.net> <20070117192100.GA26119@cutter.rexx.com>
	<eop20g$m1v$1@sea.gmane.org>
Message-ID: <c7c6f3bc0701190444g56632892k691d14e65db032b6@mail.gmail.com>

Thanks folks,
Just to add a bit of chaos :-)...i am settled on using Quicksilver:
http://www.quicksilver.net
I guess with so many frameworks out there, it all boils down to specific
implementations and
how much rolling their own one can do.

I hope to benchmark Quicksilver performance and i'll report back.

Happy coding,
"Shortash"

On 1/19/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>
> "Dave Kuhlman" <dkuhlman at rexx.com> wrote
>
> > I'm currently learning Pylons.  The tutorials for Pylons discuss
> > two object-relational mappers for Python: SQLObject and SQLAlchemy.
> > If you want to view your database from a higher, more abstract
> > level, you might want to look at them, too.
>
> FWIW.
>
> Both of these are standard in TurboGears too.
>
> SQL Alchemy seems to get the expert users vote. SQLObjects seems
> to be older and works OK for the simple stuff I've been playing with
> so far.
>
> Alan G.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070119/5aaa86b2/attachment.html 

From miago.python at gmail.com  Fri Jan 19 14:19:24 2007
From: miago.python at gmail.com (Karl Wittgenstein)
Date: Fri, 19 Jan 2007 11:19:24 -0200
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
Message-ID: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>

Dear Smart Caring Dude,
I've been dabbling into Python for about 6 weeks now.I'm a Social Sciences
student who just got interested in programming and chose Python as first
language.I have little time to practice and I am just getting into
programming concepts,so please be patient,in case you are so kind as to
enlighten this poor soul.
I am trying to write this program which should compare values that are set
by the program  through user's choice to values that the user enters on a
prompt.I use SPE on windows xp,and it tells me that there are indentation
erros on the definitions.Isn't it legal to start a new block of code when
starting a definition?And how come it returns 'variable' not defined,when
they are defined by the = ??Should i make them global?
I would be very grateful to the patient soul that answers these questions,as
my learning interest is sincere and the knowledge sources so disperse.
Here goes the code:

#Ok,this is supposed to be a 2 option choice between values 1 and 4,
#i want the value to determine the variable values inside the function
def porao():
    porao = raw_input()
    if porao == 1 :
        global altura_aeronave = 111
        global largura_aeronave = 112
        global comprimento = 211
    elif porao == 4:
       global altura_aeronave = 112
       global largura_aeronave = 113
       global comprimento = 212
    else:
        print "Por?o inexistente"
#These three functions were supposed to get input from user so it can be
compared
#with the values determinated(determined?)above
def largura():
   global largura=input()
def altura():
   global altura=input()
def comprimento():
   global comprimento = input()
#These are the comparison functions
def largura_compativel ():
    if not largura <= largura_aeronave:
        print 'Volume largo demais!'
def altura_compativel ():
    if not altura <= altura_aeronave:
        print 'Volume alto demais!'
def comprimento_compativel ():
    if not comprimento<=comprimento_aeronave:
        print 'Volume comprido demais!'
#Try to run this damn thing,man!!!!!1
porao()
largura()
altura()
comprimento()
largura_compativel()
altura_compativel
comprimento_compativel()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070119/12b6f0d9/attachment.htm 

From kent37 at tds.net  Fri Jan 19 14:26:46 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 19 Jan 2007 08:26:46 -0500
Subject: [Tutor] Perfect Python web stack?
In-Reply-To: <c7c6f3bc0701190444g56632892k691d14e65db032b6@mail.gmail.com>
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>	<45AE3C0E.6010402@tds.net>
	<20070117192100.GA26119@cutter.rexx.com>	<eop20g$m1v$1@sea.gmane.org>
	<c7c6f3bc0701190444g56632892k691d14e65db032b6@mail.gmail.com>
Message-ID: <45B0C716.1000908@tds.net>

OkaMthembo wrote:
> Thanks folks,
> Just to add a bit of chaos :-)...i am settled on using Quicksilver: 
> http://www.quicksilver.net

Is that the right URL? It doesn't work for me.

Kent


From geoframer at gmail.com  Fri Jan 19 15:00:52 2007
From: geoframer at gmail.com (Geoframer)
Date: Fri, 19 Jan 2007 15:00:52 +0100
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
Message-ID: <5d8e35a70701190600i289be9d8y996ea20afad25680@mail.gmail.com>

Alright this code is actually littered with bugs, but don't feel bad,
because as you state you are new to the whole programming thing. I'll try to
explain the things i see going wrong (please take into account that i'm also
a new pythonist ;-))

***
You get the error 'variable undefined' because you are declaring a global in
an incorrect manner. The correct manner is to define the variable in the
global scope then start a definition, declare that you are using a global
variable and then assign it. Like this :

bla = 'Hello world'

def func():
    global bla
    print bla
***
If you do :
porao = raw_input()
You'll define the integer value as a string, not an integer. If you are sure
that only an integer will be entered use input() (slower) or
int(raw_input()). In either case you should use try and except clauses more
in your code because if not a 1 or 4 is entered your code will continue
without having the variables declared! Leading to other errors.
***
Now suppose you get the definitions using globals correct then you'll get
new errors stating that an 'int' is not callable.
This happens because you define for example altura as an integer and then
also define a function called altura. If you now use :
altura()
It'll try to call the integer object and will fail.
Easy solution would be to make the function something like alturadef()
***
As for your identation you should use consistent identation... I suggest
using python -t or python -tt to compile your script and it will give
warnings/errors where the identation goes wrong.
***
Here's how i altered your code (quick and dirty probably, it should be more
clean using try and except clauses and what not) to get it to work but you
can probably better look that up in a python book and then return to the
list if you don't understand it :

#Ok,this is supposed to be a 2 option choice between values 1 and 4,
#i want the value to determine the variable values inside the function

altura_aeronave = 0
largura_aeronave = 0
comprimento_aeronave = 0
comprimento = 0
largura = 0
altura = 0

def porao():
    global altura_aeronave, largura_aeronave, comprimento
    porao = input()
    if porao == 1 :
        altura_aeronave = 111
        largura_aeronave = 112
        comprimento = 211
    elif porao == 4:
        altura_aeronave = 112
        largura_aeronave = 113
        comprimento = 212
    else:
        print "Por?o inexistente"

#These three functions were supposed to get input from user so it can be
compared
#with the values determinated(determined?)above
def larguradef():
    global largura
    largura=input()

def alturadef():
    global altura
    altura=input()

def comprimentodef():
    global comprimento
    comprimento = input()

#These are the comparison functions
def largura_compativel ():
    global largura, largura_aeronave
    if not largura <= largura_aeronave:
        print 'Volume largo demais!'

def altura_compativel ():
    global altura, altura_aeronave
    if not altura <= altura_aeronave:
        print 'Volume alto demais!'

def comprimento_compativel ():
    global comprimento, comprimento_aeronave
    if not comprimento<=comprimento_aeronave:
        print 'Volume comprido demais!'

#Try to run this damn thing,man!!!!!1
porao()
#print altura_aeronave, largura_aeronave, comprimento
larguradef()
alturadef()
comprimentodef()
largura_compativel()
altura_compativel
comprimento_compativel()








On 1/19/07, Karl Wittgenstein <miago.python at gmail.com> wrote:
>
> Dear Smart Caring Dude,
> I've been dabbling into Python for about 6 weeks now.I'm a Social Sciences
> student who just got interested in programming and chose Python as first
> language.I have little time to practice and I am just getting into
> programming concepts,so please be patient,in case you are so kind as to
> enlighten this poor soul.
> I am trying to write this program which should compare values that are set
> by the program  through user's choice to values that the user enters on a
> prompt.I use SPE on windows xp,and it tells me that there are indentation
> erros on the definitions.Isn't it legal to start a new block of code when
> starting a definition?And how come it returns 'variable' not defined,when
> they are defined by the = ??Should i make them global?
> I would be very grateful to the patient soul that answers these
> questions,as my learning interest is sincere and the knowledge sources so
> disperse.
> Here goes the code:
>
> #Ok,this is supposed to be a 2 option choice between values 1 and 4,
> #i want the value to determine the variable values inside the function
> def porao():
>     porao = raw_input()
>     if porao == 1 :
>         global altura_aeronave = 111
>         global largura_aeronave = 112
>         global comprimento = 211
>     elif porao == 4:
>        global altura_aeronave = 112
>        global largura_aeronave = 113
>        global comprimento = 212
>     else:
>         print "Por?o inexistente"
> #These three functions were supposed to get input from user so it can be
> compared
> #with the values determinated(determined?)above
> def largura():
>    global largura=input()
> def altura():
>    global altura=input()
> def comprimento():
>    global comprimento = input()
> #These are the comparison functions
> def largura_compativel ():
>     if not largura <= largura_aeronave:
>         print 'Volume largo demais!'
> def altura_compativel ():
>     if not altura <= altura_aeronave:
>         print 'Volume alto demais!'
> def comprimento_compativel ():
>     if not comprimento<=comprimento_aeronave:
>         print 'Volume comprido demais!'
> #Try to run this damn thing,man!!!!!1
> porao()
> largura()
> altura()
> comprimento()
> largura_compativel()
> altura_compativel
> comprimento_compativel()
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070119/c7a34067/attachment-0001.htm 

From zebra05 at gmail.com  Fri Jan 19 15:13:50 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Fri, 19 Jan 2007 16:13:50 +0200
Subject: [Tutor] Perfect Python web stack?
In-Reply-To: <45B0C716.1000908@tds.net>
References: <c7c6f3bc0701170258x47766684n2d81704b2d1d59e9@mail.gmail.com>
	<45AE3C0E.6010402@tds.net> <20070117192100.GA26119@cutter.rexx.com>
	<eop20g$m1v$1@sea.gmane.org>
	<c7c6f3bc0701190444g56632892k691d14e65db032b6@mail.gmail.com>
	<45B0C716.1000908@tds.net>
Message-ID: <c7c6f3bc0701190613r3302c503hc9d3972c3ba05493@mail.gmail.com>

Im thoroughly embarrassed. its http://www.clearsilver.net and not
quicksilver as i said earlier.

thanks Kent.

"Shortash"

On 1/19/07, Kent Johnson <kent37 at tds.net> wrote:
>
> OkaMthembo wrote:
> > Thanks folks,
> > Just to add a bit of chaos :-)...i am settled on using Quicksilver:
> > http://www.quicksilver.net
>
> Is that the right URL? It doesn't work for me.
>
> Kent
>
>


-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070119/13c68998/attachment.html 

From sanelson at gmail.com  Fri Jan 19 15:16:23 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Fri, 19 Jan 2007 14:16:23 +0000
Subject: [Tutor] Getting GID info
Message-ID: <b6131fdc0701190616q408adbdgaaf6467194519673@mail.gmail.com>

Hello all,

I want to produce stats on file ownership.  I am aware that I can use
stat to obtain a file statistics tuple, and with the pwd method I can
convert the UID to username.  However, is there a similar method that
will tell me that GID 1 == "staff"?

S.

From sanelson at gmail.com  Fri Jan 19 15:23:10 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Fri, 19 Jan 2007 14:23:10 +0000
Subject: [Tutor] Getting GID info
In-Reply-To: <b6131fdc0701190616q408adbdgaaf6467194519673@mail.gmail.com>
References: <b6131fdc0701190616q408adbdgaaf6467194519673@mail.gmail.com>
Message-ID: <b6131fdc0701190623y36e5094cga4d078af9879bc8@mail.gmail.com>

On 1/19/07, Steve Nelson <sanelson at gmail.com> wrote:
> Hello all,
>
> I want to produce stats on file ownership.  I am aware that I can use
> stat to obtain a file statistics tuple, and with the pwd method I can
> convert the UID to username.  However, is there a similar method that
> will tell me that GID 1 == "staff"?

Hrm... and an inspired guess.... import grp.... is what I needed.

> S.

S.

From sanelson at gmail.com  Fri Jan 19 15:35:48 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Fri, 19 Jan 2007 14:35:48 +0000
Subject: [Tutor] Filesystem Usage
In-Reply-To: <b6131fdc0609220239y1655f743n783368bf9ab77198@mail.gmail.com>
References: <b6131fdc0609210318w523a7886g62a1b050b374435@mail.gmail.com>
	<78b3a9580609212303r4c04a799uaec4b166c7f95668@mail.gmail.com>
	<b6131fdc0609220239y1655f743n783368bf9ab77198@mail.gmail.com>
Message-ID: <b6131fdc0701190635m4582d6d6if2e79133c5a34db8@mail.gmail.com>

On 9/22/06, Steve Nelson <sanelson at gmail.com> wrote:

> In the end I just did:
>
> def fsUsage(dir):
>   """Returns the % usage of a given filesystem"""
>   stat = os.statvfs(dir)
>   from statvfs import F_BLOCKS, F_BFREE
>   total = stat[F_BLOCKS]
>   avail = stat[F_BFREE]
>   used = total-avail
>   percent = used/total*100
>   return percent

Can someone explain how I manged to import F_BLOCKS and F_BFREE?

I want to do the same with pwd and grp:

>>> gstat = grp.getgrgid(1)
>>> dir(gstat)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__',
'__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmul__', '__setattr__', '__str__', 'gr_gid', 'gr_mem',
'gr_name', 'gr_passwd', 'n_fields', 'n_sequence_fields',
'n_unnamed_fields']

>>> gstat[0]
'staff'
>>> gstat[GR_GID]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'GR_GID' is not defined

What's the difference?

It just seems that specifying the location in the tuple is not very
clear or self-documenting, and using GR_GID is better.

S.
> S.
> >
> > hope this helps a little!
> > -- wesley
> > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> > "Core Python Programming", Prentice Hall, (c)2007,2001
> >     http://corepython.com
> >
> > wesley.j.chun :: wescpy-at-gmail.com
> > python training and technical consulting
> > cyberweb.consulting : silicon valley, ca
> > http://cyberwebconsulting.com
> >
>

From kent37 at tds.net  Fri Jan 19 15:55:44 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 19 Jan 2007 09:55:44 -0500
Subject: [Tutor] Filesystem Usage
In-Reply-To: <b6131fdc0701190635m4582d6d6if2e79133c5a34db8@mail.gmail.com>
References: <b6131fdc0609210318w523a7886g62a1b050b374435@mail.gmail.com>	<78b3a9580609212303r4c04a799uaec4b166c7f95668@mail.gmail.com>	<b6131fdc0609220239y1655f743n783368bf9ab77198@mail.gmail.com>
	<b6131fdc0701190635m4582d6d6if2e79133c5a34db8@mail.gmail.com>
Message-ID: <45B0DBF0.7040004@tds.net>

Steve Nelson wrote:
> On 9/22/06, Steve Nelson <sanelson at gmail.com> wrote:
> 
>> In the end I just did:
>>
>> def fsUsage(dir):
>>   """Returns the % usage of a given filesystem"""
>>   stat = os.statvfs(dir)
>>   from statvfs import F_BLOCKS, F_BFREE
>>   total = stat[F_BLOCKS]
>>   avail = stat[F_BFREE]
>>   used = total-avail
>>   percent = used/total*100
>>   return percent
> 
> Can someone explain how I manged to import F_BLOCKS and F_BFREE?

With the statement
   from statvfs import F_BLOCKS, F_BFREE
> 
> I want to do the same with pwd and grp:
> 
>>>> gstat = grp.getgrgid(1)
>>>> dir(gstat)
> ['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
> '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__',
> '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
> '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
> '__repr__', '__rmul__', '__setattr__', '__str__', 'gr_gid', 'gr_mem',
> 'gr_name', 'gr_passwd', 'n_fields', 'n_sequence_fields',
> 'n_unnamed_fields']
> 
>>>> gstat[0]
> 'staff'
>>>> gstat[GR_GID]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'GR_GID' is not defined

Try gstat.gr_gid, etc
> 
> What's the difference?

F_BLOCKS is an attribute of the statvfs module; it is a constant giving 
the offset into the stats structure.

gr_gid is an attribute of the gstat object, it is the actual value that 
you want.

The objects returned by statvfs and getgrgid are unusual in that their 
attributes can be accessed in two ways, as list values and as object 
attributes.

The list-like access uses brackets [] and an index. In the case of 
statvfs, the constants are named in the statvfs module; in the case of 
getgrgid() there don't seem to be symbolic names available.

The attribute access uses . notation and an attribute name. You can do 
stat.f_blocks and gstat.gr_gid. Python takes care of looking up the 
actual attribute value.

I suggest you use the attribute form for both, it is more compact and 
readable, consistent between both types of objects, and doesn't require 
the import of statvfs.

Kent


From sanelson at gmail.com  Fri Jan 19 16:02:55 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Fri, 19 Jan 2007 15:02:55 +0000
Subject: [Tutor] Filesystem Usage
In-Reply-To: <45B0DBF0.7040004@tds.net>
References: <b6131fdc0609210318w523a7886g62a1b050b374435@mail.gmail.com>
	<78b3a9580609212303r4c04a799uaec4b166c7f95668@mail.gmail.com>
	<b6131fdc0609220239y1655f743n783368bf9ab77198@mail.gmail.com>
	<b6131fdc0701190635m4582d6d6if2e79133c5a34db8@mail.gmail.com>
	<45B0DBF0.7040004@tds.net>
Message-ID: <b6131fdc0701190702p69aedb29id8f9535c423b6200@mail.gmail.com>

On 1/19/07, Kent Johnson <kent37 at tds.net> wrote:

> The attribute access uses . notation and an attribute name. You can do
> stat.f_blocks and gstat.gr_gid. Python takes care of looking up the
> actual attribute value.

Excellent - thank you.

> I suggest you use the attribute form for both, it is more compact and
> readable, consistent between both types of objects, and doesn't require
> the import of statvfs.

Done.

> Kent

S.

From geoframer at gmail.com  Fri Jan 19 16:07:23 2007
From: geoframer at gmail.com (Geoframer)
Date: Fri, 19 Jan 2007 16:07:23 +0100
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <5d8e35a70701190600i289be9d8y996ea20afad25680@mail.gmail.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
	<5d8e35a70701190600i289be9d8y996ea20afad25680@mail.gmail.com>
Message-ID: <5d8e35a70701190707g30a25bfaoe3c0902a56ad1d75@mail.gmail.com>

Accidentally the number of function definitions does not help the clarity of
the program, even though it's completely unclear to me what exactly you are
trying to do. :-)
I rewrote your program a bit combining the definition of the functions, the
comparision of the functions and removed the chance that your program goes
on the define/compare values that have not been defined.

*** Insert redone code ***
altura_aeronave = 0
largura_aeronave = 0
comprimento_aeronave = 0
comprimento = 0
largura = 0
altura = 0

def compativel():
    global altura, altura_aeronave, comprimento, comprimento_aeronave, \
           largura, largura_aeronave
    if not largura <= largura_aeronave:
        print 'Volume largo demais!'
    elif not altura <= altura_aeronave:
        print 'Volume alto demais!'
    elif not comprimento<=comprimento_aeronave:
        print 'Volume comprido demais!'

def define():
    global largura, altura, comprimento
    largura=input()
    altura=input()
    comprimento=input()

def porao():
    global altura_aeronave, largura_aeronave, comprimento
    porao = input()
    if porao == 1 :
        altura_aeronave = 111
        largura_aeronave = 112
        comprimento = 211
        return 1
    elif porao == 4:
        altura_aeronave = 112
        largura_aeronave = 113
        comprimento = 212
        return 1
    else:
        print "Porao inexistente!"


if porao():
    define()
    compativel()

On 1/19/07, Geoframer <geoframer at gmail.com> wrote:
>
> Alright this code is actually littered with bugs, but don't feel bad,
> because as you state you are new to the whole programming thing. I'll try to
> explain the things i see going wrong (please take into account that i'm also
> a new pythonist ;-))
>
> ***
> You get the error 'variable undefined' because you are declaring a global
> in an incorrect manner. The correct manner is to define the variable in the
> global scope then start a definition, declare that you are using a global
> variable and then assign it. Like this :
>
> bla = 'Hello world'
>
> def func():
>     global bla
>     print bla
> ***
> If you do :
> porao = raw_input()
> You'll define the integer value as a string, not an integer. If you are
> sure that only an integer will be entered use input() (slower) or
> int(raw_input()). In either case you should use try and except clauses more
> in your code because if not a 1 or 4 is entered your code will continue
> without having the variables declared! Leading to other errors.
> ***
> Now suppose you get the definitions using globals correct then you'll get
> new errors stating that an 'int' is not callable.
> This happens because you define for example altura as an integer and then
> also define a function called altura. If you now use :
> altura()
> It'll try to call the integer object and will fail.
> Easy solution would be to make the function something like alturadef()
> ***
> As for your identation you should use consistent identation... I suggest
> using python -t or python -tt to compile your script and it will give
> warnings/errors where the identation goes wrong.
> ***
> Here's how i altered your code (quick and dirty probably, it should be
> more clean using try and except clauses and what not) to get it to work but
> you can probably better look that up in a python book and then return to the
> list if you don't understand it :
>
> #Ok,this is supposed to be a 2 option choice between values 1 and 4,
> #i want the value to determine the variable values inside the function
>
> altura_aeronave = 0
> largura_aeronave = 0
> comprimento_aeronave = 0
> comprimento = 0
> largura = 0
> altura = 0
>
> def porao():
>     global altura_aeronave, largura_aeronave, comprimento
>     porao = input()
>     if porao == 1 :
>         altura_aeronave = 111
>         largura_aeronave = 112
>         comprimento = 211
>     elif porao == 4:
>         altura_aeronave = 112
>         largura_aeronave = 113
>         comprimento = 212
>     else:
>         print "Por?o inexistente"
>
> #These three functions were supposed to get input from user so it can be
> compared
> #with the values determinated(determined?)above
> def larguradef():
>     global largura
>     largura=input()
>
> def alturadef():
>     global altura
>     altura=input()
>
> def comprimentodef():
>     global comprimento
>     comprimento = input()
>
> #These are the comparison functions
> def largura_compativel ():
>     global largura, largura_aeronave
>     if not largura <= largura_aeronave:
>         print 'Volume largo demais!'
>
> def altura_compativel ():
>     global altura, altura_aeronave
>     if not altura <= altura_aeronave:
>         print 'Volume alto demais!'
>
> def comprimento_compativel ():
>     global comprimento, comprimento_aeronave
>     if not comprimento<=comprimento_aeronave:
>         print 'Volume comprido demais!'
>
> #Try to run this damn thing,man!!!!!1
> porao()
> #print altura_aeronave, largura_aeronave, comprimento
> larguradef()
> alturadef()
> comprimentodef()
> largura_compativel()
> altura_compativel
> comprimento_compativel()
>
>
>
>
>
>
>
>
> On 1/19/07, Karl Wittgenstein <miago.python at gmail.com > wrote:
>
> > Dear Smart Caring Dude,
> > I've been dabbling into Python for about 6 weeks now.I'm a Social
> > Sciences student who just got interested in programming and chose Python as
> > first language.I have little time to practice and I am just getting
> > into  programming concepts,so please be patient,in case you are so kind as
> > to enlighten this poor soul.
> > I am trying to write this program which should compare values that are
> > set by the program  through user's choice to values that the user enters on
> > a prompt.I use SPE on windows xp,and it tells me that there are
> > indentation erros on the definitions.Isn't it legal to start a new block
> > of code when starting a definition?And how come it returns 'variable' not
> > defined,when they are defined by the = ??Should i make them global?
> > I would be very grateful to the patient soul that answers these
> > questions,as my learning interest is sincere and the knowledge sources so
> > disperse.
> > Here goes the code:
> >
> > #Ok,this is supposed to be a 2 option choice between values 1 and 4,
> > #i want the value to determine the variable values inside the function
> > def porao():
> >     porao = raw_input()
> >     if porao == 1 :
> >         global altura_aeronave = 111
> >         global largura_aeronave = 112
> >         global comprimento = 211
> >     elif porao == 4:
> >        global altura_aeronave = 112
> >        global largura_aeronave = 113
> >        global comprimento = 212
> >     else:
> >         print "Por?o inexistente"
> > #These three functions were supposed to get input from user so it can be
> > compared
> > #with the values determinated(determined?)above
> > def largura():
> >    global largura=input()
> > def altura():
> >    global altura=input()
> > def comprimento():
> >    global comprimento = input()
> > #These are the comparison functions
> > def largura_compativel ():
> >     if not largura <= largura_aeronave:
> >         print 'Volume largo demais!'
> > def altura_compativel ():
> >     if not altura <= altura_aeronave:
> >         print 'Volume alto demais!'
> > def comprimento_compativel ():
> >     if not comprimento<=comprimento_aeronave:
> >         print 'Volume comprido demais!'
> > #Try to run this damn thing,man!!!!!1
> > porao()
> > largura()
> > altura()
> > comprimento()
> > largura_compativel()
> > altura_compativel
> > comprimento_compativel()
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070119/0ad0974f/attachment.html 

From sanelson at gmail.com  Fri Jan 19 16:15:25 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Fri, 19 Jan 2007 15:15:25 +0000
Subject: [Tutor] MD5 Digest for files
Message-ID: <b6131fdc0701190715x4809b0eds321ef8741c1098f0@mail.gmail.com>

Hello,

I want to create a dictionary of files and md5sums for a given
directory.  It seems, however, that md5 works with strings or
read-only buffers, and can't be passed a file.

What I want to do is something like:

for f is os.listdir("."):
  d[f] = someFunctionThatReturnsMD5Sum(f)

Has this wheel already been invented?  I can't see how to operate on
the file itself.

S.

From geoframer at gmail.com  Fri Jan 19 16:20:59 2007
From: geoframer at gmail.com (Geoframer)
Date: Fri, 19 Jan 2007 16:20:59 +0100
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <5d8e35a70701190707g30a25bfaoe3c0902a56ad1d75@mail.gmail.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
	<5d8e35a70701190600i289be9d8y996ea20afad25680@mail.gmail.com>
	<5d8e35a70701190707g30a25bfaoe3c0902a56ad1d75@mail.gmail.com>
Message-ID: <5d8e35a70701190720h5131817du866e77370e61ab37@mail.gmail.com>

As i stated i'm somewhat new to python myself so i defined the variables  in
a somewhat old fashion manner. The correct code is below. I also added some
comments because i think you defined the wrong variable somewhere also...
Because your code led to comprimento being compared to comprimento_aeronave
which was never defined anywhere, so i took it you ment comprimento_aeronave
there....

This code below is fully functional without any errors (not even identation
warnings ;-) ). So if this doesn't work at your computer something else is
possible wrong. Incidentally if you hit the following sequence : 1 2 3 4.
The program just terminates without a message... You'd have to insert what's
happening in such a case yourself.

**** insert code ****
global altura_aeronave, largura_aeronave, comprimento_aeronave, comprimento,
\
       largura, altura

def compativel():
    global altura, altura_aeronave, comprimento, comprimento_aeronave, \
           largura, largura_aeronave
    if not largura <= largura_aeronave:
        print 'Volume largo demais!'
    elif not altura <= altura_aeronave:
        print 'Volume alto demais!'
    elif not comprimento<=comprimento_aeronave:
        print 'Volume comprido demais!'

def define():
    global largura, altura, comprimento
    largura=input()
    altura=input()
    comprimento=input()

def porao():
    global altura_aeronave, largura_aeronave, comprimento_aeronave
    porao = input()
    if porao == 1 :
        altura_aeronave = 111
        largura_aeronave = 112
        comprimento_aeronave = 211 #You originally had comprimento here?
        return 1
    elif porao == 4:
        altura_aeronave = 112
        largura_aeronave = 113
        comprimento_aeronave = 212 #Same here
        return 1
    else:
        print "Porao inexistente!"


if porao():
    define()
    compativel()

*** end inserted code ***

HTH - Geoframer

On 1/19/07, Geoframer <geoframer at gmail.com> wrote:
>
> Accidentally the number of function definitions does not help the clarity
> of the program, even though it's completely unclear to me what exactly you
> are trying to do. :-)
> I rewrote your program a bit combining the definition of the functions,
> the comparision of the functions and removed the chance that your program
> goes on the define/compare values that have not been defined.
>
> *** Insert redone code ***
> altura_aeronave = 0
> largura_aeronave = 0
> comprimento_aeronave = 0
> comprimento = 0
> largura = 0
> altura = 0
>
> def compativel():
>     global altura, altura_aeronave, comprimento, comprimento_aeronave, \
>            largura, largura_aeronave
>     if not largura <= largura_aeronave:
>         print 'Volume largo demais!'
>     elif not altura <= altura_aeronave:
>         print 'Volume alto demais!'
>     elif not comprimento<=comprimento_aeronave:
>         print 'Volume comprido demais!'
>
> def define():
>     global largura, altura, comprimento
>     largura=input()
>     altura=input()
>     comprimento=input()
>
> def porao():
>     global altura_aeronave, largura_aeronave, comprimento
>     porao = input()
>     if porao == 1 :
>         altura_aeronave = 111
>         largura_aeronave = 112
>         comprimento = 211
>         return 1
>     elif porao == 4:
>         altura_aeronave = 112
>         largura_aeronave = 113
>         comprimento = 212
>         return 1
>     else:
>         print "Porao inexistente!"
>
>
> if porao():
>     define()
>     compativel()
>
> On 1/19/07, Geoframer <geoframer at gmail.com> wrote:
> >
> > Alright this code is actually littered with bugs, but don't feel bad,
> > because as you state you are new to the whole programming thing. I'll try to
> > explain the things i see going wrong (please take into account that i'm also
> > a new pythonist ;-))
> >
> > ***
> > You get the error 'variable undefined' because you are declaring a
> > global in an incorrect manner. The correct manner is to define the variable
> > in the global scope then start a definition, declare that you are using a
> > global variable and then assign it. Like this :
> >
> > bla = 'Hello world'
> >
> > def func():
> >     global bla
> >     print bla
> > ***
> > If you do :
> > porao = raw_input()
> > You'll define the integer value as a string, not an integer. If you are
> > sure that only an integer will be entered use input() (slower) or
> > int(raw_input()). In either case you should use try and except clauses more
> > in your code because if not a 1 or 4 is entered your code will continue
> > without having the variables declared! Leading to other errors.
> > ***
> > Now suppose you get the definitions using globals correct then you'll
> > get new errors stating that an 'int' is not callable.
> > This happens because you define for example altura as an integer and
> > then also define a function called altura. If you now use :
> > altura()
> > It'll try to call the integer object and will fail.
> > Easy solution would be to make the function something like alturadef()
> > ***
> > As for your identation you should use consistent identation... I suggest
> > using python -t or python -tt to compile your script and it will give
> > warnings/errors where the identation goes wrong.
> > ***
> > Here's how i altered your code (quick and dirty probably, it should be
> > more clean using try and except clauses and what not) to get it to work but
> > you can probably better look that up in a python book and then return to the
> > list if you don't understand it :
> >
> > #Ok,this is supposed to be a 2 option choice between values 1 and 4,
> > #i want the value to determine the variable values inside the function
> >
> > altura_aeronave = 0
> > largura_aeronave = 0
> > comprimento_aeronave = 0
> > comprimento = 0
> > largura = 0
> > altura = 0
> >
> > def porao():
> >     global altura_aeronave, largura_aeronave, comprimento
> >     porao = input()
> >     if porao == 1 :
> >         altura_aeronave = 111
> >         largura_aeronave = 112
> >         comprimento = 211
> >     elif porao == 4:
> >         altura_aeronave = 112
> >         largura_aeronave = 113
> >         comprimento = 212
> >     else:
> >         print "Por?o inexistente"
> >
> > #These three functions were supposed to get input from user so it can be
> > compared
> > #with the values determinated(determined?)above
> > def larguradef():
> >     global largura
> >     largura=input()
> >
> > def alturadef():
> >     global altura
> >     altura=input()
> >
> > def comprimentodef():
> >     global comprimento
> >     comprimento = input()
> >
> > #These are the comparison functions
> > def largura_compativel ():
> >     global largura, largura_aeronave
> >     if not largura <= largura_aeronave:
> >         print 'Volume largo demais!'
> >
> > def altura_compativel ():
> >     global altura, altura_aeronave
> >     if not altura <= altura_aeronave:
> >         print 'Volume alto demais!'
> >
> > def comprimento_compativel ():
> >     global comprimento, comprimento_aeronave
> >     if not comprimento<=comprimento_aeronave:
> >         print 'Volume comprido demais!'
> >
> > #Try to run this damn thing,man!!!!!1
> > porao()
> > #print altura_aeronave, largura_aeronave, comprimento
> > larguradef()
> > alturadef()
> > comprimentodef()
> > largura_compativel()
> > altura_compativel
> > comprimento_compativel()
> >
> >
> >
> >
> >
> >
> >
> >
> > On 1/19/07, Karl Wittgenstein < miago.python at gmail.com > wrote:
> >
> > > Dear Smart Caring Dude,
> > > I've been dabbling into Python for about 6 weeks now.I'm a Social
> > > Sciences student who just got interested in programming and chose Python as
> > > first language.I have little time to practice and I am just getting
> > > into  programming concepts,so please be patient,in case you are so kind as
> > > to enlighten this poor soul.
> > > I am trying to write this program which should compare values that are
> > > set by the program  through user's choice to values that the user enters on
> > > a prompt.I use SPE on windows xp,and it tells me that there are
> > > indentation erros on the definitions.Isn't it legal to start a new
> > > block of code when starting a definition?And how come it returns 'variable'
> > > not defined,when they are defined by the = ??Should i make them global?
> > > I would be very grateful to the patient soul that answers these
> > > questions,as my learning interest is sincere and the knowledge sources so
> > > disperse.
> > > Here goes the code:
> > >
> > > #Ok,this is supposed to be a 2 option choice between values 1 and 4,
> > > #i want the value to determine the variable values inside the function
> > > def porao():
> > >     porao = raw_input()
> > >     if porao == 1 :
> > >         global altura_aeronave = 111
> > >         global largura_aeronave = 112
> > >         global comprimento = 211
> > >     elif porao == 4:
> > >        global altura_aeronave = 112
> > >        global largura_aeronave = 113
> > >        global comprimento = 212
> > >     else:
> > >         print "Por?o inexistente"
> > > #These three functions were supposed to get input from user so it can
> > > be compared
> > > #with the values determinated(determined?)above
> > > def largura():
> > >    global largura=input()
> > > def altura():
> > >    global altura=input()
> > > def comprimento():
> > >    global comprimento = input()
> > > #These are the comparison functions
> > > def largura_compativel ():
> > >     if not largura <= largura_aeronave:
> > >         print 'Volume largo demais!'
> > > def altura_compativel ():
> > >     if not altura <= altura_aeronave:
> > >         print 'Volume alto demais!'
> > > def comprimento_compativel ():
> > >     if not comprimento<=comprimento_aeronave:
> > >         print 'Volume comprido demais!'
> > > #Try to run this damn thing,man!!!!!1
> > > porao()
> > > largura()
> > > altura()
> > > comprimento()
> > > largura_compativel()
> > > altura_compativel
> > > comprimento_compativel()
> > >
> > >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> > >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070119/84dd998f/attachment.htm 

From chris.arndt at web.de  Fri Jan 19 17:49:19 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 19 Jan 2007 17:49:19 +0100
Subject: [Tutor] MD5 Digest for files
In-Reply-To: <b6131fdc0701190715x4809b0eds321ef8741c1098f0@mail.gmail.com>
References: <b6131fdc0701190715x4809b0eds321ef8741c1098f0@mail.gmail.com>
Message-ID: <45B0F68F.9090102@web.de>

Steve Nelson schrieb:
> I want to create a dictionary of files and md5sums for a given
> directory.  It seems, however, that md5 works with strings or
> read-only buffers, and can't be passed a file.
> 
> What I want to do is something like:
> 
> for f is os.listdir("."):
>   d[f] = someFunctionThatReturnsMD5Sum(f)
> 
> Has this wheel already been invented?  I can't see how to operate on
> the file itself.

Just open and read in the file and then calculate the MD5 sum from the contents:

import os
import md5

def md5sums_for_dir(directory):
    d = {}
    for fn in os.listdir(directory):
        fp = os.path.join(directory, fn)
        if os.path.isfile(fp):
            try:
                fo = open(fp, 'rb')
            except (IOError, OSError):
                print "Could not open file '%s', skipping..." % fp
                continue
            else:
                fcontent = fo.read()
                digest = md5.new()
                digest.update(fcontent)
                d[fn] = digest.hexdigest() # or .digest()
                # the above four lines can be shortened to:
                d[fn] = md5.new(fo.read()).hexdigest()
                fo.close()
    return d


if __name__ == '__main__':
    import sys
    from pprint import pprint
    pprint(md5sums_for_dir(sys.argv[1]))

Chris

From dyoo at hkn.eecs.berkeley.edu  Fri Jan 19 18:28:00 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 19 Jan 2007 09:28:00 -0800 (PST)
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>


> I've been dabbling into Python for about 6 weeks now.I'm a Social 
> Sciences student who just got interested in programming and chose Python 
> as first language.

Out of curiosity, what materials are you using to learn how to program?



> Isn't it legal to start a new block of code when starting a 
> definition?And how come it returns 'variable' not defined,when they are 
> defined by the = ??Should i make them global?

Wait, wait.  I think you may be misunderstanding the use of 'global'. 
You should not be using global unless you really need it.



I see three variables here that you are interested in:

     altura_aeronave
     largura_aeronave
     comprimento

Are these always collected together?  If they are related, you should have 
a single structure that holds them together, rather than represent them as 
three separate variables.


Concretely, you can represent these three values as a single tuple.  You 
can think of it as a "vector" from your mathematics class.  For example:

#################################################
def make_measure(start, stop):
     """make_measure: number number -> measure
     Creates a new measure from start and stop."""
     return (start, stop)

def measure_start(a_measure):
     """measure_start: measure -> number
     Selects the start portion of a measure."""
     return a_measure[0]

def measure_stop(a_measure):
     """measure_end: measure -> end
     Selects the stop portion of a measure."""
     return a_measure[1]
#################################################


That is, these functions take inputs and produce outputs.  That should be 
a concept that you are familiar with from your previous experience:

     f(x) = 2x     (math notation)

is a function that takes a number and produces the double of that number. 
We write this in Python as:

################
def double(x):
     """double: number -> number
     Returns the double of x."""
     return x * 2
################


Getting back to the measure example: once we have these functions to build 
measures and take them apart, we can then use these like this:

################################################
## Small test program
m1 = make_measure(3, 4)
m2 = make_measure(17, 42)
print "m1", measure_start(m1), measure_stop(m1)
print "m2", measure_start(m2), measure_stop(m2)
################################################

If we dislike the duplication of those last two statements here, we can 
create a function that doesn't produce an output, but it still takes 
input:


########################################################################
def print_measure(header_name, a_measure):
     """print_measure: measure string -> None
     Prints out the measurement.
     """
     print header_name, measure_start(a_measure), measure_stop(a_measure)
########################################################################


After we define this helper function "print_measure()", our little program 
can now look like this:

#########################
## Small test program
m1 = make_measure(3, 4)
m2 = make_measure(17, 42)
print_measure("m1", m1)
print_measure("m2", m2)
#########################

Notice that, here, we do not need to say anything about "globals" to make 
effective programs.  We are simply passing values back and forth as 
parameters.


Does this make sense so far?  If you have any questions, please feel free 
to ask.  Please continue to reply to Tutor by using your email client's 
Reply to All feature.

From max.jameson at sbcglobal.net  Fri Jan 19 18:26:02 2007
From: max.jameson at sbcglobal.net (Max Jameson)
Date: Fri, 19 Jan 2007 09:26:02 -0800 (PST)
Subject: [Tutor] (no subject)
Message-ID: <20070119172602.59102.qmail@web81410.mail.mud.yahoo.com>

I know this is totally off-the-wall, but what am I doing wrong here?  I am using Python 2.5, and I am just learning...please be kind!


>>> aList = [2,3]
>>> bList = [5,7,9]
>>> aList.append(bList)
>>> print aList
[2, 3, [5, 7, 9]]
>>> print aList [1] [2]
Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    print aList [1] [2]
TypeError: 'int' object is unsubscriptable
>>> print aList [0] [1]
Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    print aList [0] [1]
TypeError: 'int' object is unsubscriptable
>>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070119/31468966/attachment.htm 

From dyoo at hkn.eecs.berkeley.edu  Fri Jan 19 18:41:53 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 19 Jan 2007 09:41:53 -0800 (PST)
Subject: [Tutor] (no subject)
In-Reply-To: <20070119172602.59102.qmail@web81410.mail.mud.yahoo.com>
References: <20070119172602.59102.qmail@web81410.mail.mud.yahoo.com>
Message-ID: <Pine.LNX.4.64.0701190937110.13190@hkn.eecs.berkeley.edu>



On Fri, 19 Jan 2007, Max Jameson wrote:

> I know this is totally off-the-wall, but what am I doing wrong here?  I 
> am using Python 2.5, and I am just learning...please be kind!


Hi Max,

Let's take a look.


###########################################
>>> aList = [2,3]
>>> bList = [5,7,9]
>>> aList.append(bList)
>>> print aList
[2, 3, [5, 7, 9]]
###########################################

Ok, looks good so far.  You have a list of three elements:

     2
     3
     [5, 7, 9]

where the third element in the list is itself a list.



###########################################
>>> print aList [1] [2]
Traceback (most recent call last):
   File "<pyshell#40>", line 1, in <module>
     print aList [1] [2]
TypeError: 'int' object is unsubscriptable
###########################################

Can you explain what you're trying to do at this point?  Pretend that we 
are clueless for the moment.

What are you expecting to get out from this?  We know you don't want to 
get the error, of course.  But what do you want to get?


Also, have you had a chance to look at something like:

    http://swaroopch.info/text/Byte_of_Python:Data_Structures

From dyoo at hkn.eecs.berkeley.edu  Fri Jan 19 19:14:01 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 19 Jan 2007 10:14:01 -0800 (PST)
Subject: [Tutor] (no subject) (fwd)
Message-ID: <Pine.LNX.4.64.0701191012580.13190@hkn.eecs.berkeley.edu>

[Forwarding to tutor.  Can someone answer Max?  Slightly busy at the 
moment.  Quick note: get him to realize that the list he was playing with 
originally had three elements.  The example in his book has two elements. 
Something has to change.  *grin*]


---------- Forwarded message ----------
Date: Fri, 19 Jan 2007 10:10:04 -0800 (PST)
From: Max Jameson <max.jameson at sbcglobal.net>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] (no subject)

Thanks, Danny.

I expected to get the third element of the second list printed, as shown on the on-line tutorial I am reading: http://www.freenetpages.co.uk/hp/alan.gauld/

This is exactly how the tutorial reads (I omited the definition of the aList and anoterh):
>>> aList.append(another)
>>> print aList
[42, [1, 2, 7]]

Notice how the result is a list of two elements but the second element is itself a list (as shown by the []?s around it). We can now access the element 7 by using a double index: 
>>> print aList[1][2]
7

The first index, 1, extracts the second element which is in turn a list. The second index, 2, extracts the third element of the sublist.


----- Original Message ----
From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
To: Max Jameson <max.jameson at sbcglobal.net>
Cc: tutor at python.org
Sent: Friday, January 19, 2007 11:41:53 AM
Subject: Re: [Tutor] (no subject)


On Fri, 19 Jan 2007, Max Jameson wrote:

> I know this is totally off-the-wall, but what am I doing wrong here?  I 
> am using Python 2.5, and I am just learning...please be kind!


Hi Max,

Let's take a look.


###########################################
>>> aList = [2,3]
>>> bList = [5,7,9]
>>> aList.append(bList)
>>> print aList
[2, 3, [5, 7, 9]]
###########################################

Ok, looks good so far.  You have a list of three elements:

      2
      3
      [5, 7, 9]

where the third element in the list is itself a list.



###########################################
>>> print aList [1] [2]
Traceback (most recent call last):
    File "<pyshell#40>", line 1, in <module>
      print aList [1] [2]
TypeError: 'int' object is unsubscriptable
###########################################

Can you explain what you're trying to do at this point?  Pretend that we 
are clueless for the moment.

What are you expecting to get out from this?  We know you don't want to 
get the error, of course.  But what do you want to get?


Also, have you had a chance to look at something like:

     http://swaroopch.info/text/Byte_of_Python:Data_Structures

From dyoo at hkn.eecs.berkeley.edu  Fri Jan 19 19:36:35 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 19 Jan 2007 10:36:35 -0800 (PST)
Subject: [Tutor] What is a mixin class?
In-Reply-To: <45AFB411.3060404@gmail.com>
References: <eolnmg$epm$1@sea.gmane.org>
	<Pine.LNX.4.64.0701171235550.3381@hkn.eecs.berkeley.edu>
	<45AFB411.3060404@gmail.com>
Message-ID: <Pine.LNX.4.64.0701191028550.13190@hkn.eecs.berkeley.edu>

> Wow, Danny.  I am impressed.  I am not sure that this should not be 
> called a 'mash-up' rather than a 'mix-in' but it has really been food 
> for thought.

Thank you, but this isn't an original contribution.  I mostly adapted the 
stuff in papers like:

     http://www.cs.utah.edu/plt/publications/aplas06-fff.pdf


> What else have you got stashed away?  Have you got a book on the way?

Not yet.


> You should at least put this recipe into the Python Cookbook. There is 
> not much on mix-ins in there.

The example I gave isn't quite right because of the thread-safety issue. 
I should revisit that observer code later to handle thread safety before 
putting it into the Cookbook.


Best of wishes!

From eric at ericwalstad.com  Fri Jan 19 19:40:49 2007
From: eric at ericwalstad.com (Eric Walstad)
Date: Fri, 19 Jan 2007 10:40:49 -0800
Subject: [Tutor] (no subject) (fwd)
In-Reply-To: <Pine.LNX.4.64.0701191012580.13190@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0701191012580.13190@hkn.eecs.berkeley.edu>
Message-ID: <45B110B1.5080801@ericwalstad.com>

Hey Max,
Danny Yoo wrote:
> [Forwarding to tutor.  Can someone answer Max?  Slightly busy at the
> moment.  Quick note: get him to realize that the list he was playing
> with originally had three elements.  The example in his book has two
> elements. Something has to change.  *grin*]
> 
> 
> ---------- Forwarded message ----------
> Date: Fri, 19 Jan 2007 10:10:04 -0800 (PST)
> From: Max Jameson <max.jameson at sbcglobal.net>
> To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] (no subject)
> 
[...]
> This is exactly how the tutorial reads (I omited the definition of the
> aList and anoterh):
>>>> aList.append(another)
>>>> print aList
> [42, [1, 2, 7]]
I suspect I didn't see the definition of 'aList' on Alan's website, but
the values look different than what you posted originally.

Based on the output above, I'd say:
aList = [42,]
another = [1, 2, 7]

Whereas your definition, in your original email:
aList = [2,3]
bList = [5,7,9]

Do you see the difference between the two (aside from the different
variable names)?


> I expected to get the third element of the second list printed
In your example, that would be the 'second' item in your bList (because
lists are zero-based):
bList[2] == 9

After 'append'ing bList to aList, aList has three items.  Try this at
the python command line:
print aList[0]
print aList[1]
print aList[2]

Two of those will be integers, One will be a list.

I hope that helps.

Eric.

From kent37 at tds.net  Fri Jan 19 19:42:41 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 19 Jan 2007 13:42:41 -0500
Subject: [Tutor] (no subject)
In-Reply-To: <20070119172602.59102.qmail@web81410.mail.mud.yahoo.com>
References: <20070119172602.59102.qmail@web81410.mail.mud.yahoo.com>
Message-ID: <45B11121.3000908@tds.net>

Max Jameson wrote:
> I know this is totally off-the-wall, but what am I doing wrong here?  I 
> am using Python 2.5, and I am just learning...please be kind!
> 
>  
> 
> 
>  >>> aList = [2,3]
>  >>> bList = [5,7,9]
>  >>> aList.append(bList)
>  >>> print aList
> [2, 3, [5, 7, 9]]
>  >>> print aList [1] [2]

What did you expect to happen here?
alist[1][2] is the same as (alist[1])[2]; in other words, it is the 
third item in the second item in alist. The second item (alist[1]) is 
the integer 3 which is not subscriptable; if you try 3[2] at the 
interactive prompt you will get the same error.

If you are trying to get the elements of bList out of aList you should 
try alist[2][0], alist[2][1] etc.

Kent

> 
> Traceback (most recent call last):
>   File "<pyshell#40>", line 1, in <module>
>     print aList [1] [2]
> TypeError: 'int' object is unsubscriptable
>  >>> print aList [0] [1]
> 
> Traceback (most recent call last):
>   File "<pyshell#41>", line 1, in <module>
>     print aList [0] [1]
> TypeError: 'int' object is unsubscriptable
>  >>>
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



From pytutor.20.247ob at spamgourmet.com  Fri Jan 19 19:50:12 2007
From: pytutor.20.247ob at spamgourmet.com (pytutor.20.247ob at spamgourmet.com)
Date: Fri, 19 Jan 2007 18:50:12 +0000 (GMT)
Subject: [Tutor] Correct Way to Start a Python Program Under Linux
In-Reply-To: <1169198568.6509.0.camel@localhost.localdomain>
Message-ID: <20070119185012.69682.qmail@web23414.mail.ird.yahoo.com>

> <pytutor.20.247ob at spamgourmet.com> wrote
> 
> I'm not sure what you mean by a filelauncher.
> In my window manager I just add the file path to my menu
> by editing a dialog box or config file. which environment are you 
> using?

Im using gnome and creating a 'custom application launcher' by rt click
a panel and choosing 'add to panel'. It is just a case of adding a file
path, the only option is you can run in a terminal (which works but
fires up a terminal window which I do not want)

> > my program uses subprocess.Popen({command string}, etc)
> > and these calls to Popen do not work, only if I run the program
> from 
> > a
> > shell window.
> 
> How do you know it doesn't work? Do you get an error or just silence?
> If you launch a program that writes to stdout then you had better
> be sure it has a stdout to write to! Are you sure its not just
> dumping its output to /dev/null?

when it's working you can see the processes created by doing 'ps -ef'
in another shell window, the python program spawns a child process
running tcpdump.

> OTOH it could also be that the
> import
> path is not set correctly(try checking your PYTHONPATH environment
> variable)

from a shell window typing echo $PYTHONPATH returns nothing, is this
normal, should I be setting this or is it optional? 
from within a python session importing sys and typing > sys.path
I get a long list of paths which I assume is right as its searching and
finding all the standard library modules.

> Can you give us a bit more info about what you mean by the
> statement that it doesn't work?

I mean the call to subprocess.Popen....  should create a new process
when viewed with 'ps -ef' from another command window, normally I see
the new process running the command 'tcpdump .....' but when running
the application from the launcher this just does not happen. The main
pygtk program is running fine, just the new process does not start.

> As a check try writing a very simple program with no external
> dependencies and see if it works...

You have helped crack it, I just wrote a small program like this, it
reads 400 packets from the eth0 interface saving it to a file:

<code>
#!/usr/bin/env python
#test prog
import curses.ascii, sys, os, subprocess, tempfile
def Readtraffic():
    myerr = tempfile.TemporaryFile()
    myout = tempfile.TemporaryFile()
    command = "sudo /usr/sbin/tcpdump -c 400 -q -t -s 192 -i eth0 -w
/var/tmp/testdump -Z wayne"
    myproc = subprocess.Popen(command, executable="/bin/bash",
shell=True, stderr=myerr, stdout=myout)
    return (myproc)

proc = Readtraffic()
stat = proc.poll()
print "stat = " + str(stat)

while stat == None:
    stat = proc.poll()
print "stat = " + str(stat)
print "finished"
</code>

This works fine, using another shell window I can see the subprocess
and tcpdump running under a new pid as expected, it's VERY similar to
the code in the program (which has been chopped about quite a bit by
now) with the difference being I changed the variable 'command' to be a
pure text string instead of a concatenation of variables and strings.
 
Substituting the code above into my program works! 
Now the puzzling bit identifying the actual error,

the code below works until I un-comment the line below '#oldcommand
...', I have even changed the variable name to 'oldcommand' so in
effect it's not even used, but just uncommenting it causes the problem,
ie, the subprocess does not start up when run from an application
launcher (yet still works when started from a shell!).

<code>
#oldcommand = "sudo " + self.exe['tcpdump'] + " -c " + str(packets) + "
-q -t -s " + str(packetsize) \
#+ " -i " + self.nic + " -w " + self.savepath + self.dumpfilename + "
-Z " + os.getlogin()
command = "sudo /usr/sbin/tcpdump -c 400 -q -t -s 192 -i eth0 -w
/var/tmp/testdump -Z wayne"
myproc = subprocess.Popen(command, executable="/bin/bash", shell=True,
stderr=myerr, stdout=myout)
return (myproc)
</code>

After going through the command piece by piece I found the problem, the
call to os.getlogin() works fine when run from a shell BUT fails when
run from a launcher, back to the docs I found:

user = pwd.getpwuid(os.getuid()) [0]

and this works!!!

Thanks for your help,

Wayne.



		
___________________________________________________________ 
What kind of emailer are you? Find out today - get a free analysis of your email personality. Take the quiz at the Yahoo! Mail Championship. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 

From kabads at gmail.com  Fri Jan 19 20:18:36 2007
From: kabads at gmail.com (Adam Cripps)
Date: Fri, 19 Jan 2007 19:18:36 +0000
Subject: [Tutor] Set changing order of items?
Message-ID: <c7ff38550701191118j104564b5l378da13cfa5bf49d@mail.gmail.com>

I'm adding strings to a Set to prevent duplicates. However, the
strings are meant to be in the correct order. When I add the string to
the Set, the order seems to change (and I don't seem to be able to
predict what order they are in).

The string is a simple addition question which should look like this
1) 20 + 3 = 23

I've kept the question ("1) 20 + ") separate from the answer ("23") so
that I can hide the answers later on.

The code that produces this is:

problem_set.add(str(count) +") "+ str(a)+ " + "+ str(b)+ " = ")

problem_set.add(str(a + b) + "\n")

However str(problem_set) returns something more like:
(['18\n', '2) 6 + 9 = ', '15\n', '1) 9 + 9 = '])

Is there a better way of organising this? Any suggestions gratefully
received.  In writing this email, I've realised that already I run the
risk of having different problems (20 + 1 and 19 + 2) which have the
same answer (21) which won't be allowed in the set.

The whole code can be seen at[1].

TIA
Adam
-- 
http://www.monkeez.org
PGP key: 0x7111B833

[1]
def add (lowrange, hirange, i):
        """Returns a list of additions for i iterations."""
        count = 1
        sums = []
        problem_set = set()
        while len(problem_set)<=i*2:
            #while count <=i:
            a = randint(lowrange, hirange)
            b = randint (lowrange, hirange)
            problem_set.add(str(count) +") "+ str(a)+ " + "+ str(b)+ " = ")
            problem_set.add(str(a + b) + "\n")
            count = count + 1
            #sums.append(sum)
        print "len problem_set " + str(len(problem_set))
        print "problem_set " + str(problem_set)
        sums = list(problem_set)
        print "len sums " + str(len(sums))
        #sums1 = sums.reverse()
        print "sums " + str(sums)
        return sums

From simon at brunningonline.net  Fri Jan 19 20:51:50 2007
From: simon at brunningonline.net (Simon Brunning)
Date: Fri, 19 Jan 2007 19:51:50 +0000
Subject: [Tutor] Set changing order of items?
In-Reply-To: <c7ff38550701191118j104564b5l378da13cfa5bf49d@mail.gmail.com>
References: <c7ff38550701191118j104564b5l378da13cfa5bf49d@mail.gmail.com>
Message-ID: <8c7f10c60701191151o58feb844t8293310853882bb0@mail.gmail.com>

On 1/19/07, Adam Cripps <kabads at gmail.com> wrote:
> I'm adding strings to a Set to prevent duplicates. However, the
> strings are meant to be in the correct order. When I add the string to
> the Set, the order seems to change (and I don't seem to be able to
> predict what order they are in).

Sets, like dictionaries, hold their items in an arbitrary order - see
<http://tinyurl.com/a2nkg>.

-- 
Cheers,
Simon B
simon at brunningonline.net

From kabads at gmail.com  Fri Jan 19 21:05:31 2007
From: kabads at gmail.com (Adam Cripps)
Date: Fri, 19 Jan 2007 20:05:31 +0000
Subject: [Tutor] Set changing order of items?
In-Reply-To: <8c7f10c60701191151o58feb844t8293310853882bb0@mail.gmail.com>
References: <c7ff38550701191118j104564b5l378da13cfa5bf49d@mail.gmail.com>
	<8c7f10c60701191151o58feb844t8293310853882bb0@mail.gmail.com>
Message-ID: <c7ff38550701191205t76dee4br3b7bf9914de3ac2a@mail.gmail.com>

On 1/19/07, Simon Brunning <simon at brunningonline.net> wrote:
> On 1/19/07, Adam Cripps <kabads at gmail.com> wrote:
> > I'm adding strings to a Set to prevent duplicates. However, the
> > strings are meant to be in the correct order. When I add the string to
> > the Set, the order seems to change (and I don't seem to be able to
> > predict what order they are in).
>
> Sets, like dictionaries, hold their items in an arbitrary order - see
> <http://tinyurl.com/a2nkg>.

OK - thanks for that - so it seems that using a Set will complicate
the matter more.

Really, I want to have a set of sets which won't have any duplicates.
An example might look something ilke this:

sums = [['1) 10 + 2 =', '12'], ['2) 13 + 4 =', '17']]
return sums

How might I achieve this list, without the duplicates (the duplicate
bit is the bit I'm stuck on).

Adam
-- 
http://www.monkeez.org
PGP key: 0x7111B833

From kmaheshw at science.uva.nl  Fri Jan 19 22:24:28 2007
From: kmaheshw at science.uva.nl (Ketan Maheshwari)
Date: Fri, 19 Jan 2007 22:24:28 +0100
Subject: [Tutor] messagebox positioning
Message-ID: <45B1370C.8070404@science.uva.nl>

Hi! All:
    tkMessageBox.showinfo("done", "You are done!!!")
    I need to show a message similar to this when some activity is done.
    However, I want to position this message box in a different part of 
the screen so that it does not occlude the background.
    How could I do it?

Cheers
ketan.

From dyoo at hkn.eecs.berkeley.edu  Fri Jan 19 23:30:49 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 19 Jan 2007 14:30:49 -0800 (PST)
Subject: [Tutor] Set changing order of items?
In-Reply-To: <c7ff38550701191118j104564b5l378da13cfa5bf49d@mail.gmail.com>
References: <c7ff38550701191118j104564b5l378da13cfa5bf49d@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0701191420440.22897@hkn.eecs.berkeley.edu>



On Fri, 19 Jan 2007, Adam Cripps wrote:

> I'm adding strings to a Set to prevent duplicates. However, the strings 
> are meant to be in the correct order. When I add the string to the Set, 
> the order seems to change (and I don't seem to be able to predict what 
> order they are in).


Hi Adam,

You can create your own data structure.  You don't have to work with raw 
data structures: you can make your own.


It sounds like you want a few operations from this data structure, which 
we'll call "UniqueList" for the moment:

     append(x): add x to the uniqueList if we don't already have seen it.

     elements(): return all the unique elements, in the order that we saw
                 them.

Does that sound ok, or do you need more operations?



We can even start writing test cases for this, even without writing 
implementation:

#############################################
def simple_test():
    ulist = UniqueList()
    ulist.append("a")
    ulist.append("b")
    ulist.append("b")
    ulist.append("c")
    assert ["a", "b", "c"] == ulist.elements()
#############################################

Would the behavior here be reasonable to you?



There's a naive way to implement this, which is:

##################################
class UniqueList:
     def __init__(self):
         self.elts = []

     def append(self, item):
         if item not in self.elts:
             self.elts.append(item)

     def elements(self):
         return self.elts
##################################


And now we can make instances of UniqueLists, and we can see that it 
passes our simple test function:

###############################################
>>> simple_test()
>>> 
>>> ulist = UniqueList()
>>> ulist.append("hello")
>>> ulist.append("hello")
>>> ulist.append("world")
>>> ulist.append("testing")
>>> ulist.append("hello")
>>> ulist.append("world")
>>> ulist
<__main__.UniqueList instance at 0xb7d1c3cc>
>>> ulist.elements()
['hello', 'world', 'testing']
###############################################


Would you be able to work with UniqueList here?  Would it do the job for 
you?

If not, then we should find out why.  Only after we get the functionality 
down should we think about efficiency.  It does us no good to make things 
fast if they don't do what you want.


Good luck to you!

From python at venix.com  Fri Jan 19 23:53:28 2007
From: python at venix.com (Python)
Date: Fri, 19 Jan 2007 17:53:28 -0500
Subject: [Tutor] Set changing order of items?
In-Reply-To: <c7ff38550701191205t76dee4br3b7bf9914de3ac2a@mail.gmail.com>
References: <c7ff38550701191118j104564b5l378da13cfa5bf49d@mail.gmail.com>
	<8c7f10c60701191151o58feb844t8293310853882bb0@mail.gmail.com>
	<c7ff38550701191205t76dee4br3b7bf9914de3ac2a@mail.gmail.com>
Message-ID: <1169247208.17376.84.camel@www.venix.com>

On Fri, 2007-01-19 at 20:05 +0000, Adam Cripps wrote:
> On 1/19/07, Simon Brunning <simon at brunningonline.net> wrote:
> > On 1/19/07, Adam Cripps <kabads at gmail.com> wrote:
> > > I'm adding strings to a Set to prevent duplicates. However, the
> > > strings are meant to be in the correct order. When I add the string to
> > > the Set, the order seems to change (and I don't seem to be able to
> > > predict what order they are in).
> >
> > Sets, like dictionaries, hold their items in an arbitrary order - see
> > <http://tinyurl.com/a2nkg>.
> 
> OK - thanks for that - so it seems that using a Set will complicate
> the matter more.
> 
> Really, I want to have a set of sets which won't have any duplicates.
> An example might look something ilke this:
> 
> sums = [['1) 10 + 2 =', '12'], ['2) 13 + 4 =', '17']]
> return sums

It looks like you have embedded the numbering into your strings.  If the
numbers were removed from the strings would you still care about keeping
the strings in order?

>>> sums = set([('10 + 2 =', '12'), ('13 + 4 =', '17')])

I changed the inside lists of pairs to tuples of pairs

>>> for ndx,(query,answer) in enumerate(sums):
...     print "%d) %s %s" % (ndx+1, query, answer)
... 
1) 10 + 2 = 12
2) 13 + 4 = 17


> 
> How might I achieve this list, without the duplicates (the duplicate
> bit is the bit I'm stuck on).
> 
> Adam
-- 
Lloyd Kvam
Venix Corp


From kent37 at tds.net  Sat Jan 20 01:10:39 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 19 Jan 2007 19:10:39 -0500
Subject: [Tutor] Set changing order of items?
In-Reply-To: <c7ff38550701191205t76dee4br3b7bf9914de3ac2a@mail.gmail.com>
References: <c7ff38550701191118j104564b5l378da13cfa5bf49d@mail.gmail.com>	<8c7f10c60701191151o58feb844t8293310853882bb0@mail.gmail.com>
	<c7ff38550701191205t76dee4br3b7bf9914de3ac2a@mail.gmail.com>
Message-ID: <45B15DFF.5010603@tds.net>

Adam Cripps wrote:
> On 1/19/07, Simon Brunning <simon at brunningonline.net> wrote:
>> On 1/19/07, Adam Cripps <kabads at gmail.com> wrote:
>>> I'm adding strings to a Set to prevent duplicates. However, the
>>> strings are meant to be in the correct order. When I add the string to
>>> the Set, the order seems to change (and I don't seem to be able to
>>> predict what order they are in).
>> Sets, like dictionaries, hold their items in an arbitrary order - see
>> <http://tinyurl.com/a2nkg>.
> 
> OK - thanks for that - so it seems that using a Set will complicate
> the matter more.
> 
> Really, I want to have a set of sets which won't have any duplicates.
> An example might look something ilke this:
> 
> sums = [['1) 10 + 2 =', '12'], ['2) 13 + 4 =', '17']]
> return sums
> 
> How might I achieve this list, without the duplicates (the duplicate
> bit is the bit I'm stuck on).

What is your criterion for uniqueness? Are you looking at just the sum, 
as you mentioned earlier, or the whole problem? Why is the order 
important, since the problems are randomly generated?

You should think about a more abstract way of representing a problem. 
For example, the two problems above could be represented as the tuples
(10, 2, 12) and (13, 4, 17). If you want the whole problems to be 
unique, then creating a set of tuples like this should do what you want. 
(I used tuples instead of lists because you can't make a set of lists.)

If you want only one problem with a given sum, then I would represent a 
problem as an entry in a dictionary where the sum is the key and the 
value is a tuple containing the two addends. Then you can keep putting 
problems in the dictionary until it is the size you want.

Once you have the final set (or dict) of problems, then you can convert 
them to a string representation and print them.

Kent


From duke at tuba.net  Sat Jan 20 01:01:13 2007
From: duke at tuba.net (duke at tuba.net)
Date: Fri, 19 Jan 2007 16:01:13 -0800 (PST)
Subject: [Tutor] wixi.cc to teach python?
Message-ID: <1683.189.145.147.14.1169251273.squirrel@webmail.tuba.net>

hi.. http://wixi.cc is an idea to teach python
using a real-world example of a real-world software
for the OLPC: http://wiki.laptop.org/go/wixi

also: for dutch developers there's a ?30K opportunity
http://wixi.cc/index.php?title=digital_pioneers
but deadline is soon (5 FEB)

feedback welcome.. thanks


From paulino1 at sapo.pt  Sat Jan 20 03:10:15 2007
From: paulino1 at sapo.pt (Paulino)
Date: Sat, 20 Jan 2007 02:10:15 +0000
Subject: [Tutor] Redirect from a CGI script
In-Reply-To: <6faf39c90701180526x74c9ce20v3d7e59a6b2983fc9@mail.gmail.com>
References: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt>
	<6faf39c90701180526x74c9ce20v3d7e59a6b2983fc9@mail.gmail.com>
Message-ID: <45B17A07.5030905@sapo.pt>

Thank you Andre,

well it doesn't work either!

Paulino
> Andre Engels escreveu:
> 2007/1/18, Paulino <paulino1_at_sapo.pt at .syntax-error>:
>
>     How can i redirect to another URL from a python CGI script.
>
>     Is's suposed to be as simply as:
>
>     print "Location : http://newurl "
>     It's not working.
>
>     this simple code does't work - < redir.pyw>
>     'print "Content-Type:text/html\n\n"
>     'print "Location : /cgi-bin/ecodiv.pyw "
>     'print
>
>     I use CGIHTTPServer, the server script is as follows:
>
>     'from BaseHTTPServer import HTTPServer
>     'from CGIHTTPServer import CGIHTTPRequestHandler
>     'HTTPServer(("localhost", 80), CGIHTTPRequestHandler).serve_forever()
>
>     instead of redirecting, it only prints 'Location :
>     /cgi-bin/ecodiv.pyw' inthe
>     browser
>
>
>
> I haven't tested it, but I think I had a similar error recently, and 
> that was solved by removing the \n\n at the end of the Content-Type 
> line. You could try that.
>
>
>
>
> -- 
> Andre Engels, andreengels at gmail.com <mailto:andreengels at gmail.com>
> ICQ: 6260644  --  Skype: a_engels 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070120/ae743455/attachment.htm 

From python at venix.com  Sat Jan 20 04:12:58 2007
From: python at venix.com (Python)
Date: Fri, 19 Jan 2007 22:12:58 -0500
Subject: [Tutor] Redirect from a CGI script
In-Reply-To: <45B17A07.5030905@sapo.pt>
References: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt>
	<6faf39c90701180526x74c9ce20v3d7e59a6b2983fc9@mail.gmail.com>
	<45B17A07.5030905@sapo.pt>
Message-ID: <1169262778.17376.103.camel@www.venix.com>

On Sat, 2007-01-20 at 02:10 +0000, Paulino wrote:
> Thank you Andre,
> 
> well it doesn't work either!

This works, 

#!/usr/bin/python
print "Location:        http://python.org/\r\n\r"

as does this

#!/usr/bin/python
print "Content-type:    text/html\r"
print "Location:        http://python.org/\r\n\r"


Tested using Apache on Linux.  A redirect should have a 3xx status.
Apache saw the location header and fixed the status to be 302.  My
browser (firefox) received the 302 status with the new location and
requested the new URL.

Each header line should be separated by \r\n.  A Python print on linux
will only output \n.  In actual practice, that appears to work OK.
either the browsers tolerate the missing \r or Apache fixes the data
stream.

Firefox plugins called tamperdata and liveheaders can be very helpful
for debugging these kinds of interactions.

Get the redirect to a real web site working.  Then fix it to redirect to
your script.  Use tamperdata to see what is going on if you have trouble
making it work.

> 
> Paulino
> > Andre Engels escreveu:
> > 2007/1/18, Paulino <paulino1_at_sapo.pt at .syntax-error>: 
> >         How can i redirect to another URL from a python CGI script.
> >         
> >         Is's suposed to be as simply as:
> >         
> >         print "Location : http://newurl "
> >         It's not working.
> >         
> >         this simple code does't work - < redir.pyw>
> >         'print "Content-Type:text/html\n\n"
> >         'print "Location : /cgi-bin/ecodiv.pyw "
> >         'print
> >         
> >         I use CGIHTTPServer, the server script is as follows:
> >         
> >         'from BaseHTTPServer import HTTPServer 
> >         'from CGIHTTPServer import CGIHTTPRequestHandler
> >         'HTTPServer(("localhost", 80),
> >         CGIHTTPRequestHandler).serve_forever()
> >         
> >         instead of redirecting, it only prints
> >         'Location : /cgi-bin/ecodiv.pyw' inthe 
> >         browser
> > 
> > 
> > I haven't tested it, but I think I had a similar error recently, and
> > that was solved by removing the \n\n at the end of the Content-Type
> > line. You could try that.
> > 
> > 
> > 
> > 
> > 
> > 
> > -- 
> > Andre Engels, andreengels at gmail.com
> > ICQ: 6260644  --  Skype: a_engels
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp


From dyoo at hkn.eecs.berkeley.edu  Sat Jan 20 05:33:31 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 19 Jan 2007 20:33:31 -0800 (PST)
Subject: [Tutor] Redirect from a CGI script
In-Reply-To: <45B17A07.5030905@sapo.pt>
References: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt>
	<6faf39c90701180526x74c9ce20v3d7e59a6b2983fc9@mail.gmail.com>
	<45B17A07.5030905@sapo.pt>
Message-ID: <Pine.LNX.4.64.0701192030560.13751@hkn.eecs.berkeley.edu>



On Sat, 20 Jan 2007, Paulino wrote:

> well it doesn't work either!

Hi Paulino,

Try being more descriptive: what does your program look like now?  It 
sounds like you've made a few changes.  If you can show us the program, 
we'll do what we can to pinpoint the problems.

From cappy2112 at gmail.com  Sat Jan 20 09:21:59 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Sat, 20 Jan 2007 00:21:59 -0800
Subject: [Tutor] Are there any MAC OSX python users here?
Message-ID: <8249c4ac0701200021k42ad8346o933c6de347d5a3b5@mail.gmail.com>

I'm trying to help some people run a python cmd line program on OSX.

Would you email me off list if you have OSX and run python apps form the cmd
line?

thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070120/4596957c/attachment.html 

From kmaheshw at science.uva.nl  Sat Jan 20 09:59:26 2007
From: kmaheshw at science.uva.nl (Ketan Maheshwari)
Date: Sat, 20 Jan 2007 09:59:26 +0100
Subject: [Tutor] python certification
Message-ID: <45B1D9EE.9010106@science.uva.nl>

Hi All:
    I am looking forward to obtain some kind of certification for 
Python. Is there anything like that exist?
    Could someone give me pointers for details.

    Regards:
        Ketan

From alan.gauld at btinternet.com  Sat Jan 20 10:14:09 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 20 Jan 2007 09:14:09 -0000
Subject: [Tutor] Are there any MAC OSX python users here?
References: <8249c4ac0701200021k42ad8346o933c6de347d5a3b5@mail.gmail.com>
Message-ID: <eosmh5$bju$1@sea.gmane.org>


"Tony Cappellini" <cappy2112 at gmail.com> wrote in message 
news:8249c4ac0701200021k42ad8346o933c6de347d5a3b5 at mail.gmail.com...
> I'm trying to help some people run a python cmd line program on OSX.
>
> Would you email me off list if you have OSX and run python apps form 
> the cmd
> line?

I do.

They need to start Applications-Utilities->Terminal

And that gets them a Unix terminal.
After that its standard Unix... What kind of problems are you having?

Alan G 



From kabads at gmail.com  Sat Jan 20 10:27:35 2007
From: kabads at gmail.com (Adam Cripps)
Date: Sat, 20 Jan 2007 09:27:35 +0000
Subject: [Tutor] Set changing order of items?
In-Reply-To: <45B15DFF.5010603@tds.net>
References: <c7ff38550701191118j104564b5l378da13cfa5bf49d@mail.gmail.com>
	<8c7f10c60701191151o58feb844t8293310853882bb0@mail.gmail.com>
	<c7ff38550701191205t76dee4br3b7bf9914de3ac2a@mail.gmail.com>
	<45B15DFF.5010603@tds.net>
Message-ID: <c7ff38550701200127t16f3ea86pad05604a2a9e5870@mail.gmail.com>

On 1/20/07, Kent Johnson <kent37 at tds.net> wrote:
> Adam Cripps wrote:
> > On 1/19/07, Simon Brunning <simon at brunningonline.net> wrote:
> >> On 1/19/07, Adam Cripps <kabads at gmail.com> wrote:
> >>> I'm adding strings to a Set to prevent duplicates. However, the
> >>> strings are meant to be in the correct order. When I add the string to
> >>> the Set, the order seems to change (and I don't seem to be able to
> >>> predict what order they are in).
> >> Sets, like dictionaries, hold their items in an arbitrary order - see
> >> <http://tinyurl.com/a2nkg>.
> >
> > OK - thanks for that - so it seems that using a Set will complicate
> > the matter more.
> >
> > Really, I want to have a set of sets which won't have any duplicates.
> > An example might look something ilke this:
> >
> > sums = [['1) 10 + 2 =', '12'], ['2) 13 + 4 =', '17']]
> > return sums
> >
> > How might I achieve this list, without the duplicates (the duplicate
> > bit is the bit I'm stuck on).
>
> What is your criterion for uniqueness? Are you looking at just the sum,
> as you mentioned earlier, or the whole problem? Why is the order
> important, since the problems are randomly generated?
>
> You should think about a more abstract way of representing a problem.
> For example, the two problems above could be represented as the tuples
> (10, 2, 12) and (13, 4, 17). If you want the whole problems to be
> unique, then creating a set of tuples like this should do what you want.
> (I used tuples instead of lists because you can't make a set of lists.)
>
> If you want only one problem with a given sum, then I would represent a
> problem as an entry in a dictionary where the sum is the key and the
> value is a tuple containing the two addends. Then you can keep putting
> problems in the dictionary until it is the size you want.
>
> Once you have the final set (or dict) of problems, then you can convert
> them to a string representation and print them.

Many thanks all - I've got there in the end, using a tuple inside a
set, ditching the question number and then rendering the sum for
output in my main gui module.

However, this does raise another issue now (which I had thought would
happen, but was putting it off until I'd solved the original problem).

Basically, the user can choose how many problems are set - i. They can
also choose the highest and lowest possible numbers - highest and
lowest. With these values, they can now create a scenario which will
lock the application - they can choose values with a narrow margin
(lowest = 5, highest = 6) and then choose to have 100 of these
problems (i=100). Of course, this will mean that my app will now go
through that loop trying to find a new combination that no longer is
possible.

Anyone have any guidance or tips here? How will I create a flag which
is raised once the loop becomes infinite?

TIA
Adam
-- 
http://www.monkeez.org
PGP key: 0x7111B833

From miago.python at gmail.com  Sat Jan 20 13:55:32 2007
From: miago.python at gmail.com (Karl Wittgenstein)
Date: Sat, 20 Jan 2007 10:55:32 -0200
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>
Message-ID: <1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>

First of all let me thank you and Geoframer for your patience;it was very
kind that you bothered answering this,as I realize this is very basic
stuff.You people are Smart and Caring Dudes,which is a powerful combo for
educators!!

"Out of curiosity, what materials are you using to learn how to program?"

Well, mostly Google! I have just finished that RUR-PLE tutorial by Andre
Roberge, read some of the Python documentation-not as focused as I should,I
admit;many programming concepts are simply  totally alien to me,so I also
use Wikipedia a lot.They have a Python tutorial.Sometimes I do some math
research, as I only know very basic math,predicate logic and
statistics.Ialso tried a pygame tutorial,but can't import the damn
module without at
least one error and can't get the damn chimp.bmp file loaded!!!I used
os.path.join("folder","file") to no success...
Thank you again,and once more in advance - if you would be so kind as to
point me learning material...My spare time is very short,between graduation
and work,so I would appreciate very didatic material...Thank you guys again!


2007/1/19, Danny Yoo <dyoo at hkn.eecs.berkeley.edu>:
>
>
> > I've been dabbling into Python for about 6 weeks now.I'm a Social
> > Sciences student who just got interested in programming and chose Python
> > as first language.
>
> Out of curiosity, what materials are you using to learn how to program?
>
>
>
> > Isn't it legal to start a new block of code when starting a
> > definition?And how come it returns 'variable' not defined,when they are
> > defined by the = ??Should i make them global?
>
> Wait, wait.  I think you may be misunderstanding the use of 'global'.
> You should not be using global unless you really need it.
>
>
>
> I see three variables here that you are interested in:
>
>     altura_aeronave
>     largura_aeronave
>     comprimento
>
> Are these always collected together?  If they are related, you should have
> a single structure that holds them together, rather than represent them as
> three separate variables.
>
>
> Concretely, you can represent these three values as a single tuple.  You
> can think of it as a "vector" from your mathematics class.  For example:
>
> #################################################
> def make_measure(start, stop):
>     """make_measure: number number -> measure
>     Creates a new measure from start and stop."""
>     return (start, stop)
>
> def measure_start(a_measure):
>     """measure_start: measure -> number
>     Selects the start portion of a measure."""
>     return a_measure[0]
>
> def measure_stop(a_measure):
>     """measure_end: measure -> end
>     Selects the stop portion of a measure."""
>     return a_measure[1]
> #################################################
>
>
> That is, these functions take inputs and produce outputs.  That should be
> a concept that you are familiar with from your previous experience:
>
>     f(x) = 2x     (math notation)
>
> is a function that takes a number and produces the double of that number.
> We write this in Python as:
>
> ################
> def double(x):
>     """double: number -> number
>     Returns the double of x."""
>     return x * 2
> ################
>
>
> Getting back to the measure example: once we have these functions to build
> measures and take them apart, we can then use these like this:
>
> ################################################
> ## Small test program
> m1 = make_measure(3, 4)
> m2 = make_measure(17, 42)
> print "m1", measure_start(m1), measure_stop(m1)
> print "m2", measure_start(m2), measure_stop(m2)
> ################################################
>
> If we dislike the duplication of those last two statements here, we can
> create a function that doesn't produce an output, but it still takes
> input:
>
>
> ########################################################################
> def print_measure(header_name, a_measure):
>     """print_measure: measure string -> None
>     Prints out the measurement.
>     """
>     print header_name, measure_start(a_measure), measure_stop(a_measure)
> ########################################################################
>
>
> After we define this helper function "print_measure()", our little program
> can now look like this:
>
> #########################
> ## Small test program
> m1 = make_measure(3, 4)
> m2 = make_measure(17, 42)
> print_measure("m1", m1)
> print_measure("m2", m2)
> #########################
>
> Notice that, here, we do not need to say anything about "globals" to make
> effective programs.  We are simply passing values back and forth as
> parameters.
>
>
> Does this make sense so far?  If you have any questions, please feel free
> to ask.  Please continue to reply to Tutor by using your email client's
> Reply to All feature.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070120/75e2ecd5/attachment.html 

From kent37 at tds.net  Sat Jan 20 14:04:43 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 20 Jan 2007 08:04:43 -0500
Subject: [Tutor] Set changing order of items?
In-Reply-To: <c7ff38550701200127t16f3ea86pad05604a2a9e5870@mail.gmail.com>
References: <c7ff38550701191118j104564b5l378da13cfa5bf49d@mail.gmail.com>	<8c7f10c60701191151o58feb844t8293310853882bb0@mail.gmail.com>	<c7ff38550701191205t76dee4br3b7bf9914de3ac2a@mail.gmail.com>	<45B15DFF.5010603@tds.net>
	<c7ff38550701200127t16f3ea86pad05604a2a9e5870@mail.gmail.com>
Message-ID: <45B2136B.6090906@tds.net>

Adam Cripps wrote:
> Many thanks all - I've got there in the end, using a tuple inside a
> set, ditching the question number and then rendering the sum for
> output in my main gui module.
> 
> However, this does raise another issue now (which I had thought would
> happen, but was putting it off until I'd solved the original problem).
> 
> Basically, the user can choose how many problems are set - i. They can
> also choose the highest and lowest possible numbers - highest and
> lowest. With these values, they can now create a scenario which will
> lock the application - they can choose values with a narrow margin
> (lowest = 5, highest = 6) and then choose to have 100 of these
> problems (i=100). Of course, this will mean that my app will now go
> through that loop trying to find a new combination that no longer is
> possible.

This is a pretty easy condition to test for - maybe check that the 
number of possible problems in the given range is at least double (or 
some multiple) of the number of problems desired. If not, print an error 
message and have them enter new values.
> 
> Anyone have any guidance or tips here? How will I create a flag which
> is raised once the loop becomes infinite?

You could also restrict the loop to, say, twice the number of problems 
desired and give up if after that many loops you don't have the desired 
number.

Kent


From miago.python at gmail.com  Sat Jan 20 14:23:55 2007
From: miago.python at gmail.com (Karl Wittgenstein)
Date: Sat, 20 Jan 2007 11:23:55 -0200
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>
	<1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>
Message-ID: <1f1621ae0701200523j173847dewee6446e2ccc96db1@mail.gmail.com>

I would also like to ask what skills you think I should develop so I can
approach programming more
' natively', and would like to clarify the following issue:
input("Something") usually displays Something when prompting for input;why
is that the case when I run a single line of code and isn't when I use
many?When I run three lines straight in this format,only the first message
and prompt are displayed...That is surely out of the scope of my current
knowledge....Which is not very encompassing,anyway.


2007/1/20, Karl Wittgenstein <miago.python at gmail.com>:
>
> First of all let me thank you and Geoframer for your patience;it was very
> kind that you bothered answering this,as I realize this is very basic
> stuff.You people are Smart and Caring Dudes,which is a powerful combo for
> educators!!
>
> "Out of curiosity, what materials are you using to learn how to program?"
>
> Well, mostly Google! I have just finished that RUR-PLE tutorial by Andre
> Roberge, read some of the Python documentation-not as focused as I should,I
> admit;many programming concepts are simply  totally alien to me,so I also
> use Wikipedia a lot.They have a Python tutorial.Sometimes I do some math
> research, as I only know very basic math,predicate logic and statistics.Ialso tried a pygame tutorial,but can't import the damn module without at
> least one error and can't get the damn chimp.bmp file loaded!!!I used
> os.path.join("folder","file") to no success...
> Thank you again,and once more in advance - if you would be so kind as to
> point me learning material...My spare time is very short,between
> graduation and work,so I would appreciate very didatic material...Thank
> you guys again!
>
>
> 2007/1/19, Danny Yoo <dyoo at hkn.eecs.berkeley.edu>:
> >
> >
> > > I've been dabbling into Python for about 6 weeks now.I'm a Social
> > > Sciences student who just got interested in programming and chose
> > Python
> > > as first language.
> >
> > Out of curiosity, what materials are you using to learn how to program?
> >
> >
> >
> > > Isn't it legal to start a new block of code when starting a
> > > definition?And how come it returns 'variable' not defined,when they
> > are
> > > defined by the = ??Should i make them global?
> >
> > Wait, wait.  I think you may be misunderstanding the use of 'global'.
> > You should not be using global unless you really need it.
> >
> >
> >
> > I see three variables here that you are interested in:
> >
> >     altura_aeronave
> >     largura_aeronave
> >     comprimento
> >
> > Are these always collected together?  If they are related, you should
> > have
> > a single structure that holds them together, rather than represent them
> > as
> > three separate variables.
> >
> >
> > Concretely, you can represent these three values as a single tuple.  You
> > can think of it as a "vector" from your mathematics class.  For example:
> >
> > #################################################
> > def make_measure(start, stop):
> >     """make_measure: number number -> measure
> >     Creates a new measure from start and stop."""
> >     return (start, stop)
> >
> > def measure_start(a_measure):
> >     """measure_start: measure -> number
> >     Selects the start portion of a measure."""
> >     return a_measure[0]
> >
> > def measure_stop(a_measure):
> >     """measure_end: measure -> end
> >     Selects the stop portion of a measure."""
> >     return a_measure[1]
> > #################################################
> >
> >
> > That is, these functions take inputs and produce outputs.  That should
> > be
> > a concept that you are familiar with from your previous experience:
> >
> >     f(x) = 2x     (math notation)
> >
> > is a function that takes a number and produces the double of that
> > number.
> > We write this in Python as:
> >
> > ################
> > def double(x):
> >     """double: number -> number
> >     Returns the double of x."""
> >     return x * 2
> > ################
> >
> >
> > Getting back to the measure example: once we have these functions to
> > build
> > measures and take them apart, we can then use these like this:
> >
> > ################################################
> > ## Small test program
> > m1 = make_measure(3, 4)
> > m2 = make_measure(17, 42)
> > print "m1", measure_start(m1), measure_stop(m1)
> > print "m2", measure_start(m2), measure_stop(m2)
> > ################################################
> >
> > If we dislike the duplication of those last two statements here, we can
> > create a function that doesn't produce an output, but it still takes
> > input:
> >
> >
> > ########################################################################
> > def print_measure(header_name, a_measure):
> >     """print_measure: measure string -> None
> >     Prints out the measurement.
> >     """
> >     print header_name, measure_start(a_measure), measure_stop(a_measure)
> > ########################################################################
> >
> >
> > After we define this helper function "print_measure()", our little
> > program
> > can now look like this:
> >
> > #########################
> > ## Small test program
> > m1 = make_measure(3, 4)
> > m2 = make_measure(17, 42)
> > print_measure("m1", m1)
> > print_measure("m2", m2)
> > #########################
> >
> > Notice that, here, we do not need to say anything about "globals" to
> > make
> > effective programs.  We are simply passing values back and forth as
> > parameters.
> >
> >
> > Does this make sense so far?  If you have any questions, please feel
> > free
> > to ask.  Please continue to reply to Tutor by using your email client's
> > Reply to All feature.
> >
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070120/70f52f3d/attachment.htm 

From kent37 at tds.net  Sat Jan 20 14:43:50 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 20 Jan 2007 08:43:50 -0500
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>
	<1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>
Message-ID: <45B21C96.4060708@tds.net>

Karl Wittgenstein wrote:
> Thank you again,and once more in advance - if you would be so kind as to 
> point me learning material...My spare time is very short,between 
> graduation and work,so I would appreciate very didatic material...Thank 
> you guys again!

Try one of the tutorials listed here
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

or one of these books:
http://effbot.org/pyfaq/tutor-what-are-some-good-books-on-python.htm

Kent



From kent37 at tds.net  Sat Jan 20 14:45:37 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 20 Jan 2007 08:45:37 -0500
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <1f1621ae0701200523j173847dewee6446e2ccc96db1@mail.gmail.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>	<1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>
	<1f1621ae0701200523j173847dewee6446e2ccc96db1@mail.gmail.com>
Message-ID: <45B21D01.7040504@tds.net>

Karl Wittgenstein wrote:
> I would also like to ask what skills you think I should develop so I can 
> approach programming more            
> ' natively', and would like to clarify the following issue:
> input("Something") usually displays Something when prompting for 
> input;why is that the case when I run a single line of code and isn't 
> when I use many?When I run three lines straight in this format,only the 
> first message and prompt are displayed...That is surely out of the scope 
> of my current knowledge....Which is not very encompassing,anyway.

input('Something') displays the prompt 'Something' and then waits for 
input up to a new line. When you enter the input it will execute the 
next statement which may be another input().

Kent


From rdm at rcblue.com  Sat Jan 20 15:34:37 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 20 Jan 2007 06:34:37 -0800
Subject: [Tutor] How to import this program, and other questions
Message-ID: <7.0.1.0.2.20070120060521.036cc8f8@rcblue.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070120/c4c7c489/attachment.html 

From miago.python at gmail.com  Sat Jan 20 15:39:38 2007
From: miago.python at gmail.com (Karl Wittgenstein)
Date: Sat, 20 Jan 2007 12:39:38 -0200
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <45B21D01.7040504@tds.net>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>
	<1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>
	<1f1621ae0701200523j173847dewee6446e2ccc96db1@mail.gmail.com>
	<45B21D01.7040504@tds.net>
Message-ID: <1f1621ae0701200639t47f7691aw4b3fdaf807f484b5@mail.gmail.com>

"input('Something') displays the prompt 'Something' and then waits for
input up to a new line. When you enter the input it will execute the
next statement which may be another input()."
It should be so,man,I believe you.But believe me when I say that THIS DAMN
INTERPRETER DOES NOT ACT ACCORDINGLY!!!Sorry for the emotive caps,it's just
frustration biting my ancles...Maybe it's a SPE problem??
Thank you.



2007/1/20, Kent Johnson <kent37 at tds.net>:
>
> Karl Wittgenstein wrote:
> > I would also like to ask what skills you think I should develop so I can
> > approach programming more
> > ' natively', and would like to clarify the following issue:
> > input("Something") usually displays Something when prompting for
> > input;why is that the case when I run a single line of code and isn't
> > when I use many?When I run three lines straight in this format,only the
> > first message and prompt are displayed...That is surely out of the scope
> > of my current knowledge....Which is not very encompassing,anyway.
>
> input('Something') displays the prompt 'Something' and then waits for
> input up to a new line. When you enter the input it will execute the
> next statement which may be another input().
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070120/3289a375/attachment.htm 

From kent37 at tds.net  Sat Jan 20 15:57:16 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 20 Jan 2007 09:57:16 -0500
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <1f1621ae0701200639t47f7691aw4b3fdaf807f484b5@mail.gmail.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>	
	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>	
	<1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>	
	<1f1621ae0701200523j173847dewee6446e2ccc96db1@mail.gmail.com>	
	<45B21D01.7040504@tds.net>
	<1f1621ae0701200639t47f7691aw4b3fdaf807f484b5@mail.gmail.com>
Message-ID: <45B22DCC.7010203@tds.net>

Karl Wittgenstein wrote:
> "input('Something') displays the prompt 'Something' and then waits for
> input up to a new line. When you enter the input it will execute the
> next statement which may be another input()."
> It should be so,man,I believe you.But believe me when I say that THIS 
> DAMN INTERPRETER DOES NOT ACT ACCORDINGLY!!!Sorry for the emotive 
> caps,it's just frustration biting my ancles...Maybe it's a SPE problem??
> Thank you.

Can you describe exactly what you are doing? And please stop with the 
swear words, they are not appropriate to this list.

Kent


From miago.python at gmail.com  Sat Jan 20 16:10:03 2007
From: miago.python at gmail.com (Karl Wittgenstein)
Date: Sat, 20 Jan 2007 13:10:03 -0200
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <45B22DCC.7010203@tds.net>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>
	<1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>
	<1f1621ae0701200523j173847dewee6446e2ccc96db1@mail.gmail.com>
	<45B21D01.7040504@tds.net>
	<1f1621ae0701200639t47f7691aw4b3fdaf807f484b5@mail.gmail.com>
	<45B22DCC.7010203@tds.net>
Message-ID: <1f1621ae0701200710v8f8dc0ereb556d6cc8da8a3e@mail.gmail.com>

Ok,got the script working almost fine now...The only problem is that the
program window closes before we can get a glimpse of the answer...I use SPE
under WinXP, and have seen this problem in every script i try...This is the
script,as redone by a Smart Caring Dude on this list:

global altura_aeronave, largura_aeronave, comprimento_aeronave,
comprimento,largura, altura

def compativel():
   global altura, altura_aeronave, comprimento, comprimento_aeronave, \
          largura, largura_aeronave
   if not largura <= largura_aeronave:
       print 'Volume largo demais!'
   elif not altura <= altura_aeronave:
       print 'Volume alto demais!'
   elif not comprimento<=comprimento_aeronave:
       print 'Volume comprido demais!'
def define():
   global largura, altura, comprimento
   largura=input("Por favor informe a largura do volume em cm")
   altura=input("Por favor informe a altura do volume em cm")
   comprimento=input("Por favor informe o comprimento do volume em cm")

def porao():
   global altura_aeronave, largura_aeronave, comprimento_aeronave
   porao = input("Por favor informe o por?o a ser utilizado:1-4")
   if porao == 1 :
       altura_aeronave = 111
       largura_aeronave = 112
       comprimento_aeronave = 211 #You originally had comprimento here?
       return 1
   elif porao == 4:
       altura_aeronave = 112
       largura_aeronave = 113
       comprimento_aeronave = 212 #Same here
       return 1
   else:
       print "Porao inexistente!"

if porao():
   define()
   compativel()


2007/1/20, Kent Johnson <kent37 at tds.net>:

> Karl Wittgenstein wrote:
> > "input('Something') displays the prompt 'Something' and then waits for
> > input up to a new line. When you enter the input it will execute the
> > next statement which may be another input()."
> > It should be so,man,I believe you.But believe me when I say that THIS
> > DAMN INTERPRETER DOES NOT ACT ACCORDINGLY!!!Sorry for the emotive
> > caps,it's just frustration biting my ancles...Maybe it's a SPE problem??
> > Thank you.
>
> Can you describe exactly what you are doing? And please stop with the
> swear words, they are not appropriate to this list.
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070120/9f6d2067/attachment.htm 

From miago.python at gmail.com  Sat Jan 20 16:10:36 2007
From: miago.python at gmail.com (Karl Wittgenstein)
Date: Sat, 20 Jan 2007 13:10:36 -0200
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <45B22DCC.7010203@tds.net>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>
	<1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>
	<1f1621ae0701200523j173847dewee6446e2ccc96db1@mail.gmail.com>
	<45B21D01.7040504@tds.net>
	<1f1621ae0701200639t47f7691aw4b3fdaf807f484b5@mail.gmail.com>
	<45B22DCC.7010203@tds.net>
Message-ID: <1f1621ae0701200710t73b08ab1s4b8dff33a837f410@mail.gmail.com>

Sorry for the swear words...

2007/1/20, Kent Johnson <kent37 at tds.net>:
>
> Karl Wittgenstein wrote:
> > "input('Something') displays the prompt 'Something' and then waits for
> > input up to a new line. When you enter the input it will execute the
> > next statement which may be another input()."
> > It should be so,man,I believe you.But believe me when I say that THIS
> > DAMN INTERPRETER DOES NOT ACT ACCORDINGLY!!!Sorry for the emotive
> > caps,it's just frustration biting my ancles...Maybe it's a SPE problem??
> > Thank you.
>
> Can you describe exactly what you are doing? And please stop with the
> swear words, they are not appropriate to this list.
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070120/4814e55c/attachment.html 

From paulino1 at sapo.pt  Sat Jan 20 16:22:59 2007
From: paulino1 at sapo.pt (Paulino)
Date: Sat, 20 Jan 2007 15:22:59 +0000
Subject: [Tutor] Redirect from a CGI script
In-Reply-To: <1169262778.17376.103.camel@www.venix.com>
References: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt>	
	<6faf39c90701180526x74c9ce20v3d7e59a6b2983fc9@mail.gmail.com>	
	<45B17A07.5030905@sapo.pt>
	<1169262778.17376.103.camel@www.venix.com>
Message-ID: <45B233D3.2030609@sapo.pt>

Still doesn't work.

This should be a server issue, once I use a very basic server:

'from BaseHTTPServer import HTTPServer 
'from CGIHTTPServer import CGIHTTPRequestHandler
'HTTPServer(("localhost", 80),CGIHTTPRequestHandler).serve_forever()

I tryed also with the Karrigel embeded server and nothing happened...

I tryed all the sugestions from Andre with no succes.

The cgi script as only these two lines:
'print "Content-type:    text/html\r\n"
'print "Location:        http://python.org/\r\n\r"

I have a Win Xp pro machine with Python2.5.

Paulino
> On Sat, 2007-01-20 at 02:10 +0000, Paulino wrote:
>   
>> Thank you Andre,
>>
>> well it doesn't work either!
>>     
>
> This works, 
>
> #!/usr/bin/python
> print "Location:        http://python.org/\r\n\r"
>
> as does this
>
> #!/usr/bin/python
> print "Content-type:    text/html\r"
> print "Location:        http://python.org/\r\n\r"
>
>
> Tested using Apache on Linux.  A redirect should have a 3xx status.
> Apache saw the location header and fixed the status to be 302.  My
> browser (firefox) received the 302 status with the new location and
> requested the new URL.
>
> Each header line should be separated by \r\n.  A Python print on linux
> will only output \n.  In actual practice, that appears to work OK.
> either the browsers tolerate the missing \r or Apache fixes the data
> stream.
>
> Firefox plugins called tamperdata and liveheaders can be very helpful
> for debugging these kinds of interactions.
>
> Get the redirect to a real web site working.  Then fix it to redirect to
> your script.  Use tamperdata to see what is going on if you have trouble
> making it work.
>
>   
>> Paulino
>>     
>>> Andre Engels escreveu:
>>> 2007/1/18, Paulino <paulino1_at_sapo.pt at .syntax-error>: 
>>>         How can i redirect to another URL from a python CGI script.
>>>         
>>>         Is's suposed to be as simply as:
>>>         
>>>         print "Location : http://newurl "
>>>         It's not working.
>>>         
>>>         this simple code does't work - < redir.pyw>
>>>         'print "Content-Type:text/html\n\n"
>>>         'print "Location : /cgi-bin/ecodiv.pyw "
>>>         'print
>>>         
>>>         I use CGIHTTPServer, the server script is as follows:
>>>         
>>>         'from BaseHTTPServer import HTTPServer 
>>>         'from CGIHTTPServer import CGIHTTPRequestHandler
>>>         'HTTPServer(("localhost", 80),
>>>         CGIHTTPRequestHandler).serve_forever()
>>>         
>>>         instead of redirecting, it only prints
>>>         'Location : /cgi-bin/ecodiv.pyw' inthe 
>>>         browser
>>>
>>>
>>> I haven't tested it, but I think I had a similar error recently, and
>>> that was solved by removing the \n\n at the end of the Content-Type
>>> line. You could try that.
>>>
>>>
>>>
>>>
>>>
>>>
>>> -- 
>>> Andre Engels, andreengels at gmail.com
>>> ICQ: 6260644  --  Skype: a_engels
>>>       
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>     

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070120/70f0a2f3/attachment-0001.htm 

From david at graniteweb.com  Sat Jan 20 16:44:12 2007
From: david at graniteweb.com (David Rock)
Date: Sat, 20 Jan 2007 09:44:12 -0600
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <1f1621ae0701200710v8f8dc0ereb556d6cc8da8a3e@mail.gmail.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>
	<1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>
	<1f1621ae0701200523j173847dewee6446e2ccc96db1@mail.gmail.com>
	<45B21D01.7040504@tds.net>
	<1f1621ae0701200639t47f7691aw4b3fdaf807f484b5@mail.gmail.com>
	<45B22DCC.7010203@tds.net>
	<1f1621ae0701200710v8f8dc0ereb556d6cc8da8a3e@mail.gmail.com>
Message-ID: <20070120154412.GA24150@wdfs.graniteweb.com>

* Karl Wittgenstein <miago.python at gmail.com> [2007-01-20 13:10]:
> Ok,got the script working almost fine now...The only problem is that the
> program window closes before we can get a glimpse of the answer...I use SPE
> under WinXP, and have seen this problem in every script i try...This is the
> script,as redone by a Smart Caring Dude on this list:

It sounds like you need to run it from a command window.  Running it the
way you are isn't meant to leave a window up after the script is
finished. Do Start->Run->cmd  on XP to get a command window.  python
should already be in your path, so typing "python" at the propmt should
result in it running the interpreter.  If that works, exit the
interpreter and type "python scriptname" That should run your script,
and you will see the results in the command window because it won't
close after the script is done.

-- 
David Rock
david at graniteweb.com

From python at venix.com  Sat Jan 20 16:45:49 2007
From: python at venix.com (Python)
Date: Sat, 20 Jan 2007 10:45:49 -0500
Subject: [Tutor] Redirect from a CGI script
In-Reply-To: <45B233D3.2030609@sapo.pt>
References: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt>
	<6faf39c90701180526x74c9ce20v3d7e59a6b2983fc9@mail.gmail.com>
	<45B17A07.5030905@sapo.pt> <1169262778.17376.103.camel@www.venix.com>
	<45B233D3.2030609@sapo.pt>
Message-ID: <1169307949.17376.129.camel@www.venix.com>

On Sat, 2007-01-20 at 15:22 +0000, Paulino wrote:
> Still doesn't work. 

That's not terribly useful.  What status did tamperdata report?  What
did you see in the browser window?  Did you get a 302 status?

Try (specify the right URL for your script)

        telnet localhost 80
        GET /cgi-bin/redirect.py
        <enter>
        
What do you get?  (Describe what happens.)

Let us know if you don't understand the telnet command.

> 
> This should be a server issue, once I use a very basic server:
> 'from BaseHTTPServer import HTTPServer 
> 'from CGIHTTPServer import CGIHTTPRequestHandler
> 'HTTPServer(("localhost", 80),CGIHTTPRequestHandler).serve_forever()
> I tryed also with the Karrigel embeded server and nothing happened...
> 
> I tryed all the sugestions from Andre with no succes.
> 
> The cgi script as only these two lines:
> 'print "Content-type:    text/html\r\n"
> 'print "Location:        http://python.org/\r\n\r"
> 
> I have a Win Xp pro machine with Python2.5.
> 
> Paulino
> > On Sat, 2007-01-20 at 02:10 +0000, Paulino wrote:
> >   
> > > Thank you Andre,
> > > 
> > > well it doesn't work either!
> > >     
> > 
> > This works, 
> > 
> > #!/usr/bin/python
> > print "Location:        http://python.org/\r\n\r"
> > 
> > as does this
> > 
> > #!/usr/bin/python
> > print "Content-type:    text/html\r"
> > print "Location:        http://python.org/\r\n\r"
> > 
> > 
> > Tested using Apache on Linux.  A redirect should have a 3xx status.
> > Apache saw the location header and fixed the status to be 302.  My
> > browser (firefox) received the 302 status with the new location and
> > requested the new URL.
> > 
> > Each header line should be separated by \r\n.  A Python print on linux
> > will only output \n.  In actual practice, that appears to work OK.
> > either the browsers tolerate the missing \r or Apache fixes the data
> > stream.
> > 
> > Firefox plugins called tamperdata and liveheaders can be very helpful
> > for debugging these kinds of interactions.
> > 
> > Get the redirect to a real web site working.  Then fix it to redirect to
> > your script.  Use tamperdata to see what is going on if you have trouble
> > making it work.
> > 
> >   
> > > Paulino
> > >     
> > > > Andre Engels escreveu:
> > > > 2007/1/18, Paulino <paulino1_at_sapo.pt at .syntax-error>: 
> > > >         How can i redirect to another URL from a python CGI script.
> > > >         
> > > >         Is's suposed to be as simply as:
> > > >         
> > > >         print "Location : http://newurl "
> > > >         It's not working.
> > > >         
> > > >         this simple code does't work - < redir.pyw>
> > > >         'print "Content-Type:text/html\n\n"
> > > >         'print "Location : /cgi-bin/ecodiv.pyw "
> > > >         'print
> > > >         
> > > >         I use CGIHTTPServer, the server script is as follows:
> > > >         
> > > >         'from BaseHTTPServer import HTTPServer 
> > > >         'from CGIHTTPServer import CGIHTTPRequestHandler
> > > >         'HTTPServer(("localhost", 80),
> > > >         CGIHTTPRequestHandler).serve_forever()
> > > >         
> > > >         instead of redirecting, it only prints
> > > >         'Location : /cgi-bin/ecodiv.pyw' inthe 
> > > >         browser
> > > > 
> > > > 
> > > > I haven't tested it, but I think I had a similar error recently, and
> > > > that was solved by removing the \n\n at the end of the Content-Type
> > > > line. You could try that.
> > > > 
> > > > 
> > > > 
> > > > 
> > > > 
> > > > 
> > > > -- 
> > > > Andre Engels, andreengels at gmail.com
> > > > ICQ: 6260644  --  Skype: a_engels
> > > >       
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >     
> 
-- 
Lloyd Kvam
Venix Corp


From rschroev_nospam_ml at fastmail.fm  Sat Jan 20 17:30:07 2007
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Sat, 20 Jan 2007 17:30:07 +0100
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <1f1621ae0701200710v8f8dc0ereb556d6cc8da8a3e@mail.gmail.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>	<1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>	<1f1621ae0701200523j173847dewee6446e2ccc96db1@mail.gmail.com>	<45B21D01.7040504@tds.net>	<1f1621ae0701200639t47f7691aw4b3fdaf807f484b5@mail.gmail.com>	<45B22DCC.7010203@tds.net>
	<1f1621ae0701200710v8f8dc0ereb556d6cc8da8a3e@mail.gmail.com>
Message-ID: <eotg2f$3ml$1@sea.gmane.org>

Karl Wittgenstein schreef:
> Ok,got the script working almost fine now...The only problem is that the 
> program window closes before we can get a glimpse of the answer...I use 
> SPE under WinXP, and have seen this problem in every script i try...

Any program running in a console window does that. There are two ways 
around:
- open a console window and run your program from there, as David Rock 
describes
- you can work around it by adding raw_input("Press enter") as the very 
last line of the script

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven


From alan.gauld at btinternet.com  Sat Jan 20 19:01:16 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 20 Jan 2007 18:01:16 -0000
Subject: [Tutor] How to import this program, and other questions
References: <7.0.1.0.2.20070120060521.036cc8f8@rcblue.com>
Message-ID: <eotldh$ki5$1@sea.gmane.org>

"Dick Moores" <rdm at rcblue.com> wrote 

> I've succeed with a script, clnumDivision.py, (see it 
> at < http://www.rcblue.com/Python/clnumDivision_for-web.py>) 
> but it is not one function, but a script with 3 functions plus a 
> main(). So my first question is how can I use this as a function 
> that I could, for example, import into the interactive shell 
> ...Is the answer to put all 3 functions inside one big one? 

Probably not, its more likely to be a small function that checks 
its input parameters and calls one of the 3 worker functions.
Thats a more user friendly method too since it givers users of 
the module the chance to use the internal functions in different 
ways if they don't want the top level convenience function...

I assume your main is called from within an if name== main clause?

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From dyoo at hkn.eecs.berkeley.edu  Sat Jan 20 19:13:05 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jan 2007 10:13:05 -0800 (PST)
Subject: [Tutor] Redirect from a CGI script
In-Reply-To: <45B233D3.2030609@sapo.pt>
References: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt> 
	<6faf39c90701180526x74c9ce20v3d7e59a6b2983fc9@mail.gmail.com> 
	<45B17A07.5030905@sapo.pt> <1169262778.17376.103.camel@www.venix.com>
	<45B233D3.2030609@sapo.pt>
Message-ID: <Pine.LNX.4.64.0701201005040.22512@hkn.eecs.berkeley.edu>



On Sat, 20 Jan 2007, Paulino wrote:

> Still doesn't work.

[some text cut]

> I tryed all the sugestions from Andre with no succes.
>
> The cgi script as only these two lines:
> 'print "Content-type:    text/html\r\n"
> 'print "Location:        http://python.org/\r\n\r"


Ok, good.

The last line of the program looks suspicious.  If it helps, let me 
rearrange the program that you've written to:

###############################################
print "Content-type:    text/html\r\n"
print "Location:        http://python.org/\r\n"
print "\r"
###############################################

The code is missing the critical '\n' that allows the web browser to 
recognize the header.

From rdm at rcblue.com  Sat Jan 20 19:57:10 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 20 Jan 2007 10:57:10 -0800
Subject: [Tutor] How to import this program, and other questions
In-Reply-To: <eotldh$ki5$1@sea.gmane.org>
References: <7.0.1.0.2.20070120060521.036cc8f8@rcblue.com>
	<eotldh$ki5$1@sea.gmane.org>
Message-ID: <7.0.1.0.2.20070120105033.037a7370@rcblue.com>

At 10:01 AM 1/20/2007, Alan Gauld wrote:
>"Dick Moores" <rdm at rcblue.com> wrote
>
> > I've succeed with a script, clnumDivision.py, (see it
> > at < http://www.rcblue.com/Python/clnumDivision_for-web.py>)
> > but it is not one function, but a script with 3 functions plus a
> > main(). So my first question is how can I use this as a function
> > that I could, for example, import into the interactive shell
> > ...Is the answer to put all 3 functions inside one big one?
>
>Probably not, its more likely to be a small function that checks
>its input parameters and calls one of the 3 worker functions.
>Thats a more user friendly method too since it givers users of
>the module the chance to use the internal functions in different
>ways if they don't want the top level convenience function...
>
>I assume your main is called from within an if name== main clause?

Yes. I just realized that I quoted the link wrong. Try 
<http://www.rcblue.com/Python/clnumDivision_for-web.py>

The only user I have in mind is me. And I want to use all 3 functions 
together. Now that you've seen the program, could you explain what 
you meant by "a small function that checks its input parameters and 
calls one of the 3 worker functions."?

Thanks,

Dick Moores


>HTH,
>
>--
>Alan Gauld
>Author of the Learn to Program web site
>http://www.freenetpages.co.uk/hp/alan.gauld
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



From pytutmail at gmail.com  Sat Jan 20 21:21:06 2007
From: pytutmail at gmail.com (Toon Pieton)
Date: Sat, 20 Jan 2007 21:21:06 +0100
Subject: [Tutor] Staring myself blind
Message-ID: <7c3104d20701201221i3f61a59ubab298b58be8a7c9@mail.gmail.com>

Hey friendly users!

In a program I'm writing, I'm getting a Tab/space error, with the usual 1)
identation is incorrect or 2) mixes tabs and spaces. I just can't seem to
find. I tried selecting everything and untabbing it, no workie. I searched
an searched and searched, but couldnt find anything that is really wrong.

The error shows up on this line:
                        highcard = [z[8],z[7],z[6],z[5],z[4]]

The lines surrounding this one are:
                while zab < winlen:
                    yx = winner[int(winkeys[zab])]
                    xz = yx[1]
                    z = [yx[0],xz[0],xz[1],xz[2],xz[3],xz[4],xz[5)],xz[6]]
                    # Card 1
                    if z[7] > highcard[0]:
                        highcard = [z[8],z[7],z[6],z[5],z[4]]
                        defwinner = [winkeys[zab]]
                    elif z[7] == highcard[0]:

I can't post the whole program, since it's ~1000 lines long.

Does anybody see what causes the problem? Or have any tips how to find the
error easily?

Thanks in advance!
Toon Pieton
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070120/92b07d71/attachment.html 

From python at venix.com  Sat Jan 20 21:24:06 2007
From: python at venix.com (Python)
Date: Sat, 20 Jan 2007 15:24:06 -0500
Subject: [Tutor] Redirect from a CGI script
In-Reply-To: <Pine.LNX.4.64.0701201005040.22512@hkn.eecs.berkeley.edu>
References: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt>
	<6faf39c90701180526x74c9ce20v3d7e59a6b2983fc9@mail.gmail.com>
	<45B17A07.5030905@sapo.pt> <1169262778.17376.103.camel@www.venix.com>
	<45B233D3.2030609@sapo.pt>
	<Pine.LNX.4.64.0701201005040.22512@hkn.eecs.berkeley.edu>
Message-ID: <1169324646.17376.138.camel@www.venix.com>

On Sat, 2007-01-20 at 10:13 -0800, Danny Yoo wrote:
> 
> On Sat, 20 Jan 2007, Paulino wrote:
> 
> > Still doesn't work.
> 
> [some text cut]
> 
> > I tryed all the sugestions from Andre with no succes.
> >
> > The cgi script as only these two lines:
> > 'print "Content-type:    text/html\r\n"
> > 'print "Location:        http://python.org/\r\n\r"
> 
> 
> Ok, good.
> 
> The last line of the program looks suspicious.  If it helps, let me 
> rearrange the program that you've written to:
> 
> ###############################################
> print "Content-type:    text/html\r\n"
> print "Location:        http://python.org/\r\n"
> print "\r"
> ###############################################
> 
> The code is missing the critical '\n' that allows the web browser to 
> recognize the header.

That gets supplied from the print - doesn't it?.

sys.stdout.write(...) would need the final \n and might actually be
clearer.

> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp


From dyoo at hkn.eecs.berkeley.edu  Sat Jan 20 21:59:37 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jan 2007 12:59:37 -0800 (PST)
Subject: [Tutor] Redirect from a CGI script
In-Reply-To: <1169324646.17376.138.camel@www.venix.com>
References: <1169125712.2ytc1gkymtkw@w7.mail.sapo.pt> 
	<6faf39c90701180526x74c9ce20v3d7e59a6b2983fc9@mail.gmail.com> 
	<45B17A07.5030905@sapo.pt> <1169262778.17376.103.camel@www.venix.com> 
	<45B233D3.2030609@sapo.pt>
	<Pine.LNX.4.64.0701201005040.22512@hkn.eecs.berkeley.edu>
	<1169324646.17376.138.camel@www.venix.com>
Message-ID: <Pine.LNX.4.64.0701201250290.15157@hkn.eecs.berkeley.edu>



On Sat, 20 Jan 2007, Python wrote:

> On Sat, 2007-01-20 at 10:13 -0800, Danny Yoo wrote:

>> The last line of the program looks suspicious.  If it helps, let me
>> rearrange the program that you've written to:
>>
>> ###############################################
>> print "Content-type:    text/html\r\n"
>> print "Location:        http://python.org/\r\n"
>> print "\r"
>> ###############################################
>>
>> The code is missing the critical '\n' that allows the web browser to
>> recognize the header.
>
> That gets supplied from the print - doesn't it?.

Hi Lloyd and Paulino,


Ah, very true.  Ah ha!  That's exactly the problem here.  Thanks Lloyd!

What's happening is that Python's 'print' statement introduces its own 
newline between the content-type header and the location header.


So the bytes that are actually being written to the server look something 
like:

   "Content-type: text/html\r\n\nLocation: http://python.org/\r\n\n\r\n"

which is wrong: we really want it to be:

   "Content-type: text/html\r\nLocation: http://python.org/\r\n\r\n"


> sys.stdout.write(...) would need the final \n and might actually be
> clearer.

Yeah, I agree: that's exactly the right thing to use here.  (Actually, the 
right thing to do here is probably to use a separate client library that 
handles the ugliness, raw details of the CGI protocol.)


Paulino, in any case, use sys.stdout.write() rather than the print 
statement, at least when you're writing out the headers.  You need the 
extra control that sys.stdout.write() gives you: 'print' is introducing 
newlines that, under normal circumstances, are harmless, but when we're 
writing headers like this, make it easy to make the mistakes above.


Thanks again Lloyd!

From dyoo at hkn.eecs.berkeley.edu  Sat Jan 20 22:16:00 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jan 2007 13:16:00 -0800 (PST)
Subject: [Tutor] Staring myself blind
In-Reply-To: <7c3104d20701201221i3f61a59ubab298b58be8a7c9@mail.gmail.com>
References: <7c3104d20701201221i3f61a59ubab298b58be8a7c9@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0701201301480.15157@hkn.eecs.berkeley.edu>



On Sat, 20 Jan 2007, Toon Pieton wrote:

> In a program I'm writing, I'm getting a Tab/space error, with the usual 
> 1) identation is incorrect or 2) mixes tabs and spaces. I just can't 
> seem to find. I tried selecting everything and untabbing it, no workie. 
> I searched an searched and searched, but couldnt find anything that is 
> really wrong.

Hi Toon,

If you think you're running into tab/space issues, you can try running 
tabnanny on your program; it should help you detect the problem:

     http://docs.python.org/lib/module-tabnanny.html


But actually, there is a definite syntactic problem on one of the lines 
before the one you're looking at.  Take a very close look at:

>                   z = [yx[0],xz[0],xz[1],xz[2],xz[3],xz[4],xz[5)],xz[6]]

There is an extra right parenthesis there that is almost certainly not 
supposed to be here.


By the way, the code you've shown us so far looks very syntactically 
fragile; I'd have to look at more of the code, but a "code smell" I'm 
sniffing is a lot of hardcoded array indexing.  Are you trying to treat an 
list as if it were a data structure?


Concretely, code that looks like the snippet above, or this code:

>                       highcard = [z[8],z[7],z[6],z[5],z[4]]

is very susceptible to off-by-one errors (as well as syntactic typos). 
But even if it is technically correct, there's a more important reason why 
we should avoid code like this: there's no explicit, human reasoning in 
the numbers 8, 7, 6, 5, or 4 that would make it easy to know why the 
highcard depends on those values.  At least, we'd have to look at the rest 
of the program to figure this out.  So that knowledge is not as localized 
as it should be.

There are often different ways to write this that are less susceptible to 
syntactic typos.  If you could put up your code somewhere on the web, some 
of us here would be happy to do a code review with you.



> I can't post the whole program, since it's ~1000 lines long.

This is also a possible code smell.  Unless my code estimation is way off, 
I don't believe that code shouldn't be so long.  Get your code reviewed: 
we might be able to help you hack down the size of that code to something 
significantly tighter.


Good luck to you.

From dyoo at hkn.eecs.berkeley.edu  Sat Jan 20 22:18:23 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jan 2007 13:18:23 -0800 (PST)
Subject: [Tutor] Staring myself blind
In-Reply-To: <Pine.LNX.4.64.0701201301480.15157@hkn.eecs.berkeley.edu>
References: <7c3104d20701201221i3f61a59ubab298b58be8a7c9@mail.gmail.com>
	<Pine.LNX.4.64.0701201301480.15157@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.64.0701201317190.15157@hkn.eecs.berkeley.edu>

> This is also a possible code smell.  Unless my code estimation is way off, I 
> don't believe that code shouldn't be so long.

Oh good grief.  Forgive me for the double negative there.  I meant: "I 
don't believe the code should be that long."

From bgailer at alum.rpi.edu  Sat Jan 20 23:41:32 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sat, 20 Jan 2007 14:41:32 -0800
Subject: [Tutor] Staring myself blind
In-Reply-To: <7c3104d20701201221i3f61a59ubab298b58be8a7c9@mail.gmail.com>
References: <7c3104d20701201221i3f61a59ubab298b58be8a7c9@mail.gmail.com>
Message-ID: <45B29A9C.8020308@alum.rpi.edu>

Toon Pieton wrote:
> Hey friendly users!
>
> In a program I'm writing, I'm getting a Tab/space error, with the 
> usual 1) identation is incorrect or 2) mixes tabs and spaces. I just 
> can't seem to find. I tried selecting everything and untabbing it, no 
> workie. I searched an searched and searched, but couldnt find anything 
> that is really wrong.
I copied this and pasted it in into my Python editor. I added while 1: 
at the top so I could preserve your indentation. What I get is a syntax 
error, highlighting the ) after the 5 in the line:

z = [yx[0],xz[0],xz[1],xz[2],xz[3],xz[4],xz[5)],xz[6]]

When I remove the ) it compiles OK.
>
> The error shows up on this line:
>                         highcard = [z[8],z[7],z[6],z[5],z[4]]
>
> The lines surrounding this one are:
>                 while zab < winlen:
>                     yx = winner[int(winkeys[zab])]
>                     xz = yx[1]
>                     z = 
> [yx[0],xz[0],xz[1],xz[2],xz[3],xz[4],xz[5)],xz[6]]
>                     # Card 1
>                     if z[7] > highcard[0]:
>                         highcard = [z[8],z[7],z[6],z[5],z[4]]
>                         defwinner = [winkeys[zab]]
>                     elif z[7] == highcard[0]:
>
> I can't post the whole program, since it's ~1000 lines long.
>
> Does anybody see what causes the problem? Or have any tips how to find 
> the error easily?
>
> Thanks in advance!
> Toon Pieton
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


-- 
Bob Gailer
510-978-4454


From rdm at rcblue.com  Sun Jan 21 00:53:58 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 20 Jan 2007 15:53:58 -0800
Subject: [Tutor] How to import this program, and other questions
In-Reply-To: <7.0.1.0.2.20070120060521.036cc8f8@rcblue.com>
References: <7.0.1.0.2.20070120060521.036cc8f8@rcblue.com>
Message-ID: <7.0.1.0.2.20070120153938.037a1610@rcblue.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070120/29cf6034/attachment.htm 

From anilmrn at yahoo.com  Sun Jan 21 10:18:53 2007
From: anilmrn at yahoo.com (anil maran)
Date: Sun, 21 Jan 2007 01:18:53 -0800 (PST)
Subject: [Tutor] Sets in python
Message-ID: <742101.87698.qm@web55215.mail.re4.yahoo.com>

http://www.linuxforums.org/programming/introduction_to_python__part_1.html
Sets

I think I don't really have to explain what a set is, as everyone should know them from mathematics. It's simply a pile of elements that do not have ordering and do not contain duplicates. 

A set has to be initialized with the elements of a list. Since you already know what a list is, we do this in one step. Just like with dictionaries, print can handle a set as it is.
Once we have a set, I show he first useful feature of sets: testing whether an element is in the set. 

inventory_carpenter=set(['helmet', 'gloves', 'hammer'])
print inventory_carpenter # outputs set(['helmet', 'hammer', 'gloves'])

print 'gloves' in inventory_carpenter # outputs 'True' 

Since sets are interesting only if we have more that one of them, let's introduce another one! Once we have that, we can immediately see what are the elements that both sets contain (intersection).

inventory_highscaler=set(['helmet', 'rope', 'harness', 'carabiner']) 

print inventory_carpenter & inventory_highscaler # outputs 'set(['helmet'])'

Similarly, we can have the union of sets ( using | ), difference ( using - ), or symmetric difference (using ^). 
For sets, you don't really need anything else, as you can do every meaningful operation using the ones above. For example, to add a new element, you can use union.

inventory_carpenter = inventory_carpenter | set(['nails']) 

Using the interpreter interactively

If you would like to try out the things you've learnt right now, you might appreciate that the interpreter can be used in an interactive way. In case you use it like that, you don't have to enter your commands to a file, then save and run it, just tell something to Python, and get the response immediately. All you have to do is to invoke the interpreter by typing &#39;python&#39; to your shell.

kovacsp at centaur:~$ python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17)
[GCC 4.1.2 20060715 (prerelease) (Debian 4.1.1-9)] on linux2\n
Type "help", "copyright", "credits" or "license" for more information.
>>>

Once you are here, you can just type anything you like, it will get interpreted immediately. The good new is that you don&#39;t even have to use print if you want to see the value of a variable, just type the name of it.\n

>>> a\u003d4
>>> a
4
>>>

\n\n",0] ); D(["ce"]);  //-->
All you have to do is to invoke the interpreter by typing 'python' to your shell.

 
---------------------------------
Now that's room service! Choose from over 150,000 hotels 
in 45,000 destinations on Yahoo! Travel to find your fit.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070121/d44b1111/attachment.html 

From rabidpoobear at gmail.com  Sun Jan 21 10:48:00 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 21 Jan 2007 03:48:00 -0600
Subject: [Tutor] Sets in python
In-Reply-To: <742101.87698.qm@web55215.mail.re4.yahoo.com>
References: <742101.87698.qm@web55215.mail.re4.yahoo.com>
Message-ID: <45B336D0.5020207@gmail.com>

anil maran wrote:
> http://www.linuxforums.org/programming/introduction_to_python__part_1.html 
> <http://www.linuxforums.org/programming/introduction_to_python__part_1.html>
> [snip article excerpt]
why did you copy someone else's text verbatim and create a new thread?
Assuming you were trying to help someone on the list, why not reply to 
their e-mail like this:

Hey user,
it seems like you could benefit from reading an article i found on the web:
<insert link here>



From janos.juhasz at VELUX.com  Sun Jan 21 13:40:25 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Sun, 21 Jan 2007 13:40:25 +0100
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <mailman.8989.1169324650.32030.tutor@python.org>
Message-ID: <OF2CB03E9B.0950B7A1-ONC125726A.004417F2-C125726A.00459DB7@velux.com>

Dear Karl,


I use getch() when I start my script from the windows desktop and 
I am interested about its output.

import msvcrt
raw_input('Are you distressed ?\n')
print ('It will be better, I am sure :)')
msvcrt.getch() # append as last line

> Subject: Re: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
> To: tutor at python.org
> Message-ID: <20070120154412.GA24150 at wdfs.graniteweb.com>
> Content-Type: text/plain; charset=us-ascii

> * Karl Wittgenstein <miago.python at gmail.com> [2007-01-20 13:10]:
> > Ok,got the script working almost fine now...The only problem is that 
the
> > program window closes before we can get a glimpse of the answer...I 
use SPE
> > under WinXP, and have seen this problem in every script i try...This 
is the
> > script,as redone by a Smart Caring Dude on this list:


Yours sincerely,
______________________________
J?nos Juh?sz


From kabads at gmail.com  Sun Jan 21 15:32:30 2007
From: kabads at gmail.com (Adam Cripps)
Date: Sun, 21 Jan 2007 14:32:30 +0000
Subject: [Tutor] Set changing order of items?
In-Reply-To: <45B2136B.6090906@tds.net>
References: <c7ff38550701191118j104564b5l378da13cfa5bf49d@mail.gmail.com>
	<8c7f10c60701191151o58feb844t8293310853882bb0@mail.gmail.com>
	<c7ff38550701191205t76dee4br3b7bf9914de3ac2a@mail.gmail.com>
	<45B15DFF.5010603@tds.net>
	<c7ff38550701200127t16f3ea86pad05604a2a9e5870@mail.gmail.com>
	<45B2136B.6090906@tds.net>
Message-ID: <c7ff38550701210632s787ba922j1b96cfd44416ff47@mail.gmail.com>

On 1/20/07, Kent Johnson <kent37 at tds.net> wrote:
> Adam Cripps wrote:
> > Many thanks all - I've got there in the end, using a tuple inside a
> > set, ditching the question number and then rendering the sum for
> > output in my main gui module.
> >
> > However, this does raise another issue now (which I had thought would
> > happen, but was putting it off until I'd solved the original problem).
> >
> > Basically, the user can choose how many problems are set - i. They can
> > also choose the highest and lowest possible numbers - highest and
> > lowest. With these values, they can now create a scenario which will
> > lock the application - they can choose values with a narrow margin
> > (lowest = 5, highest = 6) and then choose to have 100 of these
> > problems (i=100). Of course, this will mean that my app will now go
> > through that loop trying to find a new combination that no longer is
> > possible.
>
> This is a pretty easy condition to test for - maybe check that the
> number of possible problems in the given range is at least double (or
> some multiple) of the number of problems desired. If not, print an error
> message and have them enter new values.
> >
> > Anyone have any guidance or tips here? How will I create a flag which
> > is raised once the loop becomes infinite?
>
> You could also restrict the loop to, say, twice the number of problems
> desired and give up if after that many loops you don't have the desired
> number.

Kent - completed the check through the former method - by checking the
possibly number of permutations wasn't exceeded.

Many thanks.
-- 
http://www.monkeez.org
PGP key: 0x7111B833

From rabidpoobear at gmail.com  Sun Jan 21 17:35:32 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 21 Jan 2007 10:35:32 -0600
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <OF2CB03E9B.0950B7A1-ONC125726A.004417F2-C125726A.00459DB7@velux.com>
References: <OF2CB03E9B.0950B7A1-ONC125726A.004417F2-C125726A.00459DB7@velux.com>
Message-ID: <45B39654.7050604@gmail.com>

J?nos Juh?sz wrote:
> Dear Karl,
>
>
> I use getch() when I start my script from the windows desktop and 
> I am interested about its output.
>
> import msvcrt
> raw_input('Are you distressed ?\n')
> print ('It will be better, I am sure :)')
> msvcrt.getch() # append as last line
And where is the interesting output?  What were you expecting, and what 
did you get?

From jfabiani at yolo.com  Sun Jan 21 17:40:53 2007
From: jfabiani at yolo.com (johnf)
Date: Sun, 21 Jan 2007 08:40:53 -0800
Subject: [Tutor] search a tuple of tuples
Message-ID: <200701210840.53470.jfabiani@yolo.com>

Hi,
I want to find a item within a large tuple that contains tuples.
mytuple = (('name',123,'value'),('first',345,'newvalue'))
so a 'for loop' works
istrue = False
for i in range(len(mytuple)):
  if 'first' in mytuple[i]:
      istrue = True
      break
if istrue:
  print " true"

Is possible to use a generator or list comp.  All I want to know is it True or 
False that mytuple contains 'first'.
-- 
John Fabiani

From emadnawfal at gmail.com  Sun Jan 21 18:45:33 2007
From: emadnawfal at gmail.com (Emad Nawfal)
Date: Sun, 21 Jan 2007 10:45:33 -0700
Subject: [Tutor] Arabic text in Python
Message-ID: <652641e90701210945t5a829bdds708a6124dcdb5202@mail.gmail.com>

Dear Folks,
I'm new to Python and programming in general. I'm interested in using Python
for text processing, but whenever I enter Arabic text, it says the text is
not supported.
How can I use Python for dealing with Arabic?
Thank you

-- 
If everyone is thinking alike, then somebody isn't thinking." George S.
Patton
-------------------------------------------------------
Emad Soliman Nawfal
University of Arizona, Tucson
--------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070121/a63fe3e3/attachment.html 

From jim at well.com  Sun Jan 21 18:48:01 2007
From: jim at well.com (jim stockford)
Date: Sun, 21 Jan 2007 09:48:01 -0800
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <1f1621ae0701200710t73b08ab1s4b8dff33a837f410@mail.gmail.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>
	<1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>
	<1f1621ae0701200523j173847dewee6446e2ccc96db1@mail.gmail.com>
	<45B21D01.7040504@tds.net>
	<1f1621ae0701200639t47f7691aw4b3fdaf807f484b5@mail.gmail.com>
	<45B22DCC.7010203@tds.net>
	<1f1621ae0701200710t73b08ab1s4b8dff33a837f410@mail.gmail.com>
Message-ID: <942fea3341310f1b2a7df7dec6883e71@well.com>


    no need for apology on my side. there's
    no agreed-upon and expressed policy.
    i like the model that we accept each
other as we are.

On Jan 20, 2007, at 7:10 AM, Karl Wittgenstein wrote:

> Sorry for the swear words...
>
> 2007/1/20, Kent Johnson <kent37 at tds.net>: Karl Wittgenstein wrote:
>> > "input('Something') displays the prompt 'Something' and then waits 
>> for
>> > input up to a new line. When you enter the input it will execute the
>> > next statement which may be another input()."
>> > It should be so,man,I believe you.But believe me when I say that 
>> THIS
>> > DAMN INTERPRETER DOES NOT ACT ACCORDINGLY!!!Sorry for the emotive
>> > caps,it's just frustration biting my ancles...Maybe it's a SPE 
>> problem??
>> > Thank you.
>>
>> Can you describe exactly what you are doing? And please stop with the
>> swear words, they are not appropriate to this list.
>>
>> Kent
>>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From kent37 at tds.net  Sun Jan 21 19:30:53 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 21 Jan 2007 13:30:53 -0500
Subject: [Tutor] search a tuple of tuples
In-Reply-To: <200701210840.53470.jfabiani@yolo.com>
References: <200701210840.53470.jfabiani@yolo.com>
Message-ID: <45B3B15D.3080505@tds.net>

johnf wrote:
> Hi,
> I want to find a item within a large tuple that contains tuples.
> mytuple = (('name',123,'value'),('first',345,'newvalue'))
> so a 'for loop' works
> istrue = False
> for i in range(len(mytuple)):
>   if 'first' in mytuple[i]:

This is better written as iteration over mytuple directly, there is no 
need for the index:
for t in mytuple:
   if 'first' in t:
>       istrue = True
>       break
> if istrue:
>   print " true"
> 
> Is possible to use a generator or list comp.  All I want to know is it True or 
> False that mytuple contains 'first'.

Use any() in Python 2.5:

In [1]: mytuple = (('name',123,'value'),('first',345,'newvalue'))

In [2]: help(any)
Help on built-in function any in module __builtin__:

any(...)
     any(iterable) -> bool

     Return True if bool(x) is True for any x in the iterable.

In [5]: any('first' in x for x in mytuple)
Out[5]: True

In [6]: mytuple = (('name',123,'value'),('last',345,'newvalue'))

In [7]: any('first' in x for x in mytuple)
Out[7]: False

Kent


From kent37 at tds.net  Sun Jan 21 19:41:26 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 21 Jan 2007 13:41:26 -0500
Subject: [Tutor] Arabic text in Python
In-Reply-To: <652641e90701210945t5a829bdds708a6124dcdb5202@mail.gmail.com>
References: <652641e90701210945t5a829bdds708a6124dcdb5202@mail.gmail.com>
Message-ID: <45B3B3D6.9000904@tds.net>

Emad Nawfal wrote:
> Dear Folks,
> I'm new to Python and programming in general. I'm interested in using 
> Python for text processing, but whenever I enter Arabic text, it says 
> the text is not supported.
> How can I use Python for dealing with Arabic?

What platform? GUI or command line input?

wxPython seems to support Arabic, according to this page:
http://wiki.wxpython.org/index.cgi/ValidI18nCodes

For command-line use, my guess is that if you have a console that 
supports Arabic input then you should be able to write a Python app that 
supports Arabic input in that console. The input will be encoded 
according to the console character encoding.

Kent


From dyoo at hkn.eecs.berkeley.edu  Sun Jan 21 19:43:26 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 21 Jan 2007 10:43:26 -0800 (PST)
Subject: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
In-Reply-To: <942fea3341310f1b2a7df7dec6883e71@well.com>
References: <1f1621ae0701190519m74967aeelc3c177f21e82b41e@mail.gmail.com>
	<Pine.LNX.4.64.0701190904080.13190@hkn.eecs.berkeley.edu>
	<1f1621ae0701200455r4f4474acma6ba7580ded08db7@mail.gmail.com>
	<1f1621ae0701200523j173847dewee6446e2ccc96db1@mail.gmail.com>
	<45B21D01.7040504@tds.net>
	<1f1621ae0701200639t47f7691aw4b3fdaf807f484b5@mail.gmail.com>
	<45B22DCC.7010203@tds.net>
	<1f1621ae0701200710t73b08ab1s4b8dff33a837f410@mail.gmail.com>
	<942fea3341310f1b2a7df7dec6883e71@well.com>
Message-ID: <Pine.LNX.4.64.0701211017380.21825@hkn.eecs.berkeley.edu>



On Sun, 21 Jan 2007, jim stockford wrote:

>    no need for apology on my side. there's
>    no agreed-upon and expressed policy.
>    i like the model that we accept each
> other as we are.

[meta; not really related to Python programming]

Hi Jim,

I did want to bring up that there are some community-held expectations on 
what to write on the list.  They're certainly not set in stone, but it's 
helpful to know about them.  Here's one description of an otherwise 
unspoken expectation:

    http://www.catb.org/~esr/faqs/smart-questions.html#writewell


Generally, when we see someone being too frustrated by a problem to 
describe it properly to the rest of us, that's something that should be 
brought up to the poster, so that they can improve their writing on the 
Tutor list.

When we do so, we're not trying to coerse the poster to change who they 
are personally, because that would be domination.  But we are trying to 
say that if they are primarily focused on describing their frustration 
rather than the problem itself, they stand a good chance at succeeding. 
That is, they can risk frustrating the people who they are asking for 
help, and that's not good.


When Kent complained about the swearing, that was taken a little 
superficially.  Swearing isn't really the Big Problem.  He was really 
asking: "Can you start describing the problem more precisely so we can get 
to work helping you?"

We just want to make sure the goal structure of questions on Tutor doesn't 
lean toward: "I don't know what I'm doing, and the buggy system sucks, and 
I'm so angry that I want people to sympathize with my anger."

Rather: "I don't know what I'm doing, here's what I've done so far, and I 
hope I wrote enough information for people to help me."


Best of wishes!

From jfabiani at yolo.com  Sun Jan 21 21:17:36 2007
From: jfabiani at yolo.com (johnf)
Date: Sun, 21 Jan 2007 12:17:36 -0800
Subject: [Tutor] search a tuple of tuples
In-Reply-To: <45B3B15D.3080505@tds.net>
References: <200701210840.53470.jfabiani@yolo.com> <45B3B15D.3080505@tds.net>
Message-ID: <200701211217.36967.jfabiani@yolo.com>

On Sunday 21 January 2007 10:30, you wrote:
> johnf wrote:
> > Hi,
> > I want to find a item within a large tuple that contains tuples.
> > mytuple = (('name',123,'value'),('first',345,'newvalue'))
> > so a 'for loop' works
> > istrue = False
> > for i in range(len(mytuple)):
> >   if 'first' in mytuple[i]:
>
> This is better written as iteration over mytuple directly, there is no
> need for the index:
> for t in mytuple:
>
>    if 'first' in t:
> >       istrue = True
> >       break
> > if istrue:
> >   print " true"
> >
> > Is possible to use a generator or list comp.  All I want to know is it
> > True or False that mytuple contains 'first'.
>
> Use any() in Python 2.5:
>
> In [1]: mytuple = (('name',123,'value'),('first',345,'newvalue'))
>
> In [2]: help(any)
> Help on built-in function any in module __builtin__:
>
> any(...)
>      any(iterable) -> bool
>
>      Return True if bool(x) is True for any x in the iterable.
>
> In [5]: any('first' in x for x in mytuple)
> Out[5]: True
>
> In [6]: mytuple = (('name',123,'value'),('last',345,'newvalue'))
>
> In [7]: any('first' in x for x in mytuple)
> Out[7]: False
>
> Kent
Perfect thanks for the help!
-- 
John Fabiani

From pythontut at pusspaws.net  Sun Jan 21 21:49:53 2007
From: pythontut at pusspaws.net (Dave S)
Date: Sun, 21 Jan 2007 20:49:53 +0000
Subject: [Tutor] pyw bug ?
Message-ID: <200701212049.53814.pythontut@pusspaws.net>

Hi all,

My GUI app dumps some diagnostic output to the terminal, starting it from an 
XP terminal, all is well.

Starting it as app.pyw so no terminal is needed - and err - the app randomly 
locks because the diagnostic output is - backing up ?

Remove diagnostic output & app.pyw is 100% reliable.

... mmm ... windows .... mutter mutter

Dave



From samrobertsmith at gmail.com  Mon Jan 22 07:56:28 2007
From: samrobertsmith at gmail.com (linda.s)
Date: Sun, 21 Jan 2007 22:56:28 -0800
Subject: [Tutor] direction and draw
Message-ID: <1d987df30701212256r7f02aa3an8a27d5348d531f76@mail.gmail.com>

I have a segment (two ending points are A and B) which is 0 degree.
How to draw a segment with 10 degrees and 15 in length?
Thanks,
Linda

From vgvr620034 at gmail.com  Mon Jan 22 09:47:23 2007
From: vgvr620034 at gmail.com (vanam)
Date: Mon, 22 Jan 2007 14:17:23 +0530
Subject: [Tutor] Inputting elements of a list
Message-ID: <bedebdfb0701220047t6bd8ef4cm9f28faf2da556641@mail.gmail.com>

For standard input from the keyboard raw_input will be used for string and
input for number.Suppose i want to input a list of some elements how could
it be done. Actually i am looking for sorting out elements in a
list.Belowis the given script
list = [45,4,5]
list.sort()
for y in list:
   print y ->this would sort out elements in that list. my question is in
the above script all the elements that list carry are defined i want to
input some elements in the list how could it be done


-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070122/ccba2832/attachment.htm 

From rabidpoobear at gmail.com  Mon Jan 22 10:34:12 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 22 Jan 2007 03:34:12 -0600
Subject: [Tutor] direction and draw
In-Reply-To: <1d987df30701212256r7f02aa3an8a27d5348d531f76@mail.gmail.com>
References: <1d987df30701212256r7f02aa3an8a27d5348d531f76@mail.gmail.com>
Message-ID: <45B48514.7040403@gmail.com>

linda.s wrote:
> I have a segment (two ending points are A and B) which is 0 degree.
> How to draw a segment with 10 degrees and 15 in length?
>   
You'll need a pen, some paper, a protractor, a ruler, and a steady hand.
Good luck.
-Luke


From alan.gauld at btinternet.com  Mon Jan 22 10:35:01 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 22 Jan 2007 09:35:01 -0000
Subject: [Tutor] Inputting elements of a list
References: <bedebdfb0701220047t6bd8ef4cm9f28faf2da556641@mail.gmail.com>
Message-ID: <ep20g6$6d7$1@sea.gmane.org>


"vanam" <vgvr620034 at gmail.com> wrote
> For standard input from the keyboard raw_input will be used for 
> string and
> input for number.

input can read more than numbers. It will take whatever you type
and try to evaluate it as a Python expression. That's why input is
so dangerous and should be avoided in programs you are distributing
since a malicious user could enter a command that destroys your
data (or worse!).

But for your own use you can do things like:

>>> L = input('Enter a list: ')
Enter a list: [1,2,3,4,'five']
>>> print L
[1, 2, 3, 4, 'five']
>>>

In real programs its better to use raw_input and
convert the string to the expected value, hence to read a number:

n = int( raw_input('enter a number: ') )

to read a list you need to split the input string by some agreed
separator, say commas:

L = raw_input('enter a comma separated list: ')
L = L.split(',')

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From rabidpoobear at gmail.com  Mon Jan 22 10:35:45 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 22 Jan 2007 03:35:45 -0600
Subject: [Tutor] pyw bug ?
In-Reply-To: <200701212049.53814.pythontut@pusspaws.net>
References: <200701212049.53814.pythontut@pusspaws.net>
Message-ID: <45B48571.4090508@gmail.com>

Dave S wrote:
> Hi all,
>
> My GUI app dumps some diagnostic output to the terminal, starting it from an 
> XP terminal, all is well.
>
> Starting it as app.pyw so no terminal is needed - and err - the app randomly 
> locks because the diagnostic output is - backing up ?
Hmm, maybe check where sys.stdout is directed?
-Luke

From rabidpoobear at gmail.com  Mon Jan 22 10:43:01 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 22 Jan 2007 03:43:01 -0600
Subject: [Tutor] Inputting elements of a list
In-Reply-To: <bedebdfb0701220047t6bd8ef4cm9f28faf2da556641@mail.gmail.com>
References: <bedebdfb0701220047t6bd8ef4cm9f28faf2da556641@mail.gmail.com>
Message-ID: <45B48725.3080505@gmail.com>

vanam wrote:
> For standard input from the keyboard raw_input will be used for string 
> and input for number.Suppose i want to input a list of some elements 
> how could it be done. Actually i am looking for sorting out elements 
> in a list.Below is the given script
> list = [45,4,5]
> list.sort()

Don't call your lists 'list', or a character 'chr' or an int 'int'... 
These are all reserved keywords in Python and if you use them as 
variables you'll overwrite the builtins in that scope.
Example:

 >>> int = 1
 >>> int('1000')
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in ?
    int('1000')
TypeError: 'int' object is not callable


HTH,
-Luke

From sanelson at gmail.com  Mon Jan 22 11:06:10 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Mon, 22 Jan 2007 10:06:10 +0000
Subject: [Tutor] Better printing?
Message-ID: <b6131fdc0701220206y68dcf036y8b6df3ba69709422@mail.gmail.com>

Hello,

See below a program that will go through a directory and for each file
print user, group, size and md5sum.

A few questions:

1) It seems to fall over if I pass "." as a directory - how can I stop this?
2) When I wrote the methods I decided to do isafile() checks there,
but subsequently realised that in __main__ it would print out None for
each non-file, so I put the check in here too.  Which is better?  Or
is there a better approach?
3) How can I get this to print in a format that makes it easy to read?
ie tabulated so that the info is presented in aligned columns?

Code follows:

#!/usr/bin/env python

# Standard library imports

import unittest, os, sys, pwd, grp, md5

# Global defines

wp = sys.argv[1]

# Exception classes

# Utility functions

def getSize(fn):
  """Get the size of a file in kb"""
  fp = os.path.join(wp, fn)
  if os.path.isfile(fp):
    return os.stat(fp).st_size

def getUser(fn):
  """Get username of file owner."""
  fp = os.path.join(wp, fn)
  if os.path.isfile(fp):
    uid = os.stat(fp).st_uid
    return pwd.getpwuid(uid).pw_name

def getGroup(fn):
  """Get the group name of the file owner."""
  fp = os.path.join(wp, fn)
  if os.path.isfile(fp):
    gid = os.stat(fp).st_gid
    return grp.getgrgid(gid).gr_name

def md5Sum(fn):
  """Get md5sum for a file."""
  fp = os.path.join(wp, fn)
  if os.path.isfile(fp):
    try:
      fo = open(fp, 'rb')
    except (IOError, OSError):
      print "Could not open file '%s', skipping..." % fp
      return None
    else:
      m = md5.new(fo.read()).hexdigest()
      fo.close()
    return m

# Classes

# Unit tests

class UnitTests(unittest.TestCase):
  """Do not taunt unit tests."""

  def testGetSize(self):
    """Get the size of a file in kb"""
    self.assertEqual(getSize("foo"), 24)

  def testGetUser(self):
    """Get the username of the file owner"""
    self.assertEqual(getUser("foo"), "nelsonst")

  def testGetGroup(self):
    """Get the group name of the file owner"""
    self.assertEqual(getGroup("foo"), "staff")

  def testMd5Sum(self):
    """Get md5sum for file."""
    self.assertEqual(md5Sum("foo"), "faac88479f39ba498e827622a2a4d649")

def doTests():
  suite = unittest.makeSuite(UnitTests,'test')
  runner = unittest.TextTestRunner()
  result = runner.run(suite)

if __name__ == "__main__":
  doTests()
  for f in os.listdir(wp):
    if os.path.isfile(os.path.join(wp, f)):
      print f, getSize(f), getUser(f), getGroup(f), md5Sum(f)

From alan.gauld at btinternet.com  Mon Jan 22 10:23:31 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 22 Jan 2007 09:23:31 +0000 (GMT)
Subject: [Tutor] Are there any MAC OSX python users here?
In-Reply-To: <8249c4ac0701211741g2bbb0a93j853fb4d8493df95b@mail.gmail.com>
Message-ID: <804229.34229.qm@web86111.mail.ird.yahoo.com>

Forwarding to list.

--- Tony Cappellini <cappy2112 at gmail.com> wrote:

> >>They need to start Applications-Utilities->Terminal
> It turned out that the users needed to change the 
> permissions to +x, then the script would be 
> invoked normally.

Ah, but you specifically said it was a command 
line program, so I thought you wanted to run it 
that way. :-)

> writing simple gui launcher to get around that problem.

You could use Applescript for that.

> No- my question to you is-
> I am using a python graphics framework/lib called PyQT/QT.

Is that available for the Mac?

> When I want to deploy it on OSX, how do I get 
> around having to have the user install/compile 
> pyQT/QT on their system?

Unless there are precompiled binaries available 
you don't. I didn't even know Qt was available 
for the Mac.

If you only need a GUI launcher you might be 
better off using the standard Python GUI Tkinter 
which runs on almost any platform that Python 
runs on. Thats why its the standard... wxPython 
also works on Mac but I haven't tried it.

Alan G.



		
___________________________________________________________ 
All new Yahoo! Mail "The new Interface is stunning in its simplicity and ease of use." - PC Magazine 
http://uk.docs.yahoo.com/nowyoucan.html

From kent37 at tds.net  Mon Jan 22 12:05:21 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 22 Jan 2007 06:05:21 -0500
Subject: [Tutor] Better printing?
In-Reply-To: <b6131fdc0701220206y68dcf036y8b6df3ba69709422@mail.gmail.com>
References: <b6131fdc0701220206y68dcf036y8b6df3ba69709422@mail.gmail.com>
Message-ID: <45B49A71.4030802@tds.net>

Steve Nelson wrote:
> Hello,
> 
> See below a program that will go through a directory and for each file
> print user, group, size and md5sum.
> 
> A few questions:
> 
> 1) It seems to fall over if I pass "." as a directory - how can I stop this?

Falls over how?

> 2) When I wrote the methods I decided to do isafile() checks there,
> but subsequently realised that in __main__ it would print out None for
> each non-file, so I put the check in here too.  Which is better?  Or
> is there a better approach?

Are the checks needed in the individual methods? What happens if they 
are passed a non-file? Since you are checking in the main loop, do you care?

> 3) How can I get this to print in a format that makes it easy to read?
> ie tabulated so that the info is presented in aligned columns?

You can print with fixed fields using the string formatting operations.
http://docs.python.org/tut/node9.html#SECTION009100000000000000000
http://docs.python.org/lib/typesseq-strings.html

If you want something even fancier then look at this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662

> def getSize(fn):
>   """Get the size of a file in kb"""
>   fp = os.path.join(wp, fn)
>   if os.path.isfile(fp):
>     return os.stat(fp).st_size
> 
> def getUser(fn):
>   """Get username of file owner."""
>   fp = os.path.join(wp, fn)
>   if os.path.isfile(fp):
>     uid = os.stat(fp).st_uid
>     return pwd.getpwuid(uid).pw_name
> 
> def getGroup(fn):
>   """Get the group name of the file owner."""
>   fp = os.path.join(wp, fn)
>   if os.path.isfile(fp):
>     gid = os.stat(fp).st_gid
>     return grp.getgrgid(gid).gr_name

These functions are using the global variable wp. A better design would 
be to compute the full file path once in the main loop and pass it in.

The above three functions have a lot in common and they are always 
called together. You could combine them into one function that returns a 
tuple of size, user, group.

Kent

> 
> def md5Sum(fn):
>   """Get md5sum for a file."""
>   fp = os.path.join(wp, fn)
>   if os.path.isfile(fp):
>     try:
>       fo = open(fp, 'rb')
>     except (IOError, OSError):
>       print "Could not open file '%s', skipping..." % fp
>       return None
>     else:
>       m = md5.new(fo.read()).hexdigest()
>       fo.close()
>     return m
> 
> # Classes
> 
> # Unit tests
> 
> class UnitTests(unittest.TestCase):
>   """Do not taunt unit tests."""
> 
>   def testGetSize(self):
>     """Get the size of a file in kb"""
>     self.assertEqual(getSize("foo"), 24)
> 
>   def testGetUser(self):
>     """Get the username of the file owner"""
>     self.assertEqual(getUser("foo"), "nelsonst")
> 
>   def testGetGroup(self):
>     """Get the group name of the file owner"""
>     self.assertEqual(getGroup("foo"), "staff")
> 
>   def testMd5Sum(self):
>     """Get md5sum for file."""
>     self.assertEqual(md5Sum("foo"), "faac88479f39ba498e827622a2a4d649")
> 
> def doTests():
>   suite = unittest.makeSuite(UnitTests,'test')
>   runner = unittest.TextTestRunner()
>   result = runner.run(suite)
> 
> if __name__ == "__main__":
>   doTests()
>   for f in os.listdir(wp):
>     if os.path.isfile(os.path.join(wp, f)):
>       print f, getSize(f), getUser(f), getGroup(f), md5Sum(f)
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



From kent37 at tds.net  Mon Jan 22 12:07:32 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 22 Jan 2007 06:07:32 -0500
Subject: [Tutor] direction and draw
In-Reply-To: <1d987df30701212256r7f02aa3an8a27d5348d531f76@mail.gmail.com>
References: <1d987df30701212256r7f02aa3an8a27d5348d531f76@mail.gmail.com>
Message-ID: <45B49AF4.3030008@tds.net>

linda.s wrote:
> I have a segment (two ending points are A and B) which is 0 degree.
> How to draw a segment with 10 degrees and 15 in length?

Presumably you mean, how to draw a segment on screen? Are you using a 
GUI toolkit? Which one?

Kent


From rdm at rcblue.com  Mon Jan 22 13:08:43 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 22 Jan 2007 04:08:43 -0800
Subject: [Tutor] How to import this program, and other questions
Message-ID: <7.0.1.0.2.20070122040832.074765a8@rcblue.com>

At 01:56 AM 1/22/2007, ALAN GAULD wrote:

>--- Dick Moores <rdm at rcblue.com> wrote:
>
> > > ...Is the answer to put all 3 functions inside one big
> > > one?
> > >
> > Probably not, its more likely to be a small function
> > that checks its input parameters and calls one of
> > the 3 worker functions.
>
> > Yes. I just realized that I quoted the link wrong. Try
> > <http://www.rcblue.com/Python/clnumDivision_for-web.py>
>
>OK, Now I've seen the code I need a few more
>clues about how you would expose this code?
>
>It seems at first glance as if your main() function
>could just be renamed and made to use parameters and
>it would act as the driver?
>
> > you meant by "a small function that checks its input
> > parameters and calls one of the 3 worker functions."?
>
>I should have said "one or more" but essentially
>your main function does what I meant. If you rename
>it to something more meaningful and add input parameters
>it should be all you need.
>
>Something ike this:
>
>def precision_divide(x,y,digits):
>     s = clnumDiv(x, y, digits)
>     s = numberRounding(s, digits)
>     s = sciNotation(s)
>     return s
>
>Notice I've also made it return s rather than
>print it since thats better practice and more reusable.
>You might want to consider naming x,y
>numerator/denominator to make it more obvious which
>is which. And add a doc string for help() to find.
>
>Then you can just import as usual:
>
>from clnumDivision import precision_divide

Thanks, Alan. Did you see my later reply to myself?

=================================================================
I've been experimenting, and came up with this solution. At least it 
works. I slightly rewrote < 
http://www.rcblue.com/Python/clnumDivision_for-web.py> as clnumDiv.py
(< http://www.rcblue.com/Python/clnumDiv.py>) and put it in
E:\Python25\Lib\site-packages\mine and can now import by
from mine.clnumDiv import clnumDiv
or by
from mine.clnumDiv import clnumDiv as div

I can use this in other scripts, or at the interactive prompt:

from mine.clnumDiv import clnumDiv as div
 >>> x = '1234.5678567856785678567856786586'
 >>> y = '-.00098769876897687654654'
 >>> prec = 50
 >>> div(x, y, prec)
'-1.2499437030427053037075454076437920433253956536740E+006'
 >>>

As I said, this works, but is clnumDiv.py organized correctly pythonically?

Also, I'm still hoping for some suggestions about the details of the code.
=====================================================

So you can see I'd already pretty much implemented what you suggest 
(I think), except for some naming changes, and the doc string. Any 
comments on the code itself? Are there easier ways to do some of the 
things I've done?

As I said, this program is for myself, and I'd like to keep the 
"clnum" string in the function names (I'm writing a bunch of them). 
Using numerator and denominator as arguments in function defs is a 
lot better than x and y, I agree. Or maybe dividend and divisor.

Dick





From ajkadri at googlemail.com  Mon Jan 22 14:38:15 2007
From: ajkadri at googlemail.com (Asrarahmed Kadri)
Date: Mon, 22 Jan 2007 13:38:15 +0000
Subject: [Tutor] Can we add labels to tkinter canvas..?
Message-ID: <b4e894c70701220538n435c9d90je6194e0efc30d338@mail.gmail.com>

Hello Folks,

Is it possible to add a Label to tkinter canvas or i'll need to use
create_text method ?

Thanks in anticipation..


Best Regards,

Asrarahmed Kadri


-- 
To HIM you shall return.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070122/e14e3a02/attachment.htm 

From tinoloc at gmail.com  Mon Jan 22 17:43:04 2007
From: tinoloc at gmail.com (Tino Dai)
Date: Mon, 22 Jan 2007 11:43:04 -0500
Subject: [Tutor] Variables of Variables
In-Reply-To: <Pine.LNX.4.64.0701181514020.4796@hkn.eecs.berkeley.edu>
References: <e033edfb0701181315k27ce76e5ld742f85a4c65e8fd@mail.gmail.com>
	<5e58f2e40701181355k22d939c9lcd3b4687222d6f98@mail.gmail.com>
	<Pine.LNX.4.64.0701181514020.4796@hkn.eecs.berkeley.edu>
Message-ID: <e033edfb0701220843m5a44f001i4e071b8b9c93d1c7@mail.gmail.com>

On 1/18/07, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
> > Rather than storing your data as variables, you could store it in a
> > dictionary.  Then you can dynamically access data however you like..
>
> Suggesting a dictionary here is right.
>
> ** Stuff deleted about why using variables of variables is bad ***


Actually, I started off with a dictionary with a bunch of parameters. To
give you some background, I writing my
first GUI, and using the parameters in a dictionary to control what box the
GUI displays next. So, it looks
something that looks like this:

data={'position':'middle','next':'self.add_entry_db
(widget,None)','previous':'self.add_entry(widget,None)'}

The dictionary called data gets passed to a button maker function that will
show various buttons depending on
the position value in the data dictionary. The clicked signal is then hooked
up to a callback function (I think that's
what you call it), and the next/previous values get sent up to various
functions. An example one of these various functions
is:

    def add_next_button(self,widget,Data=None):
        self.dbTableName=self.addEntryBox.get_text()
        self.addWin.destroy()
        if type(Data) == type(None):
            print "Why are we here?"
            exit()
        print Data
        Data()

where the Data variable is 'self.add_entry_db(widget,None)'. How do I pass
the Data variable to the add_next_button so
that the contents itself the data variable can execute?

Thanks,
Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070122/6e2eaec7/attachment.htm 

From dyoo at hkn.eecs.berkeley.edu  Mon Jan 22 18:10:11 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 22 Jan 2007 09:10:11 -0800 (PST)
Subject: [Tutor] Variables of Variables
In-Reply-To: <e033edfb0701220843m5a44f001i4e071b8b9c93d1c7@mail.gmail.com>
References: <e033edfb0701181315k27ce76e5ld742f85a4c65e8fd@mail.gmail.com> 
	<5e58f2e40701181355k22d939c9lcd3b4687222d6f98@mail.gmail.com> 
	<Pine.LNX.4.64.0701181514020.4796@hkn.eecs.berkeley.edu>
	<e033edfb0701220843m5a44f001i4e071b8b9c93d1c7@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0701220853530.2342@hkn.eecs.berkeley.edu>


> Actually, I started off with a dictionary with a bunch of parameters. To
> give you some background, I writing my
> first GUI, and using the parameters in a dictionary to control what box the
> GUI displays next. So, it looks
> something that looks like this:
>
> data={'position':'middle',
>       'next':'self.add_entry_db (widget,None)',
>       'previous':'self.add_entry(widget,None)'}

Hi Tino,


Ok, so it looks like you're trying to encode the idea that, when 'next' is 
pressed, then the content of:

     'self.add_entry_db (widget,None)'

should fire off.  A good way to say this in Python is to say that 'next' 
refers to a function.


Let's do a quick refresher.  Functions can be held without them 
immediately firing off.  For example:

###############################
>>> def square(x):
...     return x * x
...
>>> square
<function square at 0xb7da9d84>
###############################

You may have left out the parentheses by accident and wondered why Python 
lets us do this: isn't it obvious that functions are meant to be called?


But this time, we are going to leave off the parens deliberately.  *grin* 
If you twist your mind enough, you can analogize this with "numbers" and 
"strings" by thinking of "functions" as just another data type.

And like those other data types, we can actually stuff functions in as 
dictionary values:

############################
>>> cmds = { '^2' : square,
...          '*2' : double }
############################

This 'cmds' is a dictionary from strings to functions!  And, weird as it 
might look, we can do the following:

###############################
>>> cmds['^2']
<function square at 0xb7da9d84>
>>>
>>> cmds['^2'](42)
1764
>>> cmds['*2'](42)
84
###############################

That is, we pull the function out of the dictionary, and then call it. 
That's the key idea we can take advantage of for your problem.



Looking back at the definition of data:

###############################################
data={'position':'middle',
       'next':'self.add_entry_db (widget,None)',
       'previous':'self.add_entry(widget,None)'}
###############################################

we can change things a bit, and make 'next' and 'previous' refer to 
functions that eat widgets:

###################################################
     ## [in the context where data is being defined]
     def next_cmd(widget):
         self.add_entry_db(widget,None)

     def previous_cmd(widget):
         self.add_entry(widget, None)

     data = { 'position' : 'middle',
              'next' : next_cmd,
              'previous' : previous_cmd }
###################################################


That is, we're building two functions on the fly and just adding them to 
our data.



Later on, when we are in your callback, the Data values are going to be 
functions that are just waiting to fire.


> The dictionary called data gets passed to a button maker function that 
> will show various buttons depending on the position value in the data 
> dictionary. The clicked signal is then hooked up to a callback function 
> (I think that's what you call it), and the next/previous values get sent 
> up to various functions. An example one of these various functions is:
>
>   def add_next_button(self,widget,Data=None):
>       self.dbTableName=self.addEntryBox.get_text()
>       self.addWin.destroy()
>       if type(Data) == type(None):
>           print "Why are we here?"
>           exit()
>       print Data
>       Data()


Yup.  With the changes above, this becomes:

###################################################
    def add_next_button(self,widget,Data=None):
        self.dbTableName=self.addEntryBox.get_text()
        self.addWin.destroy()
        if type(Data) == type(None):
            print "Why are we here?"
            exit()
        Data(widget)
###################################################



> where the Data variable is 'self.add_entry_db(widget,None)'. How do I 
> pass the Data variable to the add_next_button so that the contents 
> itself the data variable can execute?

Learn how to treat functions as data.  That's really what you are asking 
for.  If you have questions about this, please feel free to ask.

From alan.gauld at btinternet.com  Mon Jan 22 18:44:36 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 22 Jan 2007 17:44:36 -0000
Subject: [Tutor] Better printing?
References: <b6131fdc0701220206y68dcf036y8b6df3ba69709422@mail.gmail.com>
Message-ID: <ep2t66$f1g$1@sea.gmane.org>


"Steve Nelson" <sanelson at gmail.com> wrote 

> def getSize(fn):
>  """Get the size of a file in kb"""
>  fp = os.path.join(wp, fn)
>  if os.path.isfile(fp):
>    return os.stat(fp).st_size

One problem with all of these is that you only return 
a value if it is a file. If its not a file you return None
(the default return value). It would be easier to maintain 
if you make the return explicit.

Personally I would probably raise an exception 
(maybe a TypeError) if it's not a file. That puts the onus 
on the client to check that they pass something that 
you can get the size of - or use a try/except to catch 
the invalid entries..

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld at btinternet.com  Mon Jan 22 18:47:14 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 22 Jan 2007 17:47:14 -0000
Subject: [Tutor] Can we add labels to tkinter canvas..?
References: <b4e894c70701220538n435c9d90je6194e0efc30d338@mail.gmail.com>
Message-ID: <ep2tb4$glr$1@sea.gmane.org>


"Asrarahmed Kadri" <ajkadri at googlemail.com> wrote in message 
news:b4e894c70701220538n435c9d90je6194e0efc30d338 at mail.gmail.com...
> Hello Folks,
>
> Is it possible to add a Label to tkinter canvas or i'll need to use
> create_text method ?

What exactly do you expect a label in a canvas to do?
Or to look like?

You can attach a label to a canvas externally by wrapping them
in a single Frame, does that do what you want? Othewise just
putting a bit of text onto the canvas itself seems the best bet.
What would the lavbel do for you that a bit of text wouldn't?

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From klappnase at freenet.de  Mon Jan 22 20:23:56 2007
From: klappnase at freenet.de (Michael Lange)
Date: Mon, 22 Jan 2007 20:23:56 +0100
Subject: [Tutor] Can we add labels to tkinter canvas..?
In-Reply-To: <ep2tb4$glr$1@sea.gmane.org>
References: <b4e894c70701220538n435c9d90je6194e0efc30d338@mail.gmail.com>
	<ep2tb4$glr$1@sea.gmane.org>
Message-ID: <20070122202356.723fc4f2.klappnase@freenet.de>

On Mon, 22 Jan 2007 17:47:14 -0000
"Alan Gauld" <alan.gauld at btinternet.com> wrote:

> 
> "Asrarahmed Kadri" <ajkadri at googlemail.com> wrote in message 
> news:b4e894c70701220538n435c9d90je6194e0efc30d338 at mail.gmail.com...
> > Hello Folks,
> >
> > Is it possible to add a Label to tkinter canvas or i'll need to use
> > create_text method ?
> 
> What exactly do you expect a label in a canvas to do?
> Or to look like?
> 
> You can attach a label to a canvas externally by wrapping them
> in a single Frame, does that do what you want? Othewise just
> putting a bit of text onto the canvas itself seems the best bet.
> What would the lavbel do for you that a bit of text wouldn't?
> 

Or put a label (or any other widget) onto the canvas using the create_window()
method (though I don't know what's the benefit of a label over some text or image).

Michael

From ajkadri at googlemail.com  Mon Jan 22 21:14:31 2007
From: ajkadri at googlemail.com (Asrarahmed Kadri)
Date: Mon, 22 Jan 2007 20:14:31 +0000
Subject: [Tutor] problem with canvas.postscript()
Message-ID: <b4e894c70701221214l77cd6fccrccc6358f2d5c9ad0@mail.gmail.com>

Hi folks,

I am trying to save a tkinter canvas using canvas.postscript() method...

The thing works fine when the canvas size is small; but it gets cut (from
the top and left side) when the size increases..
Here is the code:

c.postscript(file=filename,height = canvas_height,width =
canvas_width,colormode='color',pagex=200,pagey=250)

The image also gets printed very low on the page in the postscript file..??

Can anybody help me to fix the problem..?

Thanks in anticipation.

Best Regards,
Asrarahmed
-- 
To HIM you shall return.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070122/f7560e48/attachment.htm 

From janos.juhasz at VELUX.com  Mon Jan 22 23:20:25 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Mon, 22 Jan 2007 23:20:25 +0100
Subject: [Tutor] direction and draw
In-Reply-To: <mailman.9155.1169487907.32030.tutor@python.org>
Message-ID: <OF153A2FAB.57ED4BAB-ONC125726B.0077B780-C125726B.007AB7CA@velux.com>

Dear Linda,

> I have a segment (two ending points are A and B) which is 0 degree.
> How to draw a segment with 10 degrees and 15 in length?
It is very simple with complex numbers:

import math

class vect:
    ## begin and end are tuples (x, y)
    ## and represented as complex numbers
    def __init__(self, begin, end):
        self.begin = complex(begin[0], begin[1])
        self.end = complex(end[0], end[1])

    def Rotate(self, deg=0):
        rad = math.radians(deg)
        rot = complex(math.cos(rad), math.sin(rad))
        self.end = self.begin + (self.end-self.begin)*rot

    def SetLength(self, length):
        dist = self.end - self.begin
        actlength = math.sqrt(dist.real**2 + dist.imag**2)
        dist = dist * length / actlength
        self.end = self.begin + dist

    def __str__(self):
        return '(%.2f, %.2f)->(%.2f, %.2f)' % \
               (self.begin.real, self.begin.imag, self.end.real, 
self.end.imag)


v = vect((10,0),(20,0))
print 'orig:', v
v.Rotate(10)
print 'rotated:', v
v.SetLength(15)
print 'sretched:', v



It seems to be a kind of homework, 
but I wanted to test how can I response in a thread.

All of my earlier responses started new threads in this list like this 
http://mail.python.org/pipermail/tutor/2007-January/052169.html.

Have I remove the '[Tutor]' or '[Tutor] ' from the subject of the response 
? 
Do I need any special about the mail in notes ?


[Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 
[Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress   Geoframer 
[Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress   Geoframer 
[Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress   Geoframer 
[Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress   Danny Yoo 
[Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 
[Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 
[Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress   Kent Johnson 
[Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 


I don't understand how these threads are built up. The subject fields 
seems to be identicals.
Is there used anything else than the subject field for recognize the base 
of the response ?

RTFM about how to respond to this list is welcomed with valuable links.


Regards:
___________
Janos Juhasz

From kim.branson at gmail.com  Mon Jan 22 23:50:14 2007
From: kim.branson at gmail.com (Kim Branson)
Date: Mon, 22 Jan 2007 14:50:14 -0800
Subject: [Tutor] metaclass question
Message-ID: <DD1B7C36-BF48-4DAF-8DCF-DA30933C095D@gmail.com>

Hi i'm interested in implementing a factoryclass in python

What i'd like to do is have my factoryClass produce an instance of a  
class with some methods defined in arguments to the factory class.

The classes that are produced have many common methods, but a single  
unique method. This method actually is a series of calls to a c++ api.
Depending on what we are doing with the produced class, i'd like the  
unique method to call api function A, or api function B etc.   
Alternatively the unique method might call A and the B and return a  
dict of the results.

I'm doing this because i'd like all my produced class instances to  
simply have  a calculateResults method which will then go and do the  
right thing.  I don't want to set some values in the init, like A==  
True  and have a if A: call methodA etc statement.

I'm not sure if a factory class is the best way to solve this  
problem, but i can see future cases where the unique function will  
need to do many things with intermediate results before returning the  
results dict.   i think a factory class might be the best way of  
ensuring an extensible design.

So whats the best way to do this. I have found many references to  
creating a class with __metaclass__ = SomeMetaClass,  but i don't see  
how one can pass arguments to the meta class.

An alternative might be to have a class that operates on an existing  
instance and adds the correct method, but this seems slightly clunky,  
and is probably not the python way


Cheers

Kim



From markusro at element.fkp.physik.tu-darmstadt.de  Tue Jan 23 00:05:48 2007
From: markusro at element.fkp.physik.tu-darmstadt.de (Markus Rosenstihl)
Date: Tue, 23 Jan 2007 00:05:48 +0100
Subject: [Tutor] Are there any MAC OSX python users here?
In-Reply-To: <804229.34229.qm@web86111.mail.ird.yahoo.com>
References: <804229.34229.qm@web86111.mail.ird.yahoo.com>
Message-ID: <4d702ec32ea6c54297209163e591ced1@element.fkp.physik.tu-darmstadt.de>


Am 22.01.2007 um 10:23 schrieb ALAN GAULD:

> Forwarding to list.
>
> --- Tony Cappellini <cappy2112 at gmail.com> wrote:
>
>>>> They need to start Applications-Utilities->Terminal
>> It turned out that the users needed to change the
>> permissions to +x, then the script would be
>> invoked normally.
>
> Ah, but you specifically said it was a command
> line program, so I thought you wanted to run it
> that way. :-)
>
>> writing simple gui launcher to get around that problem.
>
> You could use Applescript for that.

Or, for simple scripts to be started by "double clicking":

http://www.sveinbjorn.org/platypus

It's a lovely program.

regards

Markus
-------------- next part --------------
A non-text attachment was scrubbed...
Name: PGP.sig
Type: application/pgp-signature
Size: 186 bytes
Desc: Signierter Teil der Nachricht
Url : http://mail.python.org/pipermail/tutor/attachments/20070123/5fe94b09/attachment.pgp 

From andreas at kostyrka.org  Tue Jan 23 00:11:49 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Tue, 23 Jan 2007 00:11:49 +0100
Subject: [Tutor] metaclass question
In-Reply-To: <DD1B7C36-BF48-4DAF-8DCF-DA30933C095D@gmail.com>
References: <DD1B7C36-BF48-4DAF-8DCF-DA30933C095D@gmail.com>
Message-ID: <20070122231149.GF20537@andi-lap.la.revver.com>

Technically, you don't need metaclasses probably:

class A(object):
    def methA(self, abc):
        pass
    def methB(self, def, ghi):
        pass
    def defaultMethod(self):
        raise UnknownMethodError()
    def __init__(self, methodName):
        self._calc = getattr(self, "meth%s" % methodName, self.defaultMethod)
    def calcResult(self, *args, **kw):
        return self._calc(*args, **kw)

a=A("A")
b=A("B")

a.calcResult(123)
b.calcResult(234, 345)
a.calcResult(1,2) => TypeError
b.calcResult(1) => TypeError

metaclasses in Python are a way to get control of the class creation
process. E.g. it's quite useful if you need to do some changes to some
classes, no matter what.

(E.g. I've implemented a class where methods can be synchronized (by
using a lock) with a metaclass => the meta class makes sure that all
methods get wrapped with a function that acquires and releases the
needed locks.)

Andreas

* Kim Branson <kim.branson at gmail.com> [070122 23:51]:
> Hi i'm interested in implementing a factoryclass in python
> 
> What i'd like to do is have my factoryClass produce an instance of a  
> class with some methods defined in arguments to the factory class.
> 
> The classes that are produced have many common methods, but a single  
> unique method. This method actually is a series of calls to a c++ api.
> Depending on what we are doing with the produced class, i'd like the  
> unique method to call api function A, or api function B etc.   
> Alternatively the unique method might call A and the B and return a  
> dict of the results.
> 
> I'm doing this because i'd like all my produced class instances to  
> simply have  a calculateResults method which will then go and do the  
> right thing.  I don't want to set some values in the init, like A==  
> True  and have a if A: call methodA etc statement.
> 
> I'm not sure if a factory class is the best way to solve this  
> problem, but i can see future cases where the unique function will  
> need to do many things with intermediate results before returning the  
> results dict.   i think a factory class might be the best way of  
> ensuring an extensible design.
> 
> So whats the best way to do this. I have found many references to  
> creating a class with __metaclass__ = SomeMetaClass,  but i don't see  
> how one can pass arguments to the meta class.
> 
> An alternative might be to have a class that operates on an existing  
> instance and adds the correct method, but this seems slightly clunky,  
> and is probably not the python way
> 
> 
> Cheers
> 
> Kim
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From alan.gauld at btinternet.com  Tue Jan 23 00:15:54 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 22 Jan 2007 23:15:54 -0000
Subject: [Tutor] metaclass question
References: <DD1B7C36-BF48-4DAF-8DCF-DA30933C095D@gmail.com>
Message-ID: <ep3gjb$sdl$1@sea.gmane.org>


"Kim Branson" <kim.branson at gmail.com> wrote in message 
news:DD1B7C36-BF48-4DAF-8DCF-DA30933C095D at gmail.com...
> Hi i'm interested in implementing a factoryclass in python
>
> What i'd like to do is have my factoryClass produce an instance of a
> class with some methods defined in arguments to the factory class.
>
> The classes that are produced have many common methods, but a single
> unique method. This method actually is a series of calls to a c++ 
> api.

It sounds like you could create the basic class as normal but
pass in the appropriate function to the init constructor. Then
instead of making it a method create a metjod that calls that
function, something like this:

class C:
    def __init__(self, myfunc):
       self.func = myfunc
    def driver(self,params_as_needed):
       return self.func(params_as_needed)
    def common1(self....)
    etc...

Now you can create instances like:

def f1(....):...
def f2(...)....

c = C(f1)
d = C(f2)

etc.

Is that what you want?

Alan G. 



From kent37 at tds.net  Tue Jan 23 02:14:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 22 Jan 2007 20:14:48 -0500
Subject: [Tutor] metaclass question
In-Reply-To: <DD1B7C36-BF48-4DAF-8DCF-DA30933C095D@gmail.com>
References: <DD1B7C36-BF48-4DAF-8DCF-DA30933C095D@gmail.com>
Message-ID: <45B56188.2090804@tds.net>

Kim Branson wrote:
> Hi i'm interested in implementing a factoryclass in python
> 
> What i'd like to do is have my factoryClass produce an instance of a  
> class with some methods defined in arguments to the factory class.
> 
> The classes that are produced have many common methods, but a single  
> unique method. This method actually is a series of calls to a c++ api.
> Depending on what we are doing with the produced class, i'd like the  
> unique method to call api function A, or api function B etc.   
> Alternatively the unique method might call A and the B and return a  
> dict of the results.
> 
> I'm doing this because i'd like all my produced class instances to  
> simply have  a calculateResults method which will then go and do the  
> right thing.  I don't want to set some values in the init, like A==  
> True  and have a if A: call methodA etc statement.

Do you need to be passing in the unique method, or can you just make a 
base class with the common methods and subclasses that define their 
unique methods? For example,

class Base(object):
   def a(self):
     pass
   def b(self):
     pass
   def calculateResults(self):
     raise NotImplementedError

class A(Base):
   def calculateResults(self):
     return self.a() * self.b()

class B(Base):
   def calculateResults(self):
     return dict(a=self.a(), b=self.b())

Kent


From kent37 at tds.net  Tue Jan 23 02:21:46 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 22 Jan 2007 20:21:46 -0500
Subject: [Tutor] direction and draw
In-Reply-To: <OF153A2FAB.57ED4BAB-ONC125726B.0077B780-C125726B.007AB7CA@velux.com>
References: <OF153A2FAB.57ED4BAB-ONC125726B.0077B780-C125726B.007AB7CA@velux.com>
Message-ID: <45B5632A.9050605@tds.net>

J?nos Juh?sz wrote:
> I wanted to test how can I response in a thread.
> 
> All of my earlier responses started new threads in this list like this 
> http://mail.python.org/pipermail/tutor/2007-January/052169.html.
> 
> Have I remove the '[Tutor]' or '[Tutor] ' from the subject of the response 
> ? 
> Do I need any special about the mail in notes ?

You did fine. You don't have to edit the subject line, just reply to the 
message.

> [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress   Karl 
> Wittgenstein 
> <etc>
> 
> I don't understand how these threads are built up. The subject fields 
> seems to be identicals.
> Is there used anything else than the subject field for recognize the base 
> of the response ?

Yes, email contains many headers which contain information about the 
email. Your mail client may let you view the headers, for example in 
Thunderbird you can choose View / Message source to see the actual text 
of the email.

I'm not sure which header(s) are used for the threading; perhaps 
In-Reply-To.

Kent


From bgailer at alum.rpi.edu  Tue Jan 23 04:43:38 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 22 Jan 2007 19:43:38 -0800
Subject: [Tutor] Inputting elements of a list
In-Reply-To: <45B48725.3080505@gmail.com>
References: <bedebdfb0701220047t6bd8ef4cm9f28faf2da556641@mail.gmail.com>
	<45B48725.3080505@gmail.com>
Message-ID: <45B5846A.9010900@alum.rpi.edu>

Luke Paireepinart wrote:
> vanam wrote:
>   
>> For standard input from the keyboard raw_input will be used for string 
>> and input for number.Suppose i want to input a list of some elements 
>> how could it be done. Actually i am looking for sorting out elements 
>> in a list.Below is the given script
>> list = [45,4,5]
>> list.sort()
>>     
>
> Don't call your lists 'list', or a character 'chr' or an int 'int'... 
> These are all reserved keywords in Python
actually they are built-in functions / types. Reserved words (for, if, 
def, ....) can't be used for anything else.
>  and if you use them as 
> variables you'll overwrite the builtins in that scope.
> Example:
>
>  >>> int = 1
>  >>> int('1000')
> Traceback (most recent call last):
>   File "<pyshell#5>", line 1, in ?
>     int('1000')
> TypeError: 'int' object is not callable
>
>
> HTH,
> -Luke
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454


From klappnase at freenet.de  Tue Jan 23 10:56:26 2007
From: klappnase at freenet.de (Michael Lange)
Date: Tue, 23 Jan 2007 10:56:26 +0100
Subject: [Tutor] problem with canvas.postscript()
In-Reply-To: <b4e894c70701221214l77cd6fccrccc6358f2d5c9ad0@mail.gmail.com>
References: <b4e894c70701221214l77cd6fccrccc6358f2d5c9ad0@mail.gmail.com>
Message-ID: <20070123105626.2059bc72.klappnase@freenet.de>

On Mon, 22 Jan 2007 20:14:31 +0000
"Asrarahmed Kadri" <ajkadri at googlemail.com> wrote:

> Hi folks,
> 
> I am trying to save a tkinter canvas using canvas.postscript() method...
> 
> The thing works fine when the canvas size is small; but it gets cut (from
> the top and left side) when the size increases..
> Here is the code:
> 
> c.postscript(file=filename,height = canvas_height,width =
> canvas_width,colormode='color',pagex=200,pagey=250)
> 
> The image also gets printed very low on the page in the postscript file..??
> 
> Can anybody help me to fix the problem..?
> 
> Thanks in anticipation.
> 

Have you tried to omit the pagex and pagey options, if you call postscript
without any options (except filename) the whole canvas should be centered on
the page.

Michael

From gizmo1 at gmail.com  Tue Jan 23 12:16:09 2007
From: gizmo1 at gmail.com (Gizmo)
Date: Tue, 23 Jan 2007 03:16:09 -0800
Subject: [Tutor] Some "type" confusion...
Message-ID: <5d2e4d280701230316w79c9008elf1854c3ecc779313@mail.gmail.com>

Hello
I am learning Python via the excellent Dive Into Python book. I have little
question

1)
>>> import os
>>> type(os.environ)
<type 'instance'>

Why is this considered "instance" ? Should'nt it be "dict" type?
I have a feeling I am missing something deeper here.

2) What would happen if I did this
>>> os.environ = {}
Hopefully, I wont be allowed to do that...but I am too scared to try.

Sincere Regards,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070123/21c84d52/attachment.html 

From kent37 at tds.net  Tue Jan 23 14:11:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 23 Jan 2007 08:11:05 -0500
Subject: [Tutor] Some "type" confusion...
In-Reply-To: <5d2e4d280701230316w79c9008elf1854c3ecc779313@mail.gmail.com>
References: <5d2e4d280701230316w79c9008elf1854c3ecc779313@mail.gmail.com>
Message-ID: <45B60969.2070300@tds.net>

Gizmo wrote:
> Hello
> I am learning Python via the excellent Dive Into Python book. I have 
> little question
> 
> 1)
>  >>> import os
>  >>> type(os.environ)
> <type 'instance'>
> 
> Why is this considered "instance" ? Should'nt it be "dict" type?
> I have a feeling I am missing something deeper here.

'instance' is the type of instances of old-style classes. For example:

In [4]: class Foo: pass
    ...:

In [6]: f=Foo()

In [7]: type(f)
Out[7]: <type 'instance'>

On the other hand, the type of an instance of a new-style class reflects 
its actual class:

In [9]: class Bar(object): pass
    ...:

In [10]: b=Bar()

In [11]: type(b)
Out[11]: <class '__main__.Bar'>

You can find out the class of an instance by looking at its __class__ 
attribute:
In [3]: os.environ.__class__
Out[3]: <class os._Environ at 0x00B42F30>

You can also see the base classes of the class:
In [8]: os.environ.__class__.__bases__
Out[8]: (<class UserDict.IterableUserDict at 0x00B4E1E0>,)

So os.environ is not a dict or a subclass of dict. It is a subclass of 
UserDict.IterableUserDict. This is a class that is used to make custom 
mapping objects.

If you look at the docs for os.environ you see that it does not say it 
is a dict, it says it is a mapping object; that is, it is something that 
acts like a dict.

See also http://docs.python.org/ref/node33.html

> 2) What would happen if I did this
>  >>> os.environ = {}
> Hopefully, I wont be allowed to do that...but I am too scared to try.

You can do it. That would replace the os.environ object with an empty 
dict, which would have a bad effect on any code that reads values from 
os.environ. On the other hand you can restore the old value just by 
restarting Python so it is not such a disaster.

Kent


From vgvr620034 at gmail.com  Tue Jan 23 15:55:39 2007
From: vgvr620034 at gmail.com (vanam)
Date: Tue, 23 Jan 2007 20:25:39 +0530
Subject: [Tutor] Difference between filter and map
Message-ID: <bedebdfb0701230655n6938ec8fic2b98eebc2745609@mail.gmail.com>

i want to know the difference between filter(function,sequence) and
map(function,sequence).I tried for a simple script with an function which
finds the square of the number,after including separately filter and map in
the script i am getting the same results for instance
def squ(x):
     return x*x
filter(squ,range(1,3))->1,4(output)
map(squ,range(1,3)->1,4(output)

-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070123/981cc04f/attachment.htm 

From kent37 at tds.net  Tue Jan 23 16:10:41 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 23 Jan 2007 10:10:41 -0500
Subject: [Tutor] Difference between filter and map
In-Reply-To: <bedebdfb0701230655n6938ec8fic2b98eebc2745609@mail.gmail.com>
References: <bedebdfb0701230655n6938ec8fic2b98eebc2745609@mail.gmail.com>
Message-ID: <45B62571.70809@tds.net>

vanam wrote:
> i want to know the difference between filter(function,sequence) and 
> map(function,sequence).I tried for a simple script with an function 
> which finds the square of the number,after including separately filter 
> and map in the script i am getting the same results for instance
> def squ(x):
>      return x*x
> filter(squ,range(1,3))->1,4(output)
> map(squ,range(1,3)->1,4(output)

Are you sure about that? I get

In [1]: def sq(x): return x*x
    ...:

In [2]: filter(sq, range(3))
Out[2]: [1, 2]

In [3]: map(sq, range(3))
Out[3]: [0, 1, 4]

map(fn, lst) returns a new list with fn applied to each element of lst. 
In terms of list comprehensions, it is [ fn(x) for x in lst ].

filter(fn, lst) returns a new list containing all elements of the 
original list for which fn(x) is true. As a list comprehension, it is
[ x for x in lst if fn(x) ]

Kent


From vgvr620034 at gmail.com  Tue Jan 23 16:21:42 2007
From: vgvr620034 at gmail.com (vanam)
Date: Tue, 23 Jan 2007 20:51:42 +0530
Subject: [Tutor] Difference between filter and map
In-Reply-To: <45B62571.70809@tds.net>
References: <bedebdfb0701230655n6938ec8fic2b98eebc2745609@mail.gmail.com>
	<45B62571.70809@tds.net>
Message-ID: <bedebdfb0701230721h387684a8he81b7308429b5d4a@mail.gmail.com>

ya i am sure about that i am using python editor which has python
intrepreter attached to it i got the same output for both filter and map
def squ(n):
   y = n*n
  print y
filter(y,range(3))->0  1 4
map(y,range(3))->0 1 4

On 1/23/07, Kent Johnson <kent37 at tds.net> wrote:
>
> vanam wrote:
> > i want to know the difference between filter(function,sequence) and
> > map(function,sequence).I tried for a simple script with an function
> > which finds the square of the number,after including separately filter
> > and map in the script i am getting the same results for instance
> > def squ(x):
> >      return x*x
> > filter(squ,range(1,3))->1,4(output)
> > map(squ,range(1,3)->1,4(output)
>
> Are you sure about that? I get
>
> In [1]: def sq(x): return x*x
>     ...:
>
> In [2]: filter(sq, range(3))
> Out[2]: [1, 2]
>
> In [3]: map(sq, range(3))
> Out[3]: [0, 1, 4]
>
> map(fn, lst) returns a new list with fn applied to each element of lst.
> In terms of list comprehensions, it is [ fn(x) for x in lst ].
>
> filter(fn, lst) returns a new list containing all elements of the
> original list for which fn(x) is true. As a list comprehension, it is
> [ x for x in lst if fn(x) ]
>
> Kent
>
>


-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070123/0cc5e8eb/attachment.html 

From dyoo at hkn.eecs.berkeley.edu  Tue Jan 23 16:33:55 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 23 Jan 2007 07:33:55 -0800 (PST)
Subject: [Tutor] Difference between filter and map
In-Reply-To: <bedebdfb0701230655n6938ec8fic2b98eebc2745609@mail.gmail.com>
References: <bedebdfb0701230655n6938ec8fic2b98eebc2745609@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0701230724210.29472@hkn.eecs.berkeley.edu>



On Tue, 23 Jan 2007, vanam wrote:

> i want to know the difference between filter(function,sequence) and
> map(function,sequence).

Hi Vanam,

They may both take functions as input, but the intention of the functions 
is different.  In the case of filter(), the input function is used to cull 
the good elements of the sequence out.

############################################################################
>>> def starts_with_ab(word):
...     return word[:2] == 'ab'
...
>>> filter(starts_with_ab, ["abracadabra", "open sesame", "abraham lincoln"]
... )
['abracadabra', 'abraham lincoln']
############################################################################



> i am getting the same results for instance
> def squ(x):
>    return x*x
> filter(squ,range(1,3))->1,4(output)
> map(squ,range(1,3)->1,4(output)


This doesn't look right.  Please copy and paste exactly what you typed, 
and exactly what the program outputted.  You need to do this carefully or 
we can't reproduce what you see.


In fact, concretely, when you reply to Kent, you show a different 
definition of squ():

###########
def squ(n):
    y = n*n
    print y
###########

Be more careful next time.


In this case, squ() isn't even returning back a value, so you can't expect 
good things to come out of filter() and map(): filter and map depend on 
the input function actually giving values back.

What you're seeing on screen is the "side-effects" of calling squ() on 
every element.

From kent37 at tds.net  Tue Jan 23 16:38:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 23 Jan 2007 10:38:58 -0500
Subject: [Tutor] Difference between filter and map
In-Reply-To: <bedebdfb0701230721h387684a8he81b7308429b5d4a@mail.gmail.com>
References: <bedebdfb0701230655n6938ec8fic2b98eebc2745609@mail.gmail.com>	
	<45B62571.70809@tds.net>
	<bedebdfb0701230721h387684a8he81b7308429b5d4a@mail.gmail.com>
Message-ID: <45B62C12.1030006@tds.net>

vanam wrote:
> ya i am sure about that i am using python editor which has python 
> intrepreter attached to it i got the same output for both filter and map
> def squ(n):
>    y = n*n
>   print y
> filter(y,range(3))->0  1 4
> map(y,range(3))->0 1 4

This is quite different that what you posted the first time. This 
function squ() *prints* n*n but *returns* None (since it has no explicit 
return statement). The previous squ() actually returned n*n. But the 
results are still different if you look carefully:

In [2]: def sq(n):
    ...:     y=n*n
    ...:     print y
    ...:
    ...:

In [3]: map(sq, range(3))
0
1
4
Out[3]: [None, None, None]

The function sq() is called for each element of range(3) and prints the 
square. This is why 0, 1, 4 are printed. But the value returned from 
map() is the list [None, None, None] which is the accumulated return 
values from calling sq().

In [4]: filter(sq, range(3))
0
1
4
Out[4]: []

Here, sq() is still called for each element of range(3). Since the 
printing is from sq(), 0, 1 and 4 are still printed. But the return 
value is an empty list [] because None is not true so sq(n) is not true 
for any elements of range(3).

Kent


From cbc at unc.edu  Tue Jan 23 16:40:21 2007
From: cbc at unc.edu (Chris Calloway)
Date: Tue, 23 Jan 2007 10:40:21 -0500
Subject: [Tutor] Difference between filter and map
Message-ID: <45B62C65.10108@unc.edu>

vanam wrote:
> i want to know the difference between filter(function,sequence) and 
> map(function,sequence).

>>> print filter.__doc__
filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true.  If
function is None, return the items that are true.  If sequence is a
tuple or string, return the same type, else return a list.
>>> print map.__doc__
map(function, sequence[, sequence, ...]) -> list

Return a list of the results of applying the function to the items of
the argument sequence(s).  If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length.  If the function is None, return a list
of the items of the sequence (or a list of tuples if more than one
sequence).
>>>

filter returns a subsequence of a sequence based on passing each item in
the sequence to a function which returns a *boolean context*. If the
returns value's boolean context is true, the item is placed in the new
subsequence. map returns a sequence of the same length based on the
return value of passing each item in the sequence to a function.

One literally filters a sequence. The other literally maps a sequence.

filter can return a tuple, string, or list. map only returns a list.

I tried for a simple script with an function
> which finds the square of the number,after including separately filter 
> and map in the script i am getting the same results for instance
> def squ(x):
>      return x*x
> filter(squ,range(1,3))->1,4(output)
> map(squ,range(1,3)->1,4(output)

The boolean context of the return value of squ is true for all items of
the sequence which you passed it in filter. Also, the filter you showed
above does *not* return [1,4]. It returns [1,2], which is every item in
range(1,3), because every item in that list passes the filter function's
  boolean context (is x*x true?).

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599



From cbc at unc.edu  Tue Jan 23 16:48:21 2007
From: cbc at unc.edu (Chris Calloway)
Date: Tue, 23 Jan 2007 10:48:21 -0500
Subject: [Tutor] Difference between filter and map
In-Reply-To: <bedebdfb0701230721h387684a8he81b7308429b5d4a@mail.gmail.com>
References: <bedebdfb0701230655n6938ec8fic2b98eebc2745609@mail.gmail.com>	<45B62571.70809@tds.net>
	<bedebdfb0701230721h387684a8he81b7308429b5d4a@mail.gmail.com>
Message-ID: <45B62E45.4070902@unc.edu>

vanam wrote:
> ya i am sure about that i am using python editor which has python 
> intrepreter attached to it i got the same output for both filter and map
> def squ(n):
>    y = n*n
>   print y
> filter(y,range(3))->0  1 4
> map(y,range(3))->0 1 4

You are not printing the result of either the filter or map function 
here. You have the print statement embedded in squ. In fact you wouldn't 
print anything but a NameError exception here because you haven't passed 
filter or map a function, just an identifier which isn't in their scope:

 >>> def squ(n):
...    y = n*n
...    print y
...
 >>> filter(y, range(3))
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
NameError: name 'y' is not defined
 >>>

Also not, the function squ as defined here always returns None, so it is 
useless as either a filtering or mapping function. Printing a value is 
not the same as returning a value.

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599




From tinoloc at gmail.com  Tue Jan 23 17:35:09 2007
From: tinoloc at gmail.com (Tino Dai)
Date: Tue, 23 Jan 2007 11:35:09 -0500
Subject: [Tutor] Variables of Variables
In-Reply-To: <Pine.LNX.4.64.0701220853530.2342@hkn.eecs.berkeley.edu>
References: <e033edfb0701181315k27ce76e5ld742f85a4c65e8fd@mail.gmail.com>
	<5e58f2e40701181355k22d939c9lcd3b4687222d6f98@mail.gmail.com>
	<Pine.LNX.4.64.0701181514020.4796@hkn.eecs.berkeley.edu>
	<e033edfb0701220843m5a44f001i4e071b8b9c93d1c7@mail.gmail.com>
	<Pine.LNX.4.64.0701220853530.2342@hkn.eecs.berkeley.edu>
Message-ID: <e033edfb0701230835s338e162el17c2f1a2d06d7d31@mail.gmail.com>

*** Stuff deleted ****

Wanted to give you an update. It is working now. Thank you
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070123/a7d77c98/attachment.htm 

From tinoloc at gmail.com  Tue Jan 23 17:48:53 2007
From: tinoloc at gmail.com (Tino Dai)
Date: Tue, 23 Jan 2007 11:48:53 -0500
Subject: [Tutor] Question about structuring my pygtk program
Message-ID: <e033edfb0701230848k6accbd55p1af8d595668c7ae1@mail.gmail.com>

Hi Everybody,

       I have a question about structuring first pygtk program now that I
have the basics working, I am moving to the next step of organizing my
program so it doesn't turn into spaghetti code. Right now, what I'm doing is
if a component of the GUI is used in more than one spot, I make that into a
separate little function returning a GUI fragment that I can call several
times throughout the program. I have been doing this type of "non-redundant
code" in a non-GUI environment for many years, and it's worked well. Also, I
read about this technique from the Pragmatic Programmer - having one section
of code that does a specific task - instead of having it in multiple
locations. Does this translate to the GUI environment? If so, is there an
easy of accessing the different input boxes easily? If you need a code
exxample, just ask.

Thanks,
-Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070123/f159ea51/attachment.html 

From carloslara at web.de  Tue Jan 23 20:15:13 2007
From: carloslara at web.de (Carlos)
Date: Tue, 23 Jan 2007 20:15:13 +0100
Subject: [Tutor] Thanks
In-Reply-To: <mailman.9323.1169567344.32030.tutor@python.org>
References: <mailman.9323.1169567344.32030.tutor@python.org>
Message-ID: <45B65EC1.2000301@web.de>

Hello,

I want to thank all you for the all help that you have been lending to 
me for the past months.  My masters thesis is now finished and I have to 
say that it has been very succesfull. This is something that would have 
been impossible if not for all the help that you gave to me. I was 
thinking in mentioning those of you who helped me, but really fear to 
miss someone, so thanks to all of you who contributed. Thank you very much.

This doesnt means that you will get rid of me, I want to get into OO 
now.  :)

Cheers,
Carlos

From original_brownster at yahoo.co.uk  Tue Jan 23 21:10:13 2007
From: original_brownster at yahoo.co.uk (Original Brownster)
Date: Tue, 23 Jan 2007 20:10:13 +0000 (GMT)
Subject: [Tutor] OOP - have I done it right or could it be better?
Message-ID: <236157.19528.qm@web23411.mail.ird.yahoo.com>

Hi,
I'm fairly new to using OOP and very new to Python, my first program is
coming along well and I have split the code into 2 modules.

The program finds stream urls, downloads them, re-encodes them to othe
formats, all this functionality I have created in one module with one
class called Streamrip and methods to handle this.
The second module contains all the code to handle the pygtk interface
and written as a separate class called Windowapp()

You call the Windowapp() routine, in its' init method I have a call to
create an instance of the streamrip class:

self.UC = Streamrip(var=....)

from then on within the Windowapp class i refer to the methods in
streamrip like

self.UC.Dumpstream(...)  etc.

I've got this far and now I am thinking all though it works would it be
better another way for example should I have used inheritence and
allowed the windowapp class to inherit the methods of streamrip()? 

if you want to see the code I can upload it.

It would be good to get some advice, thanks.

Wayne.





	
	
		
___________________________________________________________ 
New Yahoo! Mail is the ultimate force in competitive emailing. Find out more at the Yahoo! Mail Championships. Plus: play games and win prizes. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 

From kent37 at tds.net  Tue Jan 23 21:33:39 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 23 Jan 2007 15:33:39 -0500
Subject: [Tutor] OOP - have I done it right or could it be better?
In-Reply-To: <236157.19528.qm@web23411.mail.ird.yahoo.com>
References: <236157.19528.qm@web23411.mail.ird.yahoo.com>
Message-ID: <45B67123.2050708@tds.net>

Original Brownster wrote:
> Hi,
> I'm fairly new to using OOP and very new to Python, my first program is
> coming along well and I have split the code into 2 modules.
> 
> The program finds stream urls, downloads them, re-encodes them to othe
> formats, all this functionality I have created in one module with one
> class called Streamrip and methods to handle this.
> The second module contains all the code to handle the pygtk interface
> and written as a separate class called Windowapp()
> 
> You call the Windowapp() routine, in its' init method I have a call to
> create an instance of the streamrip class:
> 
> self.UC = Streamrip(var=....)
> 
> from then on within the Windowapp class i refer to the methods in
> streamrip like
> 
> self.UC.Dumpstream(...)  etc.

This all sounds good. You have a module, Streamrip, that implements the 
core functionality you need. From your description, this module doesn't 
know about the GUI so it could be reused by another kind of client, 
tested, etc. You also have a module that implements a GUI front-end to 
Streamrip. All good. Just make sure the Streamrip module doesn't know 
anything about the Windowapp module - keep the dependencies one-way.

> I've got this far and now I am thinking all though it works would it be
> better another way for example should I have used inheritence and
> allowed the windowapp class to inherit the methods of streamrip()? 

No, that is not better. Windowapp is not a kind of streamrip (which is 
what an inheritance relationship implies), it is a client of streamrip.

Kent


From kim.branson at gmail.com  Tue Jan 23 23:10:47 2007
From: kim.branson at gmail.com (Kim Branson)
Date: Tue, 23 Jan 2007 14:10:47 -0800
Subject: [Tutor] metaclass question
In-Reply-To: <45B56188.2090804@tds.net>
References: <DD1B7C36-BF48-4DAF-8DCF-DA30933C095D@gmail.com>
	<45B56188.2090804@tds.net>
Message-ID: <EB9F4625-8C43-4056-9D99-B31984039EBE@gmail.com>


Hi,

what i've ended up doing is the following

define a EmpiricalScore class that has all the methods for computing  
results

define a single method in  the evaluation class that is called   
Score. This method simply walks though a list and executes the  
methods in that list. There may be one or many.


     def score(self):
         """
         this function computes the interaction energy and returns a
         dict of key=value pairs for the scoring functions requested
         """
         for x in self.functionList:
             x()
         return(self.scoreResults)

The factory class takes as agument some input data and determine  
which of the methods in the Evaluation class should be called.
it then produces an instance of the EmpiricalScore class,   (called  
scoreObject,) and then append the methods from that instance to its  
internal list.

         scoreObject=EmpiricalScore()

         #for each valid scoring function in the functions
         #tuple we call the method which adds the attribute
         for x in self.functionsToUse:
             #we need to check if we want both smog and smogh
             if x == "smog":
                 if bothSmog == True:
                     continue
                 for y in self.functionsToUse:
                     if y == "smog_h":
                         scoreObject.functionList.append 
(scoreObject.calBothSmog)

This is possibly not the best way to approach this, the factory class  
is possibly not required and could be added to the  EmpiricalScore  
class. I think its probably better to separate these to keep things  
clean.  In a way this method is constructing a decorator for the  
EmpiricalScore.score  method.  Is there a way of appending a method  
to the class after it is initialized. Or adding decorators to the  
method after it is defined?

kim







On Jan 22, 2007, at 5:14 PM, Kent Johnson wrote:

> Kim Branson wrote:
>> Hi i'm interested in implementing a factoryclass in python
>> What i'd like to do is have my factoryClass produce an instance of  
>> a  class with some methods defined in arguments to the factory class.
>> The classes that are produced have many common methods, but a  
>> single  unique method. This method actually is a series of calls  
>> to a c++ api.
>> Depending on what we are doing with the produced class, i'd like  
>> the  unique method to call api function A, or api function B  
>> etc.   Alternatively the unique method might call A and the B and  
>> return a  dict of the results.
>> I'm doing this because i'd like all my produced class instances  
>> to  simply have  a calculateResults method which will then go and  
>> do the  right thing.  I don't want to set some values in the init,  
>> like A==  True  and have a if A: call methodA etc statement.
>
> Do you need to be passing in the unique method, or can you just  
> make a base class with the common methods and subclasses that  
> define their unique methods? For example,
>
> class Base(object):
>   def a(self):
>     pass
>   def b(self):
>     pass
>   def calculateResults(self):
>     raise NotImplementedError
>
> class A(Base):
>   def calculateResults(self):
>     return self.a() * self.b()
>
> class B(Base):
>   def calculateResults(self):
>     return dict(a=self.a(), b=self.b())
>
> Kent
>


From alan.gauld at btinternet.com  Wed Jan 24 00:04:04 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 23 Jan 2007 23:04:04 -0000
Subject: [Tutor] OOP - have I done it right or could it be better?
References: <236157.19528.qm@web23411.mail.ird.yahoo.com>
Message-ID: <ep6496$vtm$1@sea.gmane.org>


"Original Brownster" <original_brownster at yahoo.co.uk> wrote

> The program finds stream urls, downloads them, re-encodes them to 
> othe
> formats, all this functionality I have created in one module with 
> one
> class called Streamrip and methods to handle this.

Good so far.
One nitpick is that class names should be nouns.
They refer to objects not actions.

So your class could maybe be called just Stream or
RippingStream or somesuch. This has a knock on effect
further down...

> The second module contains all the code to handle the pygtk 
> interface
> and written as a separate class called Windowapp()

Thats fine.

> You call the Windowapp() routine, in its' init method I have a call 
> to
> create an instance of the streamrip class:
>
> self.UC = Streamrip(var=....)

And thats fine too, although UC isn't an entirely obvious
name for the StreamRipper (to me anway!)

> from then on within the Windowapp class i refer to the methods in
> streamrip like
>
> self.UC.Dumpstream(...)  etc.

One of the features of OOP is that you don't need to include
the class name in the method name since the object itself tells
you what you are acting on. Thus we know that UC is the object
and you just want to dump it. So just call the method dump...
It keeps things shorter, avoids duplication and generally
improves readability.

But this is a cosmetic issue and others may disagree. But
the general notion is that we are aiming for a semantic form of

object.action

it's only in procedural programming that you need to embed
the type into the name.

> better another way for example should I have used inheritence and
> allowed the windowapp class to inherit the methods of streamrip()?

Absolutely not. The WindowApp ius one thing the stream another.
If you want to use the stream elsewhere(in a web app say) you
would be stuck. You should always try to keep presentation and
application logic separate (even in non OOP programs!)


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From vgvr620034 at gmail.com  Wed Jan 24 04:32:30 2007
From: vgvr620034 at gmail.com (vanam)
Date: Wed, 24 Jan 2007 09:02:30 +0530
Subject: [Tutor] Difference between filter and map
In-Reply-To: <45B62C12.1030006@tds.net>
References: <bedebdfb0701230655n6938ec8fic2b98eebc2745609@mail.gmail.com>
	<45B62571.70809@tds.net>
	<bedebdfb0701230721h387684a8he81b7308429b5d4a@mail.gmail.com>
	<45B62C12.1030006@tds.net>
Message-ID: <bedebdfb0701231932k7e85a856g791d457e0ebf03d@mail.gmail.com>

Yes i did a mistake in expressing my problem below are the instances of the
script and its corresponding output,for each instance its giving contrasting
result i want explanation for that
[1]:def squ(n):
           return n*n
     filter(squ,range(3))---->output is not seen on the interpreter
     map(squ,range(3))----->output  not seen on the interpreter
print filter(squ,range(3))----->output is [1,2]
print map(squ,range(3))------>output is [0,1,4]

[2]:def squ(n):
          y = n*n
          print y
      filter(squ,range(3))-->Below is the output
      0
      1
      4
      map(squ,range(3))-->Below is the output
      0
      1
      4
      print filter(squ,range(3))--->Below is the output
      0
      1
      4
      []
      print map(squ,range(3))-->Below is the output
      0
      1
      4
      [None,None,None]
I want to know why in each case its giving different results and diff
between filter and map
On 1/23/07, Kent Johnson <kent37 at tds.net> wrote:
>
> vanam wrote:
> > ya i am sure about that i am using python editor which has python
> > intrepreter attached to it i got the same output for both filter and map
> > def squ(n):
> >    y = n*n
> >   print y
> > filter(y,range(3))->0  1 4
> > map(y,range(3))->0 1 4
>
> This is quite different that what you posted the first time. This
> function squ() *prints* n*n but *returns* None (since it has no explicit
> return statement). The previous squ() actually returned n*n. But the
> results are still different if you look carefully:
>
> In [2]: def sq(n):
>     ...:     y=n*n
>     ...:     print y
>     ...:
>     ...:
>
> In [3]: map(sq, range(3))
> 0
> 1
> 4
> Out[3]: [None, None, None]
>
> The function sq() is called for each element of range(3) and prints the
> square. This is why 0, 1, 4 are printed. But the value returned from
> map() is the list [None, None, None] which is the accumulated return
> values from calling sq().
>
> In [4]: filter(sq, range(3))
> 0
> 1
> 4
> Out[4]: []
>
> Here, sq() is still called for each element of range(3). Since the
> printing is from sq(), 0, 1 and 4 are still printed. But the return
> value is an empty list [] because None is not true so sq(n) is not true
> for any elements of range(3).
>
> Kent
>
>


-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070124/afe69484/attachment-0001.htm 

From vgvr620034 at gmail.com  Wed Jan 24 07:51:48 2007
From: vgvr620034 at gmail.com (vanam)
Date: Wed, 24 Jan 2007 12:21:48 +0530
Subject: [Tutor] Python Branches
Message-ID: <bedebdfb0701232251y41a44194u4f988614eb01d543@mail.gmail.com>

i started slowly learning python as i dont have much exposure to it and  i
wanted to know what are all branches there in python actually i installed py
2.5 recently i come across question in groups about the gui where in pygtk
should be installed.My question is without this installation could i able to
develop any application using py2.5?One more thing is what is tkinter?Can
any one explain what are all branches in python and how it could be used?
-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070124/75b7ce00/attachment.html 

From rabidpoobear at gmail.com  Wed Jan 24 08:05:28 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 24 Jan 2007 01:05:28 -0600
Subject: [Tutor] Python Branches
In-Reply-To: <bedebdfb0701232251y41a44194u4f988614eb01d543@mail.gmail.com>
References: <bedebdfb0701232251y41a44194u4f988614eb01d543@mail.gmail.com>
Message-ID: <45B70538.4010809@gmail.com>

vanam wrote:
>
> i started slowly learning python as i dont have much exposure to it 
> and  i wanted to know what are all branches there in python actually i 
> installed py 2.5 recently i come across question in groups about the 
> gui where in pygtk should be installed.My question is without this 
> installation could i able to develop any application using py2.5?
Well, that depends what the meaning of the word 'any' is.
Do you mean 'any' to be one or more possible applications or do you mean 
it to be all possible applications?
Yes, you can write many programs with the base python install.
Potentially you could write any program; however, the point is not to 
rewrite code that someone has already done.
That's the purpose of libraries.
For example, python comes with a 'math' library which allows you to 
calculate sines and cosines of angles without having to understand
the process by which someone calculates these values.
> One more thing is what is tkinter?Can  any one explain what are all 
> branches in python and how it could be used?
pygtk and tkinter are libraries that people have written to let you 
write applications containing GUIs.
pygtk is a separate download; tkinter comes with most Python distributions.
> -- 
>                                   
>                                            Vanam
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From original_brownster at yahoo.co.uk  Wed Jan 24 10:01:02 2007
From: original_brownster at yahoo.co.uk (Original Brownster)
Date: Wed, 24 Jan 2007 09:01:02 +0000 (GMT)
Subject: [Tutor] OOP - have I done it right or could it be better?
In-Reply-To: <45B67123.2050708@tds.net>
Message-ID: <364097.28923.qm@web23409.mail.ird.yahoo.com>


--- Kent Johnson <kent37 at tds.net> wrote:

> Original Brownster wrote:
> > Hi,
> > I'm fairly new to using OOP and very new to Python, my first
> program is
> > coming along well and I have split the code into 2 modules.
> > 
> > The program finds stream urls, downloads them, re-encodes them to
> othe
> > formats, all this functionality I have created in one module with
> one
> > class called Streamrip and methods to handle this.
> > The second module contains all the code to handle the pygtk
> interface
> > and written as a separate class called Windowapp()
> > 
> > You call the Windowapp() routine, in its' init method I have a call
> to
> > create an instance of the streamrip class:
> > 
> > self.UC = Streamrip(var=....)
> > 
> > from then on within the Windowapp class i refer to the methods in
> > streamrip like
> > 
> > self.UC.Dumpstream(...)  etc.
> 
> This all sounds good. You have a module, Streamrip, that implements
> the 
> core functionality you need. From your description, this module
> doesn't 
> know about the GUI so it could be reused by another kind of client, 
> tested, etc. You also have a module that implements a GUI front-end
> to 
> Streamrip. All good. Just make sure the Streamrip module doesn't know
> 
> anything about the Windowapp module - keep the dependencies one-way.

That's good then as that's how it works, it looks like I'll be adding a
command line interface too as I am thinking this and cron will be a
good way to schedule jobs. With the modular approach it means I'll
pretty much not have to touch the core functionality routines.

Thanks for your advice I feel I'm getting there!
The hardest part for me so far has being moving from VB interface
programming, when I first looked at some of the gui programming
toolkits in linux I was a bit overwhelmed however, once I made a start
I soon got some little programs running. 

Wayne.



	
	
		
___________________________________________________________ 
New Yahoo! Mail is the ultimate force in competitive emailing. Find out more at the Yahoo! Mail Championships. Plus: play games and win prizes. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 

From wesbrooks at gmail.com  Wed Jan 24 11:02:09 2007
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Wed, 24 Jan 2007 10:02:09 +0000
Subject: [Tutor] Global values & import scope
Message-ID: <eec9f8ee0701240202h24e93ad9rca222d11f9eb7997@mail.gmail.com>

Dear Users,

I'm using global values to create a unique ID, or name for each
instance of a class. If I import the following in one file and test it
it works fine. If the following class was imported in two different
files run by the same program would each instance of the class have a
unique name, or would they only be unique within the scope of the file
which contains the import of the bellow class?

itemID = 0
class AssemblyItem:
    def __init__(self):
        global itemID
        self.ID = "assemblyItem" + str(itemID)
        itemID += 1

Thanks for any help,

Yours Faithfully,

Wesley Brooks

From rabidpoobear at gmail.com  Wed Jan 24 11:49:58 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 24 Jan 2007 04:49:58 -0600
Subject: [Tutor] Global values & import scope
In-Reply-To: <eec9f8ee0701240202h24e93ad9rca222d11f9eb7997@mail.gmail.com>
References: <eec9f8ee0701240202h24e93ad9rca222d11f9eb7997@mail.gmail.com>
Message-ID: <45B739D6.9030803@gmail.com>

Wesley Brooks wrote:
> Dear Users,
>
> I'm using global values to create a unique ID, or name for each
> instance of a class. If I import the following in one file and test it
> it works fine. If the following class was imported in two different
> files run by the same program would each instance of the class have a
> unique name, or would they only be unique within the scope of the file
> which contains the import of the bellow class?
>   
I believe that, if your program is importing 2 other packages, each of 
which import some other package,
that other doubly-imported package will only be executed once, by 
whichever one you import first.
> itemID = 0
> class AssemblyItem:
>     def __init__(self):
>         global itemID
>         self.ID = "assemblyItem" + str(itemID)
>         itemID += 1
>   
I'm 99% sure you can accomplish the same thing with a variable that is 
global to all instances of the class.
something like (may not work):

class Foo:
    itemID = 0
    def __init__(self):
        itemID += 1

HTH,
-Luke

From kent37 at tds.net  Wed Jan 24 11:56:50 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 24 Jan 2007 05:56:50 -0500
Subject: [Tutor] Difference between filter and map
In-Reply-To: <bedebdfb0701231932k7e85a856g791d457e0ebf03d@mail.gmail.com>
References: <bedebdfb0701230655n6938ec8fic2b98eebc2745609@mail.gmail.com>	
	<45B62571.70809@tds.net>	
	<bedebdfb0701230721h387684a8he81b7308429b5d4a@mail.gmail.com>	
	<45B62C12.1030006@tds.net>
	<bedebdfb0701231932k7e85a856g791d457e0ebf03d@mail.gmail.com>
Message-ID: <45B73B72.7060204@tds.net>

vanam wrote:
> Yes i did a mistake in expressing my problem below are the instances of 
> the script and its corresponding output,for each instance its giving 
> contrasting result i want explanation for that

This has pretty much been explained already. Do you have some question 
with the explanation?

> [1]:def squ(n):
>            return n*n
>      filter(squ,range(3))---->output is not seen on the interpreter
>      map(squ,range(3))----->output  not seen on the interpreter
> print filter(squ,range(3))----->output is [1,2]
> print map(squ,range(3))------>output is [0,1,4]
> 
> [2]:def squ(n):
>           y = n*n
>           print y
>       filter(squ,range(3))-->Below is the output

Note that in a script, the results of function calls are not printed 
unless you explicitly ask for it with a print statement. So the output 
here is from the "print y" in squ(), it is not the result of filter().

>       0
>       1
>       4
>       map(squ,range(3))-->Below is the output
>       0
>       1
>       4

Again, this is just the output from "print y"

>       print filter(squ,range(3))--->Below is the output
>       0
>       1
>       4

This is the result from filter():
>       []
>       print map(squ,range(3))-->Below is the output
>       0
>       1
>       4

This is the result from map():
>       [None,None,None]
> I want to know why in each case its giving different results and diff 
> between filter and map

Please reread the previous replies, all of this is explained.

Kent


From kent37 at tds.net  Wed Jan 24 11:58:43 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 24 Jan 2007 05:58:43 -0500
Subject: [Tutor] OOP - have I done it right or could it be better?
In-Reply-To: <364097.28923.qm@web23409.mail.ird.yahoo.com>
References: <364097.28923.qm@web23409.mail.ird.yahoo.com>
Message-ID: <45B73BE3.40001@tds.net>

Original Brownster wrote:
> --- Kent Johnson <kent37 at tds.net> wrote:
>> This all sounds good. You have a module, Streamrip, that implements
>> the 
>> core functionality you need. From your description, this module
>> doesn't 
>> know about the GUI so it could be reused by another kind of client, 
>> tested, etc. You also have a module that implements a GUI front-end
>> to 
>> Streamrip. All good. Just make sure the Streamrip module doesn't know
>>
>> anything about the Windowapp module - keep the dependencies one-way.
> 
> That's good then as that's how it works, it looks like I'll be adding a
> command line interface too as I am thinking this and cron will be a
> good way to schedule jobs. With the modular approach it means I'll
> pretty much not have to touch the core functionality routines.

Exactly the point. You might need to add or modify functionality for new 
requirements but the core should be easily reusable.

Kent


From alan.gauld at btinternet.com  Wed Jan 24 12:03:03 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 24 Jan 2007 11:03:03 -0000
Subject: [Tutor] Difference between filter and map
References: <bedebdfb0701230655n6938ec8fic2b98eebc2745609@mail.gmail.com><45B62571.70809@tds.net><bedebdfb0701230721h387684a8he81b7308429b5d4a@mail.gmail.com><45B62C12.1030006@tds.net>
	<bedebdfb0701231932k7e85a856g791d457e0ebf03d@mail.gmail.com>
Message-ID: <ep7ed9$449$1@sea.gmane.org>


"vanam" <vgvr620034 at gmail.com> wrote

> Yes i did a mistake in expressing my problem below are the instances 
> of the
> script and its corresponding output,for each instance its giving 
> contrasting
> result i want explanation for that
> [1]:def squ(n):
>           return n*n

>     filter(squ,range(3))---->output is not seen on the interpreter
>     map(squ,range(3))----->output  not seen on the interpreter

I don;t know why you aren't seeing the output, I would expect
more or less the same output as the next two lines.
What tool are you using? Is it IDLE or something else?

> print filter(squ,range(3))----->output is [1,2]
> print map(squ,range(3))------>output is [0,1,4]

The first one returns the actual items from the list where
squ(item) evaluates to Ture,  ie non zero. The first item (0)
squared is zero so it is not included - it is filtered out, leaving
1 and 2 as the only output.

The second one returns the result of passing each item
through squ()each item. So you get 0,1,4 which are the
squares of 0,1,2

> [2]:def squ(n):
>          y = n*n
>          print y

This function prrints the values then returns None (Python's
default return value) which is equivalent to False in a boolean
context.

>      filter(squ,range(3))-->Below is the output
>      0
>      1
>      4

filter applies squ to each item. squ prints the square.
filter then returns an empty list since squ always returns
None, which is false, so all items are filtered out.
Why it is not printed by the interpreter I don't know.

>      map(squ,range(3))-->Below is the output
>      0
>      1
>      4

As above but this time map returns a list of 3 Nones.
Why it is not printed I don't know.

>      print filter(squ,range(3))--->Below is the output
>      0
>      1
>      4
>      []
>      print map(squ,range(3))-->Below is the output
>      0
>      1
>      4
>      [None,None,None]

Exactly as above except the output from the functions is
actually being printed.


> I want to know why in each case its giving different results and 
> diff
> between filter and map

Hopefully my explanation has made that clear.
Why the versions without print do not display the result of the
functions is a mystery.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From kent37 at tds.net  Wed Jan 24 12:03:50 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 24 Jan 2007 06:03:50 -0500
Subject: [Tutor] Python Branches
In-Reply-To: <bedebdfb0701232251y41a44194u4f988614eb01d543@mail.gmail.com>
References: <bedebdfb0701232251y41a44194u4f988614eb01d543@mail.gmail.com>
Message-ID: <45B73D16.9080105@tds.net>

vanam wrote:
> 
> i started slowly learning python as i dont have much exposure to it and  
> i wanted to know what are all branches there in python actually i 
> installed py 2.5 recently i come across question in groups about the gui 
> where in pygtk should be installed.My question is without this 
> installation could i able to develop any application using py2.5?One 
> more thing is what is tkinter?Can  any one explain what are all branches 
> in python and how it could be used?

You need to install pygtk if you want to develop applications that use 
the GTK GUI toolkit.

I don't know what you mean by "branches", can you explain?

Kent


From kent37 at tds.net  Wed Jan 24 12:06:27 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 24 Jan 2007 06:06:27 -0500
Subject: [Tutor] Global values & import scope
In-Reply-To: <45B739D6.9030803@gmail.com>
References: <eec9f8ee0701240202h24e93ad9rca222d11f9eb7997@mail.gmail.com>
	<45B739D6.9030803@gmail.com>
Message-ID: <45B73DB3.1060603@tds.net>

Luke Paireepinart wrote:
> I believe that, if your program is importing 2 other packages, each of 
> which import some other package,
> that other doubly-imported package will only be executed once, by 
> whichever one you import first.

Yes, that's right.

>> itemID = 0
>> class AssemblyItem:
>>     def __init__(self):
>>         global itemID
>>         self.ID = "assemblyItem" + str(itemID)
>>         itemID += 1
>>   
> I'm 99% sure you can accomplish the same thing with a variable that is 
> global to all instances of the class.
> something like (may not work):
> 
> class Foo:
>     itemID = 0
>     def __init__(self):
>         itemID += 1

That should be Foo.itemID += 1; the class namespace is not part of the 
default name search path.

Kent


From kent37 at tds.net  Wed Jan 24 12:09:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 24 Jan 2007 06:09:18 -0500
Subject: [Tutor] Global values & import scope
In-Reply-To: <eec9f8ee0701240202h24e93ad9rca222d11f9eb7997@mail.gmail.com>
References: <eec9f8ee0701240202h24e93ad9rca222d11f9eb7997@mail.gmail.com>
Message-ID: <45B73E5E.6040602@tds.net>

Wesley Brooks wrote:
> Dear Users,
> 
> I'm using global values to create a unique ID, or name for each
> instance of a class. If I import the following in one file and test it
> it works fine. If the following class was imported in two different
> files run by the same program would each instance of the class have a
> unique name, or would they only be unique within the scope of the file
> which contains the import of the bellow class?
> 
> itemID = 0
> class AssemblyItem:
>     def __init__(self):
>         global itemID
>         self.ID = "assemblyItem" + str(itemID)
>         itemID += 1

That will work fine. When a module is imported twice, the second import 
received a cached copy of the same module; the module is only 
instantiated once. The variable itemID will just exist in one place, in 
the single instance of the module, and AssemblyItems created from 
different clients will all share the same counter.

Kent


From alan.gauld at btinternet.com  Wed Jan 24 12:11:45 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 24 Jan 2007 11:11:45 -0000
Subject: [Tutor] Python Branches
References: <bedebdfb0701232251y41a44194u4f988614eb01d543@mail.gmail.com>
Message-ID: <ep7etj$5qs$1@sea.gmane.org>


"vanam" <vgvr620034 at gmail.com> wrote in message 
news:bedebdfb0701232251y41a44194u4f988614eb01d543 at mail.gmail.com...
>i started slowly learning python as i dont have much exposure to it 
>and  i
> wanted to know what are all branches there in python

I assume by branches you mean all the different libraries available?
Thats difficult to answer because there are literally hundreds if not
thousands available. Anything not in the core release will need to
be synchronised with the core release before you can use it. Thus
a library built for version 2.4 may need slight modification before
it can be used in version 2.5. That is the responsibility of the
library author. (Or if its open source you might try doing it
yourself!)

> 2.5 recently i come across question in groups about the gui where in 
> pygtk
> should be installed.

That will also usually depend on the author of the library.
They normally provide an installation script that puts it in
the right place for your platform.

> My question is without this installation could i able to
> develop any application using py2.5?

You can develop standard Python applications but you
couldn't develop anything using pygtk until you install it.

> One more thing is what is tkinter?

Tkinter is the standard GUI toolkit library for Python.
It is based on the Tcl/Tk toolkit and as such is not particularly
modern in appearance, but it is widely supported, well documented
and fairly easy to use and extend. pygtk is a similar library based
on the GTk GUI toolit.

The other two popular GUI libraries for Python are wxPython
and pyQT.

If that doesn't answer your questions can you be more
specific, possibly with more examples?

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From johan at accesstel.co.za  Wed Jan 24 13:30:35 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Wed, 24 Jan 2007 14:30:35 +0200
Subject: [Tutor] Python code to connect using PPPoE
Message-ID: <20070124122454.D4CEC165C1@mail.accesstel.co.za>

Hi all,
 
I don't know if this the right place to ask the question, but I did some
Googling and struggled to get decent examples of code to use for PPPoE
connection.
 
I have a wireless modem that uses PPPoE to connect and want to use Python to
connect to the internet through this modem using PPPoE.
 
Does anybody know where I can get something like this? Is it in Twisted or
is there possibly a "cleaner" example of this?
 
Thanks 
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.8/649 - Release Date: 2007/01/23
08:40 PM
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070124/6c5c4c0e/attachment.html 

From kent37 at tds.net  Wed Jan 24 14:52:17 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 24 Jan 2007 08:52:17 -0500
Subject: [Tutor] Python code to connect using PPPoE
In-Reply-To: <20070124122454.D4CEC165C1@mail.accesstel.co.za>
References: <20070124122454.D4CEC165C1@mail.accesstel.co.za>
Message-ID: <45B76491.7090201@tds.net>

Johan Geldenhuys wrote:
> Hi all,
>  
> I don't know if this the right place to ask the question, but I did some 
> Googling and struggled to get decent examples of code to use for PPPoE 
> connection.
>  
> I have a wireless modem that uses PPPoE to connect and want to use 
> Python to connect to the internet through this modem using PPPoE.
>  
> Does anybody know where I can get something like this? Is it in Twisted 
> or is there possibly a "cleaner" example of this?

I'm not too sure what you want to do. Are you trying to use Python to 
establish the connection, or do you want to access the internet over an 
established connection?

If it is the former, I don't have an answer for you. For the latter, 
check out urllib, urllib2, httplib, etc.

Kent


From johan at accesstel.co.za  Wed Jan 24 14:55:20 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Wed, 24 Jan 2007 15:55:20 +0200
Subject: [Tutor] Python code to connect using PPPoE
In-Reply-To: <45B76491.7090201@tds.net>
Message-ID: <20070124134939.119611669D@mail.accesstel.co.za>

Kent,
I want to establish the connection with Python. I think in Linux you can use
a PPPoE package to make life easier, but I don't want to use the Kernel to
do that.

Johan 

-----Original Message-----
From: Kent Johnson [mailto:kent37 at tds.net] 
Sent: 24 January 2007 03:52 PM
To: johan at accesstel.co.za
Cc: tutor at python.org
Subject: Re: [Tutor] Python code to connect using PPPoE

Johan Geldenhuys wrote:
> Hi all,
>  
> I don't know if this the right place to ask the question, but I did 
> some Googling and struggled to get decent examples of code to use for 
> PPPoE connection.
>  
> I have a wireless modem that uses PPPoE to connect and want to use 
> Python to connect to the internet through this modem using PPPoE.
>  
> Does anybody know where I can get something like this? Is it in 
> Twisted or is there possibly a "cleaner" example of this?

I'm not too sure what you want to do. Are you trying to use Python to
establish the connection, or do you want to access the internet over an
established connection?

If it is the former, I don't have an answer for you. For the latter, check
out urllib, urllib2, httplib, etc.

Kent

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.8/649 - Release Date: 2007/01/23
08:40 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.8/649 - Release Date: 2007/01/23
08:40 PM
 


From wesbrooks at gmail.com  Wed Jan 24 15:11:44 2007
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Wed, 24 Jan 2007 14:11:44 +0000
Subject: [Tutor] Global values & import scope
In-Reply-To: <45B73E5E.6040602@tds.net>
References: <eec9f8ee0701240202h24e93ad9rca222d11f9eb7997@mail.gmail.com>
	<45B73E5E.6040602@tds.net>
Message-ID: <eec9f8ee0701240611y2fbcfdcbld63c8f069098db3a@mail.gmail.com>

Thanks for your help I tested what you two said as follows and it
worked great. Thank you.

(Bellow in file TEST_ClassID.py)
class AssemblyItem:
    itemID = 0
    def __init__(self):
        self.ID = "assemblyItem" + str(AssemblyItem.itemID)
        AssemblyItem.itemID += 1

    def ReturnID(self):
        return self.ID

(Bellow in file TEST_ImportID1.py)
from TEST_ClassID import AssemblyItem

class Parent1:
    def __init__(self):
        self.testList = []

    def PrintID(self):
        self.testList.append(AssemblyItem())
        print self.testList[-1].ReturnID()

(Bellow in file TEST_ImportID2.py)
from TEST_ClassID import AssemblyItem

class Parent2:
    def __init__(self):
        self.testList = []

    def PrintID(self):
        self.testList.append(AssemblyItem())
        print self.testList[-1].ReturnID()

(Bellow, the commands run in the python terminal in the same directory)
>>> from TEST_ClassID1 import Parent1
>>>from TEST_ClassID2 import Parent2
>>>a = Parent1()
>>>b = Parent2()
>>>a.PrintID()
assemblyItem0
>>>a.PrintID()
assemblyItem1
>>>b.PrintID()
assemblyItem2
>>>b.PrintID()
assemblyItem3
>>>a.PrintID()
assemblyItem4
>>>b.PrintID()
assemblyItem5

Thanks again for your help.

Wesley Brooks.


On 24/01/07, Kent Johnson <kent37 at tds.net> wrote:
> Wesley Brooks wrote:
> > Dear Users,
> >
> > I'm using global values to create a unique ID, or name for each
> > instance of a class. If I import the following in one file and test it
> > it works fine. If the following class was imported in two different
> > files run by the same program would each instance of the class have a
> > unique name, or would they only be unique within the scope of the file
> > which contains the import of the bellow class?
> >
> > itemID = 0
> > class AssemblyItem:
> >     def __init__(self):
> >         global itemID
> >         self.ID = "assemblyItem" + str(itemID)
> >         itemID += 1
>
> That will work fine. When a module is imported twice, the second import
> received a cached copy of the same module; the module is only
> instantiated once. The variable itemID will just exist in one place, in
> the single instance of the module, and AssemblyItems created from
> different clients will all share the same counter.
>
> Kent
>
>

From kent37 at tds.net  Wed Jan 24 15:31:11 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 24 Jan 2007 09:31:11 -0500
Subject: [Tutor] Global values & import scope
In-Reply-To: <eec9f8ee0701240611y2fbcfdcbld63c8f069098db3a@mail.gmail.com>
References: <eec9f8ee0701240202h24e93ad9rca222d11f9eb7997@mail.gmail.com>	
	<45B73E5E.6040602@tds.net>
	<eec9f8ee0701240611y2fbcfdcbld63c8f069098db3a@mail.gmail.com>
Message-ID: <45B76DAF.1010404@tds.net>

Wesley Brooks wrote:
> Thanks for your help I tested what you two said as follows and it
> worked great. Thank you.
> 
> (Bellow in file TEST_ClassID.py)
> class AssemblyItem:
>     itemID = 0
>     def __init__(self):
>         self.ID = "assemblyItem" + str(AssemblyItem.itemID)
>         AssemblyItem.itemID += 1
> 
>     def ReturnID(self):
>         return self.ID
> 
> (Bellow in file TEST_ImportID1.py)
> from TEST_ClassID import AssemblyItem
> 
> class Parent1:
>     def __init__(self):
>         self.testList = []
> 
>     def PrintID(self):
>         self.testList.append(AssemblyItem())
>         print self.testList[-1].ReturnID()

That's a bit convoluted if all you are trying to do is test 
AssemblyItem. You could just write

from TEST_ClassID import AssemblyItem

def printID():
	item = AssemblyItem()
	print tem.ReturnID()

or even

def printID():
	print AssemblyItem().ReturnID()

Kent


From kent37 at tds.net  Wed Jan 24 15:38:59 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 24 Jan 2007 09:38:59 -0500
Subject: [Tutor] Python code to connect using PPPoE
In-Reply-To: <20070124134939.119611669D@mail.accesstel.co.za>
References: <20070124134939.119611669D@mail.accesstel.co.za>
Message-ID: <45B76F83.4050406@tds.net>

Johan Geldenhuys wrote:
> Kent,
> I want to establish the connection with Python. I think in Linux you can use
> a PPPoE package to make life easier, but I don't want to use the Kernel to
> do that.

If you are on Linux, maybe you can use os.command() to control rp-pppoe.
http://www.roaringpenguin.com/penguin/openSourceProducts/rpPppoe

If you are on Windows maybe win32ras does what you want?

Kent


From johan at accesstel.co.za  Wed Jan 24 15:44:04 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Wed, 24 Jan 2007 16:44:04 +0200
Subject: [Tutor] Python code to connect using PPPoE
In-Reply-To: <45B76F83.4050406@tds.net>
Message-ID: <20070124143824.32F6A166D4@mail.accesstel.co.za>

Is there a module that I can use for this or is it a "os" function?

Johan

-----Original Message-----
From: Kent Johnson [mailto:kent37 at tds.net] 
Sent: 24 January 2007 04:39 PM
To: johan at accesstel.co.za
Cc: tutor at python.org
Subject: Re: [Tutor] Python code to connect using PPPoE

Johan Geldenhuys wrote:
> Kent,
> I want to establish the connection with Python. I think in Linux you 
> can use a PPPoE package to make life easier, but I don't want to use 
> the Kernel to do that.

If you are on Linux, maybe you can use os.command() to control rp-pppoe.
http://www.roaringpenguin.com/penguin/openSourceProducts/rpPppoe

If you are on Windows maybe win32ras does what you want?

Kent

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.8/649 - Release Date: 2007/01/23
08:40 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.8/649 - Release Date: 2007/01/23
08:40 PM
 


From kent37 at tds.net  Wed Jan 24 16:04:56 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 24 Jan 2007 10:04:56 -0500
Subject: [Tutor] Python code to connect using PPPoE
In-Reply-To: <20070124143824.32F6A166D4@mail.accesstel.co.za>
References: <20070124143824.32F6A166D4@mail.accesstel.co.za>
Message-ID: <45B77598.9010801@tds.net>

Johan Geldenhuys wrote:
> Is there a module that I can use for this or is it a "os" function?

I haven't found any module for Linux.

Kent

> 
> Johan
> 
> -----Original Message-----
> From: Kent Johnson [mailto:kent37 at tds.net] 
> Sent: 24 January 2007 04:39 PM
> To: johan at accesstel.co.za
> Cc: tutor at python.org
> Subject: Re: [Tutor] Python code to connect using PPPoE
> 
> Johan Geldenhuys wrote:
>> Kent,
>> I want to establish the connection with Python. I think in Linux you 
>> can use a PPPoE package to make life easier, but I don't want to use 
>> the Kernel to do that.
> 
> If you are on Linux, maybe you can use os.command() to control rp-pppoe.
> http://www.roaringpenguin.com/penguin/openSourceProducts/rpPppoe
> 
> If you are on Windows maybe win32ras does what you want?
> 
> Kent
> 
> --
> No virus found in this incoming message.
> Checked by AVG Free Edition.
> Version: 7.5.432 / Virus Database: 268.17.8/649 - Release Date: 2007/01/23
> 08:40 PM
>  
> 



From kent37 at tds.net  Wed Jan 24 16:15:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 24 Jan 2007 10:15:06 -0500
Subject: [Tutor] metaclass question
In-Reply-To: <EB9F4625-8C43-4056-9D99-B31984039EBE@gmail.com>
References: <DD1B7C36-BF48-4DAF-8DCF-DA30933C095D@gmail.com>	<45B56188.2090804@tds.net>
	<EB9F4625-8C43-4056-9D99-B31984039EBE@gmail.com>
Message-ID: <45B777FA.2030003@tds.net>

Kim Branson wrote:
> Hi,
> 
> what i've ended up doing is the following
> 
> define a EmpiricalScore class that has all the methods for computing  
> results
> 
> define a single method in  the evaluation class that is called   
> Score. This method simply walks though a list and executes the  
> methods in that list. There may be one or many.
> 
> 
>      def score(self):
>          """
>          this function computes the interaction energy and returns a
>          dict of key=value pairs for the scoring functions requested
>          """
>          for x in self.functionList:
>              x()
>          return(self.scoreResults)

That looks fine, presumably the functions in functionList affect 
scoreResults...
> 
> The factory class takes as agument some input data and determine  
> which of the methods in the Evaluation class should be called.
> it then produces an instance of the EmpiricalScore class,   (called  
> scoreObject,) and then append the methods from that instance to its  
> internal list.
> 
>          scoreObject=EmpiricalScore()
> 
>          #for each valid scoring function in the functions
>          #tuple we call the method which adds the attribute
>          for x in self.functionsToUse:
>              #we need to check if we want both smog and smogh
>              if x == "smog":
>                  if bothSmog == True:
>                      continue
>                  for y in self.functionsToUse:
>                      if y == "smog_h":
>                          scoreObject.functionList.append 
> (scoreObject.calBothSmog)

This could be much simpler:
if "smog" in self.functionsToUse and "smog_h" in self.functionsToUse:
   scoreObject.functionList.append(scoreObject.calBothSmog)
> 
> This is possibly not the best way to approach this, the factory class  
> is possibly not required and could be added to the  EmpiricalScore  
> class. I think its probably better to separate these to keep things  
> clean.  

 From what you have said I don't see any need for a factory class, it 
sounds like it could be a factory function. You could also put the 
initialization into the EmpiricalScore constructor and just pass the 
list of functions to use to the constructor instead of the factory function.

> In a way this method is constructing a decorator for the  
> EmpiricalScore.score  method.  Is there a way of appending a method  
> to the class after it is initialized.

Yes, you can add a method to a class easily:

In [1]: class Foo(object): pass
    ...:

In [2]: def sayHello(self):
    ...:     print 'Hello'
    ...:

In [3]: f = Foo()

In [4]: f.sayHello()
------------------------------------------------------------
Traceback (most recent call last):
   File "<ipython console>", line 1, in <module>
<type 'exceptions.AttributeError'>: 'Foo' object has no attribute 'sayHello'


In [5]: Foo.sayHello = sayHello

In [6]: f.sayHello()
Hello

However I think you actually want to add a method to an instance, not to 
the class. But the way you have it seems pretty simple.

> Or adding decorators to the  
> method after it is defined?

Yes, you can re-assign a new value to a method which is basically what a 
decorator does. But again it sounds like you want to complicate a clean, 
simple design.

Kent


From jalilsan at gmail.com  Wed Jan 24 18:53:58 2007
From: jalilsan at gmail.com (Jalil)
Date: Wed, 24 Jan 2007 09:53:58 -0800
Subject: [Tutor] Python connecting to an exchange server
Message-ID: <5850ed90701240953x7eb0963fr5f2d1d9f80a281e6@mail.gmail.com>

I just wanted to know if its possible or if anyone can point me to a place
where I can get info on howto to get  python to talk to an MS exchange
server.
I would basically want the python code to  parse  the appointsments  in my
outlook calendar.


Is this possible?


Thank You
-- 
Shoot for the moon. Even if you miss, you'll land among the stars.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070124/17a71914/attachment.html 

From tedroche at gmail.com  Wed Jan 24 19:17:30 2007
From: tedroche at gmail.com (Ted Roche)
Date: Wed, 24 Jan 2007 13:17:30 -0500
Subject: [Tutor] Python connecting to an exchange server
In-Reply-To: <5850ed90701240953x7eb0963fr5f2d1d9f80a281e6@mail.gmail.com>
References: <5850ed90701240953x7eb0963fr5f2d1d9f80a281e6@mail.gmail.com>
Message-ID: <c9415b010701241017l42b98d77mfd9894b3cf84ad8f@mail.gmail.com>

On 1/24/07, Jalil <jalilsan at gmail.com> wrote:
>
> I would basically want the python code to  parse  the appointsments  in my
> outlook calendar.
>

Then it's most likely you don't want to talk to exchange at all, but
rather talk with Outlook. Outlook supports a COM Automation interface
and you can use it to do most of the things Outlooks does via the GUI,
although some of them are rather difficult. An example of COM
Automation with Outlook and Python can be found:

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

A paper on COM Automation and Outlook I wrote some time ago (in a
different programming language) has some pretty good references at the
end:

http://www.tedroche.com/Present/2003/OutlookAutomation.html

-- 
Ted Roche
Ted Roche & Associates, LLC
http://www.tedroche.com

From janos.juhasz at VELUX.com  Wed Jan 24 22:13:57 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Wed, 24 Jan 2007 22:13:57 +0100
Subject: [Tutor] Cause-Effect, Isikawa, fishbone diagram
Message-ID: <OF29022A1B.C511615C-ONC125726D.00719F2F-C125726D.0074A255@velux.com>

Dear All,

does someone know any python based solution to draw a 
cause-effect diagram into PDF from a simple textfile ?

It is also called a Fishbone Diagram, because of its shape, 
or an Ishikawa Chart, after its originator, Kaoru Ishikawa
I feel, it can be converted from a structure like this.

Title
Effect
  Cause1
    Secundary
      Tertiary
      Tertiary
  Cause2
    Secundary
      Tertiary
  Cause3
    Secundary
      Tertiary

It is probably a simple function.



Yours sincerely,
______________________________
Janos Juhasz

From mike.key at sbcglobal.net  Wed Jan 24 23:34:14 2007
From: mike.key at sbcglobal.net (Michael Key)
Date: Wed, 24 Jan 2007 14:34:14 -0800 (PST)
Subject: [Tutor] Tracking time
Message-ID: <20070124223414.20530.qmail@web82509.mail.mud.yahoo.com>

I am trying to develop a project tracking program that would allow you to track hours and minutes spent on several different projects and store he data in a database for printing. Any help would be appreciated.
 
Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070124/f803cfed/attachment.htm 

From rabidpoobear at gmail.com  Wed Jan 24 23:46:52 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 24 Jan 2007 16:46:52 -0600
Subject: [Tutor] Tracking time
In-Reply-To: <20070124223414.20530.qmail@web82509.mail.mud.yahoo.com>
References: <20070124223414.20530.qmail@web82509.mail.mud.yahoo.com>
Message-ID: <45B7E1DC.5080100@gmail.com>

Michael Key wrote:
> I am trying to develop a project tracking program that would allow you 
> to track hours and minutes spent on several different projects and 
> store he data in a database for printing. Any help would be appreciated.
You could store the start time using the time module.
when they're done with whatever you're timing,
get the current time again.
The difference between these two times is how long it took them to 
complete the task.
Decide on a database (oracle, postgre, mysql) and get the python library 
that lets you interface with your database and learn how to use it.
It's unclear what exactly a 'project' is from your e-mail so my reply is 
similarly vague, sorry.

HTH,
-Luke

From ke7fxl at gmail.com  Thu Jan 25 02:51:23 2007
From: ke7fxl at gmail.com (Tod Haren)
Date: Wed, 24 Jan 2007 17:51:23 -0800
Subject: [Tutor] Send binary/hex data to a TCP socket
Message-ID: <6f5b2c4e0701241751g773ba3ebt9486168e950d04b0@mail.gmail.com>

I need to send a server at the other end of a socket a 36 byte
"frame", where each byte represents a specific field in the custom
data structure.    (If there are any Ham operators reading this, I'm
talking about the AGW Packet Engine)

The documentation for the server says to initialize each field to a
binary zero(0x00).  How do I get a binary zero in Python?  The next
step is to send this all to the server and subsequently receive a
similarly formated frame.

A very basic frame looks something like this(modified from documentation):

    |00 00 00 00 4D 00 00 00 00 00 00 00 00 00 00 00 |....M...........
    |00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................
    |00 00 00 00 |....

My problem is that hex(0) return '0x0' and hex(ord('M')) returns
'0x4d'.  If I concatonate these all together then the socket receives
109 bytes instead of 36.  The documentation examples are in C++, so
they are little help to me.  The examples make use of the MoveMemory
function for building the frames, but I'm clueless what that does.

Pseudo code for the frame above:

  l = []
  for i in xrange(36):
    l.append(hex(0))

  l[4]=hex(ord('M'))

  d=''
  d=d.join(l)  #I need some other data type to send besides a string!
  sock.send(d)  #send the 36 bytes to the socket

Any pointers or references would be greatly appreciated.

From adam.jtm30 at gmail.com  Thu Jan 25 03:05:27 2007
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Thu, 25 Jan 2007 02:05:27 +0000
Subject: [Tutor] Send binary/hex data to a TCP socket
In-Reply-To: <6f5b2c4e0701241751g773ba3ebt9486168e950d04b0@mail.gmail.com>
References: <6f5b2c4e0701241751g773ba3ebt9486168e950d04b0@mail.gmail.com>
Message-ID: <be4fbf920701241805g19cb916ave04dae11410f97e9@mail.gmail.com>

On 25/01/07, Tod Haren <ke7fxl at gmail.com> wrote:
>
> I need to send a server at the other end of a socket a 36 byte
> "frame", where each byte represents a specific field in the custom
> data structure.    (If there are any Ham operators reading this, I'm
> talking about the AGW Packet Engine)
>
> The documentation for the server says to initialize each field to a
> binary zero(0x00).  How do I get a binary zero in Python?  The next
> step is to send this all to the server and subsequently receive a
> similarly formated frame.
>
> A very basic frame looks something like this(modified from documentation):
>
>     |00 00 00 00 4D 00 00 00 00 00 00 00 00 00 00 00 |....M...........
>     |00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................
>     |00 00 00 00 |....
>
> My problem is that hex(0) return '0x0' and hex(ord('M')) returns
> '0x4d'.  If I concatonate these all together then the socket receives
> 109 bytes instead of 36.  The documentation examples are in C++, so
> they are little help to me.  The examples make use of the MoveMemory
> function for building the frames, but I'm clueless what that does.
>
> Pseudo code for the frame above:
>
>   l = []
>   for i in xrange(36):
>     l.append(hex(0))
>
>   l[4]=hex(ord('M'))
>
>   d=''
>   d=d.join(l)  #I need some other data type to send besides a string!
>   sock.send(d)  #send the 36 bytes to the socket
>
> Any pointers or references would be greatly appreciated.


 This should do what you need:
http://docs.python.org/lib/module-struct.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070125/c9251b7b/attachment.html 

From shadabsayani at yahoo.com  Thu Jan 25 04:12:21 2007
From: shadabsayani at yahoo.com (Shadab Sayani)
Date: Thu, 25 Jan 2007 03:12:21 +0000 (GMT)
Subject: [Tutor]  Best IDE for Python
Message-ID: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>

Hi,
  I am using vim editor to code my project in python.Is there a good  IDE  where in I type the name of the class object and then dot  then all the attributes of the object are displayed so on.I tried to  install IDLE but I have no idea how to install tkinter?
  Any help that enables me to use good IDE as soon as possible is appreciated
  Thanks and Regards,
  Shadab
  
 Send instant messages to your online friends http://uk.messenger.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070125/df7dc966/attachment.htm 

From shadabsayani at yahoo.com  Thu Jan 25 04:22:46 2007
From: shadabsayani at yahoo.com (Shadab Sayani)
Date: Thu, 25 Jan 2007 03:22:46 +0000 (GMT)
Subject: [Tutor] Optimal solution in dealing with huge databases in python
Message-ID: <768410.66504.qm@web38711.mail.mud.yahoo.com>

Hi,
  I am working in a biodatabases project.The data I need to deal with is  in 100s of GB.I am using postgresql backend and SQLALCHEMY ORM.I need  to read the bio datafiles and parse them and then store them in  database.I am in the process of storing them.
  I used the session,flush concept in SQLALCHEMY.Initially I used to  flush every query immediately.Later I realised that the queries are  independent of each other and so started flushing 3-5 Lakh insert  queries at a time.This increased the response time.But the memory is  overflowing.Then I released not-in-use memory using del command in  python still there is no use as this del statement can only free part  of memory.I need to increase the above 3-5 lakh number to a much large  one to get a real time response.Other wise my estimation is it will  take 1 year to just insert the data into the database.From postgresql  side also I turned off WAL.
  Please suggest some viable solution to handle such enormous data from  python.Is there a better solution than SQL alchemy?Any solution that  speeds up my program is highly appreciated.
  Thanks and Regards,
  Shadab.
  
 Send instant messages to your online friends http://uk.messenger.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070125/9112087e/attachment.html 

From jfabiani at yolo.com  Thu Jan 25 04:28:13 2007
From: jfabiani at yolo.com (johnf)
Date: Wed, 24 Jan 2007 19:28:13 -0800
Subject: [Tutor] Tracking time
In-Reply-To: <20070124223414.20530.qmail@web82509.mail.mud.yahoo.com>
References: <20070124223414.20530.qmail@web82509.mail.mud.yahoo.com>
Message-ID: <200701241928.13384.jfabiani@yolo.com>

On Wednesday 24 January 2007 14:34, Michael Key wrote:
> I am trying to develop a project tracking program that would allow you to
> track hours and minutes spent on several different projects and store he
> data in a database for printing. Any help would be appreciated.
>
> Mike

Take a good look at Dabo @ www.dabodev.com
Check out the latest screencast.  Dabo was designed from bottom to support 
database and GUI apps.
-- 
John Fabiani

From rdm at rcblue.com  Thu Jan 25 06:22:18 2007
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 24 Jan 2007 21:22:18 -0800
Subject: [Tutor] Best IDE for Python
In-Reply-To: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
Message-ID: <7.0.1.0.2.20070124211941.06bb6bd0@rcblue.com>

At 07:12 PM 1/24/2007, Shadab Sayani wrote:
>Hi,
>I am using vim editor to code my project in python.Is there a good 
>IDE  where in I type the name of the class object and then dot then 
>all the attributes of the object are displayed so on.

I believe IPython does this. Check out <http://ipython.scipy.org/moin/>.

Dick Moores




From jakieabraham at yahoo.com  Thu Jan 25 07:11:15 2007
From: jakieabraham at yahoo.com (Jacob Abraham)
Date: Wed, 24 Jan 2007 22:11:15 -0800 (PST)
Subject: [Tutor] Python re without string consumption
Message-ID: <941262.80717.qm@web54109.mail.yahoo.com>

Dear Tutors,

   I'm having a little trouble while using the re module.

eg

>>> import re
>>> re.findall("abca", "abcabcabca")
["abca", "abca"]

While I am expecting.

["abca", "abca", "abca"]

How do I modify my regular expression to do the same.

Thanks for the help.

Regards,
Jacob Abraham




 
____________________________________________________________________________________
Never miss an email again!
Yahoo! Toolbar alerts you the instant new Mail arrives.
http://tools.search.yahoo.com/toolbar/features/mail/

From dyoo at hkn.eecs.berkeley.edu  Thu Jan 25 07:44:31 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 24 Jan 2007 22:44:31 -0800 (PST)
Subject: [Tutor] Python re without string consumption
In-Reply-To: <941262.80717.qm@web54109.mail.yahoo.com>
References: <941262.80717.qm@web54109.mail.yahoo.com>
Message-ID: <Pine.LNX.4.64.0701242222230.29366@hkn.eecs.berkeley.edu>



On Wed, 24 Jan 2007, Jacob Abraham wrote:

>>>> import re
>>>> re.findall("abca", "abcabcabca")
> ["abca", "abca"]
>
> While I am expecting.
>
> ["abca", "abca", "abca"]


Hi Jacob,

Just to make sure: do you understand, though, why findall() won't give you 
the results you want?  The documentation on findall() says:

""" Return a list of all non-overlapping matches of pattern in string. If 
one or more groups are present in the pattern, return a list of groups; 
this will be a list of tuples if the pattern has more than one group. 
Empty matches are included in the result unless they touch the beginning 
of another match. New in version 1.5.2. Changed in version 2.4: Added the 
optional flags argument. """

It's designed not to return overlapping items.



> How do I modify my regular expression to do the same.

We can just write our own helper function to restart the match.  That is, 
we can expliciltely call search() ourselves, and pass in a new string 
that's a fragment of the old one.


Concretely,

#############
>>> import re
>>> text = "abcabcabca"
>>> re.search("abca", text)
<_sre.SRE_Match object at 0x50d40>
>>> re.search("abca", text).start()
0
#############

Ok, so we know the first match starts at 0.  So let's just restart the 
search, skipping that position.

##################################
>>> re.search("abca", text[1:])
<_sre.SRE_Match object at 0x785d0>
>>> re.search("abca", text[1:]).start()
2
##################################

There's our second match.  Let's continue.  We have to be careful, though, 
to make sure we're skipping the right number of characters:

#######################################
>>> re.search("abca", text[4:]).start()
2
>>> re.search("abca", text[7:])
>>> 
#######################################

And there are no matches after this point.


You can try writing this helper function yourself.  If you need help doing 
so, please feel free to ask the list for suggestions.

From jakieabraham at yahoo.com  Thu Jan 25 08:22:18 2007
From: jakieabraham at yahoo.com (Jacob Abraham)
Date: Wed, 24 Jan 2007 23:22:18 -0800 (PST)
Subject: [Tutor] Python re without string consumption
Message-ID: <559442.72938.qm@web54114.mail.yahoo.com>

Hi Danny Yoo,

   I would like to thank you for the solution and the helper funtion that I have written is as follows. But I do hope that future versions of Python include a regular expression syntax to handle such cases simply because this method seems very process and memory intensive. I also notice that fall_back_len is a very crude solution.

def searchall(expr, text, fall_back_len=0):

    while True:

        match =  re.search(expr, text)

        if not match:

            break

        yield match

        end = match.end()

        text = text[end-fallbacklen:]



for match in searchall("abca", "abcabcabca", 1):

   print match.group()

Thanks Again.

Jacob Abraham





----- Original Message ----
From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
To: Jacob Abraham <jakieabraham at yahoo.com>
Cc: python <tutor at python.org>
Sent: Thursday, January 25, 2007 12:14:31 PM
Subject: Re: [Tutor] Python re without string consumption



On Wed, 24 Jan 2007, Jacob Abraham wrote:

>>>> import re
>>>> re.findall("abca", "abcabcabca")
> ["abca", "abca"]
>
> While I am expecting.
>
> ["abca", "abca", "abca"]


Hi Jacob,

Just to make sure: do you understand, though, why findall() won't give you 
the results you want?  The documentation on findall() says:

""" Return a list of all non-overlapping matches of pattern in string. If 
one or more groups are present in the pattern, return a list of groups; 
this will be a list of tuples if the pattern has more than one group. 
Empty matches are included in the result unless they touch the beginning 
of another match. New in version 1.5.2. Changed in version 2.4: Added the 
optional flags argument. """

It's designed not to return overlapping items.



> How do I modify my regular expression to do the same.

We can just write our own helper function to restart the match.  That is, 
we can expliciltely call search() ourselves, and pass in a new string 
that's a fragment of the old one.


Concretely,

#############
>>> import re
>>> text = "abcabcabca"
>>> re.search("abca", text)
<_sre.SRE_Match object at 0x50d40>
>>> re.search("abca", text).start()
0
#############

Ok, so we know the first match starts at 0.  So let's just restart the 
search, skipping that position.

##################################
>>> re.search("abca", text[1:])
<_sre.SRE_Match object at 0x785d0>
>>> re.search("abca", text[1:]).start()
2
##################################

There's our second match.  Let's continue.  We have to be careful, though, 
to make sure we're skipping the right number of characters:

#######################################
>>> re.search("abca", text[4:]).start()
2
>>> re.search("abca", text[7:])
>>> 
#######################################

And there are no matches after this point.


You can try writing this helper function yourself.  If you need help doing 
so, please feel free to ask the list for suggestions.





 
____________________________________________________________________________________
Do you Yahoo!?
Everyone is raving about the all-new Yahoo! Mail beta.
http://new.mail.yahoo.com

From rabidpoobear at gmail.com  Thu Jan 25 08:52:51 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 25 Jan 2007 01:52:51 -0600
Subject: [Tutor] Python re without string consumption
In-Reply-To: <559442.72938.qm@web54114.mail.yahoo.com>
References: <559442.72938.qm@web54114.mail.yahoo.com>
Message-ID: <45B861D3.6090604@gmail.com>


>
> def searchall(expr, text, fall_back_len=0):
> [snip]
>
>         text = text[end-fallbacklen:]
oops, those look like two different variables to me.

From jakieabraham at yahoo.com  Thu Jan 25 09:16:25 2007
From: jakieabraham at yahoo.com (Jacob Abraham)
Date: Thu, 25 Jan 2007 00:16:25 -0800 (PST)
Subject: [Tutor] Python re without string consumption
Message-ID: <888004.78133.qm@web54111.mail.yahoo.com>

Hi Danny Yoo,

   I would like to thank you for the solution and
the helper funtion that I have written is as follows. But I do hope
that future versions of Python include a regular expression syntax to
handle such cases simply because this method seems very process and
memory intensive. I also notice that fall_back_len is a very crude
solution.

def searchall(expr, text, fall_back_len=0):
    while True:
        match =  re.search(expr, text)
        if not match:
            break
        yield match
        end = match.end()
        text = text[end-fall_back_len:]

for match in searchall("abca", "abcabcabca", 1):
   print match.group()

Thanks Again.

Jacob Abraham




 
____________________________________________________________________________________
Get your own web address.  
Have a HUGE year through Yahoo! Small Business.
http://smallbusiness.yahoo.com/domains/?p=BESTDEAL

From ke7fxl at gmail.com  Thu Jan 25 09:46:44 2007
From: ke7fxl at gmail.com (Tod Haren)
Date: Thu, 25 Jan 2007 00:46:44 -0800
Subject: [Tutor] Send binary/hex data to a TCP socket
In-Reply-To: <be4fbf920701241805g19cb916ave04dae11410f97e9@mail.gmail.com>
References: <6f5b2c4e0701241751g773ba3ebt9486168e950d04b0@mail.gmail.com>
	<be4fbf920701241805g19cb916ave04dae11410f97e9@mail.gmail.com>
Message-ID: <6f5b2c4e0701250046n47060be0neac60000af0af092@mail.gmail.com>

The struct module seems to fit the bill.  Thanks Adam

From alan.gauld at btinternet.com  Thu Jan 25 10:34:21 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 25 Jan 2007 09:34:21 -0000
Subject: [Tutor] Send binary/hex data to a TCP socket
References: <6f5b2c4e0701241751g773ba3ebt9486168e950d04b0@mail.gmail.com>
Message-ID: <ep9tiv$35s$1@sea.gmane.org>

"Tod Haren" <ke7fxl at gmail.com> wrote

>I need to send a server at the other end of a socket a 36 byte
> "frame", where each byte represents a specific field in the custom
> data structure.

If its all single bytes then its fairly easy.

> The documentation for the server says to initialize each field to a
> binary zero(0x00).  How do I get a binary zero in Python?

Binary zero is the same as any other zero. So use the char function(to 
limit it to a single byte):

>>> char(0)
'\0x00'

Now if you are worried that this looks like more than a single
byte don't be, its not. The \0x is not included its just there for
representation.

>>> len(chr(0))
1

> A very basic frame looks something like this(modified from 
> documentation):
>
>    |00 00 00 00 4D 00 00 00 00 00 00 00 00 00 00 00 
> |....M...........
>    |00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
> |................
>    |00 00 00 00 |....
>
> My problem is that hex(0) return '0x0' and hex(ord('M')) returns
> '0x4d'.

You don't want the hex representation of the data you want the
data in byte format, namely a character.

> 109 bytes instead of 36.  The documentation examples are in C++, so
> they are little help to me.  The examples make use of the MoveMemory
> function for building the frames, but I'm clueless what that does.

It literally moves blocks of memory around. It workls at
the RAM address level. There is no direct equivalent in Python.

> Pseudo code for the frame above:
>
>  l = []
>  for i in xrange(36):
>    l.append(hex(0))

L = [chr(0) for n in range(36)]

>  l[4]=hex(ord('M'))

L[4] = 'M'

>  d=''.join(l)

> # I need some other data type to send besides a string!

No a 36 character string is what you want to send.
Don't let the term byte scare you, ascii characters are bytes.

If the data gets more complex and you need to send integers
(4 bytes) etc then you need to look to the struct module.
But for simple byte sequences there's no need.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Thu Jan 25 10:41:26 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 25 Jan 2007 09:41:26 -0000
Subject: [Tutor] Best IDE for Python
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
Message-ID: <ep9u08$4hp$1@sea.gmane.org>

"Shadab Sayani" <shadabsayani at yahoo.com> wrote 

>  I am using vim editor to code my project in python.

Its not so much tthe editor that matters as the OS!
Are you using Linux(I suspect) or Windows or MacOS?
(Or something else!)

> Is there a good  IDE  where in I type the name of 
> the class object and then dot  then all the attributes 
> of the object are displayed so on.

There are several that do this but many are OS specific.
The PythonWin IDE that comes as standard in the winall 
package or the ActiveState version of Pytthon can do this.

I'm prettty sure Blackadder, Wing and Eclipse will do it too.

> I tried to  install IDLE but I have no idea how to install tkinter?

Tkinter is usually built in to Python. If you are compiling 
from source (on Linux?) You need to configure the makefile 
to include it, but most pre-built packages will have it.

> Any help that enables me to use good IDE as soon 
> as possible is appreciated

Personally I just use vim and an interpreter prompt! :-)
Because of the dynamic nature of Python I tend to know 
what options I need  before I get to typing in the editor so 
parameter pop-ups etc are less valuable in Python than 
in C/Java etc.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at btinternet.com  Thu Jan 25 10:56:34 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 25 Jan 2007 09:56:34 -0000
Subject: [Tutor] Optimal solution in dealing with huge databases in
	python
References: <768410.66504.qm@web38711.mail.mud.yahoo.com>
Message-ID: <ep9usk$7bt$1@sea.gmane.org>

"Shadab Sayani" <shadabsayani at yahoo.com> wrote 

> The data I need to deal with is  in 100s of GB.
> I am using postgresql backend and SQLALCHEMY ORM.

All ORMs will introduce a significant performance hit.
If you really need high speed, and populating a 100G+ database 
probably is included in that, then you should look at raw SQL.
In fact for really big data loads most databases provide a 
C api that goes under the SQL, because even SQL is 
relatively slow.

As an example, we use a large Oracle database at work.
Loading about 3 Terabytes of data through an ORM took 
over 3 months! Loading it through SQL took about 3 days.
Loading it through the C API took less than a day.

Your mileage may vary since a lot depends on locks, 
indexes etc etc. And of course the server spec!

But for loading large data volumes get as close to the metal 
as possible. Once the data is loaded you can use the 
ORM to simplify the application code for extracting and 
modifying the data.

> I need  to read the bio datafiles and parse them and 
> then store them in  database.

Parsing them and preparing the SQL statements can 
be done in Python. But the actual loading I suggest 
should be done in SQL if possible (The C aPI should 
be a last resort - its frought with danger!)

> Please suggest some viable solution to handle such 
> enormous data from  python.

A few hundred gigabytes is not too enormous these days
but you are never going to achieve times of less than hours.
You do need to be realistic about that. And if you are using
a standard PC spec server instead of a large multi CPU 
box with SCSI/RAID disc arrays etc then you could be 
looking at days.

The other important factor is your data schema. The more 
tables, joins, indexes etc the database has to maintain the 
more work it takes and the sloewer it gets. The 3TB example 
I gave had over 2000 tables, so it was always going to be 
slow. If you have a single unindexed table then it will be 
much simpler. (But the queries later will be much harder!)

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From Senthil_OR at Dell.com  Thu Jan 25 11:04:06 2007
From: Senthil_OR at Dell.com (Senthil_OR at Dell.com)
Date: Thu, 25 Jan 2007 15:34:06 +0530
Subject: [Tutor] Best IDE for Python
In-Reply-To: <7.0.1.0.2.20070124211941.06bb6bd0@rcblue.com>
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
	<7.0.1.0.2.20070124211941.06bb6bd0@rcblue.com>
Message-ID: <D6ED7B7268DC0F4C9BF6AF2537BCE5C69471A9@blrx3m03.blr.amer.dell.com>

Dick Moores wrote:
>> Hi,
>> I am using vim editor to code my project in python.Is there a good
>> IDE  where in I type the name of the class object and then dot then
>> all the attributes of the object are displayed so on.
> 
> I believe IPython does this. Check out
> <http://ipython.scipy.org/moin/>. 
> 

Vim 7.0 has the omni complete facility, which will help you complete..
--- object.<c-x><c-n>attributes.

Also, python 2.5 IDLE and (Mark Hammonds) PythonWin Editor supports
command completion.


-- 
Senthil


Capitalism is the astounding belief that the most wickedest of men will
do the most wickedest of things for the greatest good of everyone.
Keynes 

From kent37 at tds.net  Thu Jan 25 12:13:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 25 Jan 2007 06:13:48 -0500
Subject: [Tutor] Python re without string consumption
In-Reply-To: <888004.78133.qm@web54111.mail.yahoo.com>
References: <888004.78133.qm@web54111.mail.yahoo.com>
Message-ID: <45B890EC.9000801@tds.net>

Jacob Abraham wrote:
> Hi Danny Yoo,
> 
>    I would like to thank you for the solution and
> the helper funtion that I have written is as follows. But I do hope
> that future versions of Python include a regular expression syntax to
> handle such cases simply because this method seems very process and
> memory intensive. I also notice that fall_back_len is a very crude
> solution.
> 
> def searchall(expr, text, fall_back_len=0):
>     while True:
>         match =  re.search(expr, text)
>         if not match:
>             break
>         yield match
>         end = match.end()
>         text = text[end-fall_back_len:]
> 
> for match in searchall("abca", "abcabcabca", 1):
>    print match.group()

The string slicing is not needed. The search() method for a compiled re 
has an optional pos parameter that tells where to start the search,. You 
can start the next search at the next position after the *start* of a 
successful search, so fall_back_len is not needed. How about this:

def searchall(expr, text):
   searchRe = re.compile(expr)
   match = searchRe.search(text)
   while match:
     yield match
     match = searchRe.search(text, match.start() + 1)

Also, if you are just finding plain text, you don't need to use regular 
expressions at all, you can use str.find():

def searchall(expr, text):
   pos = text.find(expr)
   while pos != -1:
     yield pos
     pos = text.find(expr, pos+1)

(inspired by this recipe: 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499314)

Kent


From hieu.d.hoang at gmail.com  Thu Jan 25 12:52:14 2007
From: hieu.d.hoang at gmail.com (Hieu Hoang)
Date: Thu, 25 Jan 2007 18:52:14 +0700
Subject: [Tutor] Best IDE for Python
Message-ID: <4f12b0dd0701250352m57817b92mf86c4acf4125bc1a@mail.gmail.com>

Hi all,

> ---------- Forwarded message ----------
> From: "Alan Gauld" <alan.gauld at btinternet.com>
  [snip]
> > Is there a good  IDE  where in I type the name of
> > the class object and then dot  then all the attributes
> > of the object are displayed so on.
>
> There are several that do this but many are OS specific.
> The PythonWin IDE that comes as standard in the winall
> package or the ActiveState version of Pytthon can do this.
>
> I'm prettty sure Blackadder, Wing and Eclipse will do it too.

 I can add Geany, SPE, and after reading Senthil's remark on gVim c-x
c-n, Pida. Geany works on top of PyGTK, SPE on wxPython, pida need
kiwi which requires pygtk also.

> > I tried to  install IDLE but I have no idea how to install tkinter?
>
> Tkinter is usually built in to Python. If you are compiling
> from source (on Linux?) You need to configure the makefile
> to include it, but most pre-built packages will have it.

 On self-compiled python, I just need to have tcl-dev and tk-dev
packages installed (ubuntu linux), and the configure script does the
proper work. I have only tried the epydoc gui.

> > Any help that enables me to use good IDE as soon
> > as possible is appreciated
>
> Personally I just use vim and an interpreter prompt! :-)

Me too, just that pida bundles them in one window.

Hieu

From zebra05 at gmail.com  Thu Jan 25 13:50:00 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Thu, 25 Jan 2007 14:50:00 +0200
Subject: [Tutor] Best IDE for Python
In-Reply-To: <4f12b0dd0701250352m57817b92mf86c4acf4125bc1a@mail.gmail.com>
References: <4f12b0dd0701250352m57817b92mf86c4acf4125bc1a@mail.gmail.com>
Message-ID: <c7c6f3bc0701250450u49154a96t4aecbaf7308d6e26@mail.gmail.com>

hi guys,

would someone please point me to an active link to download SPE? the url to
Stani's site just wont click through to
http://stani.be/python/spe/blog/

i have a similar problem with the url to the Windows distro of Lighttpd from
http://www.kevinworthington.com:8181/

would appreciate any help...


kind regards,

"Shortash"

On 1/25/07, Hieu Hoang <hieu.d.hoang at gmail.com> wrote:
>
> Hi all,
>
> > ---------- Forwarded message ----------
> > From: "Alan Gauld" <alan.gauld at btinternet.com>
>   [snip]
> > > Is there a good  IDE  where in I type the name of
> > > the class object and then dot  then all the attributes
> > > of the object are displayed so on.
> >
> > There are several that do this but many are OS specific.
> > The PythonWin IDE that comes as standard in the winall
> > package or the ActiveState version of Pytthon can do this.
> >
> > I'm prettty sure Blackadder, Wing and Eclipse will do it too.
>
> I can add Geany, SPE, and after reading Senthil's remark on gVim c-x
> c-n, Pida. Geany works on top of PyGTK, SPE on wxPython, pida need
> kiwi which requires pygtk also.
>
> > > I tried to  install IDLE but I have no idea how to install tkinter?
> >
> > Tkinter is usually built in to Python. If you are compiling
> > from source (on Linux?) You need to configure the makefile
> > to include it, but most pre-built packages will have it.
>
> On self-compiled python, I just need to have tcl-dev and tk-dev
> packages installed (ubuntu linux), and the configure script does the
> proper work. I have only tried the epydoc gui.
>
> > > Any help that enables me to use good IDE as soon
> > > as possible is appreciated
> >
> > Personally I just use vim and an interpreter prompt! :-)
>
> Me too, just that pida bundles them in one window.
>
> Hieu
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070125/f7930123/attachment.htm 

From hieu.d.hoang at gmail.com  Thu Jan 25 14:15:16 2007
From: hieu.d.hoang at gmail.com (Hieu Hoang)
Date: Thu, 25 Jan 2007 20:15:16 +0700
Subject: [Tutor] Best IDE for Python
In-Reply-To: <c7c6f3bc0701250450u49154a96t4aecbaf7308d6e26@mail.gmail.com>
References: <4f12b0dd0701250352m57817b92mf86c4acf4125bc1a@mail.gmail.com>
	<c7c6f3bc0701250450u49154a96t4aecbaf7308d6e26@mail.gmail.com>
Message-ID: <4f12b0dd0701250515m46c1a006qdaa81e44cdd2f03@mail.gmail.com>

On 1/25/07, OkaMthembo <zebra05 at gmail.com> wrote:
> hi guys,
>
> would someone please point me to an active link to download SPE? the url to
> Stani's site just wont click through to
> http://stani.be/python/spe/blog/

A while ago the SPE's author said something on python-list to the
effect that he was looking for another host for stani.be. There're
still the Berlios project page. ... Well, to be honest, the svn link
still works, but I haven't found the website yet
svn checkout svn://svn.berlios.de/python spe
Copy the _spe folder to your site-package, then run the file SPE.py should work.

Hope this helps,
Hieu

From shadabsayani at yahoo.com  Thu Jan 25 15:01:36 2007
From: shadabsayani at yahoo.com (Shadab Sayani)
Date: Thu, 25 Jan 2007 14:01:36 +0000 (GMT)
Subject: [Tutor] Optimal solution in dealing with huge databases in
	python
In-Reply-To: <ep9usk$7bt$1@sea.gmane.org>
Message-ID: <889386.70898.qm@web38710.mail.mud.yahoo.com>

Hi Alan,
Thank you very much for immediate response.I didnt get
the point of loading the data using SQL.What does that
mean?Does it mean Bulk file load.If so then there will
I/O performance hit right.Writing the parsed tokens in
the csv format in a file.After that only I can bulk
load this file.
Do have any idea about the C api for Postgresql and
some documentation to use it?
Thanks and Regards,
Shadab.
--- Alan Gauld <alan.gauld at btinternet.com> wrote:

> "Shadab Sayani" <shadabsayani at yahoo.com> wrote 
> 
> > The data I need to deal with is  in 100s of GB.
> > I am using postgresql backend and SQLALCHEMY ORM.
> 
> All ORMs will introduce a significant performance
> hit.
> If you really need high speed, and populating a
> 100G+ database 
> probably is included in that, then you should look
> at raw SQL.
> In fact for really big data loads most databases
> provide a 
> C api that goes under the SQL, because even SQL is 
> relatively slow.
> 
> As an example, we use a large Oracle database at
> work.
> Loading about 3 Terabytes of data through an ORM
> took 
> over 3 months! Loading it through SQL took about 3
> days.
> Loading it through the C API took less than a day.
> 
> Your mileage may vary since a lot depends on locks, 
> indexes etc etc. And of course the server spec!
> 
> But for loading large data volumes get as close to
> the metal 
> as possible. Once the data is loaded you can use the
> 
> ORM to simplify the application code for extracting
> and 
> modifying the data.
> 
> > I need  to read the bio datafiles and parse them
> and 
> > then store them in  database.
> 
> Parsing them and preparing the SQL statements can 
> be done in Python. But the actual loading I suggest 
> should be done in SQL if possible (The C aPI should 
> be a last resort - its frought with danger!)
> 
> > Please suggest some viable solution to handle such
> 
> > enormous data from  python.
> 
> A few hundred gigabytes is not too enormous these
> days
> but you are never going to achieve times of less
> than hours.
> You do need to be realistic about that. And if you
> are using
> a standard PC spec server instead of a large multi
> CPU 
> box with SCSI/RAID disc arrays etc then you could be
> 
> looking at days.
> 
> The other important factor is your data schema. The
> more 
> tables, joins, indexes etc the database has to
> maintain the 
> more work it takes and the sloewer it gets. The 3TB
> example 
> I gave had over 2000 tables, so it was always going
> to be 
> slow. If you have a single unindexed table then it
> will be 
> much simpler. (But the queries later will be much
> harder!)
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


Send instant messages to your online friends http://uk.messenger.yahoo.com 

From Mike.Hansen at atmel.com  Thu Jan 25 16:17:05 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 25 Jan 2007 08:17:05 -0700
Subject: [Tutor] Best IDE for Python
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
Message-ID: <57B026980605A64F9B23484C5659E32E5B151E@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Shadab Sayani
> Sent: Wednesday, January 24, 2007 8:12 PM
> To: tutor at python.org
> Subject: [Tutor] Best IDE for Python
> 
> Hi,
> I am using vim editor to code my project in python.Is there a 
> good IDE  where in I type the name of the class object and 
> then dot then all the attributes of the object are displayed 
> so on.I tried to install IDLE but I have no idea how to 
> install tkinter?
> Any help that enables me to use good IDE as soon as possible 
> is appreciated
> Thanks and Regards,
> Shadab
> 

Someone mentioned that VIM 7 does this. You might need to pick up the
latest python.vim file from vim.org.

Activestate just released Komodo Edit and Komodo IDE. I believe both do
auto-completion that shows a list of possibilities. Komodo Edit is free
and Komodo IDE cost some $$.

Mike
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS

From python-tutor at ccoker.net  Thu Jan 25 16:21:35 2007
From: python-tutor at ccoker.net (Chuck Coker)
Date: Thu, 25 Jan 2007 07:21:35 -0800
Subject: [Tutor] Optimal solution in dealing with huge databases
	in	python
In-Reply-To: <889386.70898.qm@web38710.mail.mud.yahoo.com>
References: <889386.70898.qm@web38710.mail.mud.yahoo.com>
Message-ID: <45B8CAFF.9080905@ccoker.net>

This page has some info on C/C++ for PostgreSQL:
http://www.postgresql.org/docs/8.0/interactive/xfunc-c.html

Shadab Sayani wrote:

> Do have any idea about the C api for Postgresql and
> some documentation to use it?

-- 
======================================================================
Chuck Coker, Software Developer                python-tutor at ccoker.net
Tyrell Software Corporation                      http://www.tyrell.com
Office: +1 949 458 1911 x 203                    Cell: +1 714 326 5939
======================================================================


From tim at johnsons-web.com  Thu Jan 25 17:02:43 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Thu, 25 Jan 2007 07:02:43 -0900
Subject: [Tutor] Best IDE for Python
In-Reply-To: <57B026980605A64F9B23484C5659E32E5B151E@poccso.US.ad.atmel.com>
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
	<57B026980605A64F9B23484C5659E32E5B151E@poccso.US.ad.atmel.com>
Message-ID: <200701250702.43188.tim@johnsons-web.com>

On Thursday 25 January 2007 06:17 am, Mike Hansen wrote:
 
> Someone mentioned that VIM 7 does this. You might need to pick up the
> latest python.vim file from vim.org.

Vim offers some intriguing possibilities for python:
If you compile Vim from source, the python interpreter can be "compiled into" 
the Vim executable. A number of Vim add-ons are available for python in this
configuration.
I also use emacs and xemacs which enables running the interpreter inside of 
the editor. Really nice feature!

> Activestate just released Komodo Edit and Komodo IDE. I believe both do
> auto-completion that shows a list of possibilities. Komodo Edit is free
> and Komodo IDE cost some $$.

IMHO: If one programs in more than one programming language, the
ultimate would be an editor/IDE that can accommodate all with similar
functionality and behavior for all. 

MTCW
tim 

From alan.gauld at btinternet.com  Thu Jan 25 18:23:48 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 25 Jan 2007 17:23:48 -0000
Subject: [Tutor] Optimal solution in dealing with huge databases inpython
References: <ep9usk$7bt$1@sea.gmane.org>
	<889386.70898.qm@web38710.mail.mud.yahoo.com>
Message-ID: <epap36$dgb$1@sea.gmane.org>

"Shadab Sayani" <shadabsayani at yahoo.com> wrote 

> Thank you very much for immediate response.I didnt get
> the point of loading the data using SQL.What does that
> mean?

It means writing a SQL file that can then be run from 
the database SQL prompt. I don't know what that means 
in PostGres terms since I use Oracle mainly. But in Oracle 
it would involve typing

$ sqlplus loadfile.sql

And sqlplus would execute the SQL commands in loadfile.sql.

Loadfile.sql would in turn contain lots of SQL commands like:

INSERT into CUSTOMER 
VALUES ( 'fred', 'bloggs', 45, '01773-987321');

One thing to note is that due to caching issues you might find 
it works better if you keep the individual loader files fairly small 
- say 1000 or so records each. On other databases (DB2 for 
example) very big data files seem to be faster, it just depends on 
how the internal SQL engine works.

> Does it mean Bulk file load.If so then there will
> I/O performance hit right.

There will aleays be a big I/O load if you are loading data 
into a database, at some stage it must get onto the disk!

> Writing the parsed tokens in the csv format in a file.

I would use Python to translate the CSV data into SQL 
command like the INSERT statement above.

> Do have any idea about the C api for Postgresql and
> some documentation to use it?

Nope. I don't use Postgres.
There are usually two levels of API, the one that 
allows you to write SQL commands from C. That's not 
much advantage over the Pytthon DBAPI, and the one 
that bypasses SQL to allow you to access the raw data 
on the disk, thats the fast one. But it does require a good 
knowledge of how the underlying data structuires are 
stored within the files. Oracle, DB2, Informix etc will have 
that documented somlewhere but open source databases 
may require you to read the source! As I say its fast, 
but very, very risky.

Alan G.


From jfabiani at yolo.com  Thu Jan 25 19:20:36 2007
From: jfabiani at yolo.com (johnf)
Date: Thu, 25 Jan 2007 10:20:36 -0800
Subject: [Tutor] Optimal solution in dealing with huge databases in
	python
In-Reply-To: <768410.66504.qm@web38711.mail.mud.yahoo.com>
References: <768410.66504.qm@web38711.mail.mud.yahoo.com>
Message-ID: <200701251020.36033.jfabiani@yolo.com>

On Wednesday 24 January 2007 19:22, Shadab Sayani wrote:
> Hi,
>   I am working in a biodatabases project.The data I need to deal with is 
> in 100s of GB.I am using postgresql backend and SQLALCHEMY ORM.I need  to
> read the bio datafiles and parse them and then store them in  database.I am
> in the process of storing them. I used the session,flush concept in
> SQLALCHEMY.Initially I used to  flush every query immediately.Later I
> realised that the queries are  independent of each other and so started
> flushing 3-5 Lakh insert  queries at a time.This increased the response
> time.But the memory is  overflowing.Then I released not-in-use memory using
> del command in  python still there is no use as this del statement can only
> free part  of memory.I need to increase the above 3-5 lakh number to a much
> large  one to get a real time response.Other wise my estimation is it will 
> take 1 year to just insert the data into the database.From postgresql  side
> also I turned off WAL. Please suggest some viable solution to handle such
> enormous data from  python.Is there a better solution than SQL alchemy?Any
> solution that  speeds up my program is highly appreciated. Thanks and
> Regards,
>   Shadab.
>
>  Send instant messages to your online friends http://uk.messenger.yahoo.com

To tell the truth I know nothing about SQLALCHEMY ORM.  But I do know how to 
load large amounts of data into Postgres.  You use the 'copy ... from' 
command.  I once had 2 gigs of data and was surprised how fast it added the 
data.  Two things to remember:
1.  no indexes
2.  you have to format the data correctly - see Postgres DOC's

BTW I use psycopg for my connection
-- 
John Fabiani

From Mike.Hansen at atmel.com  Thu Jan 25 20:55:50 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 25 Jan 2007 12:55:50 -0700
Subject: [Tutor] Best IDE for Python
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com><57B026980605A64F9B23484C5659E32E5B151E@poccso.US.ad.atmel.com>
	<200701250702.43188.tim@johnsons-web.com>
Message-ID: <57B026980605A64F9B23484C5659E32E5B1573@poccso.US.ad.atmel.com>

 

> 
> > Activestate just released Komodo Edit and Komodo IDE. I 
> believe both do
> > auto-completion that shows a list of possibilities. Komodo 
> Edit is free
> > and Komodo IDE cost some $$.
> 
> IMHO: If one programs in more than one programming language, the
> ultimate would be an editor/IDE that can accommodate all with similar
> functionality and behavior for all. 
> 
> MTCW
> tim 

I agree. Depending on what I'm doing, I toggle between VIM and Komodo. I
like that both can handle multiple languages. 

Mike
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS

From dkuhlman at rexx.com  Thu Jan 25 21:35:44 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Thu, 25 Jan 2007 12:35:44 -0800
Subject: [Tutor] Best IDE for Python
In-Reply-To: <200701250702.43188.tim@johnsons-web.com>
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
	<57B026980605A64F9B23484C5659E32E5B151E@poccso.US.ad.atmel.com>
	<200701250702.43188.tim@johnsons-web.com>
Message-ID: <20070125203544.GA82864@cutter.rexx.com>

On Thu, Jan 25, 2007 at 07:02:43AM -0900, Tim Johnson wrote:
[snip]
> 
> IMHO: If one programs in more than one programming language, the
> ultimate would be an editor/IDE that can accommodate all with similar
> functionality and behavior for all. 

Maybe Eclipse (http://www.eclipse.org/)?  There is a plug-in for
Python.

But, on my machine, the last time I looked, it was buggy and
incredibly slow.

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From eric at ericwalstad.com  Thu Jan 25 23:36:49 2007
From: eric at ericwalstad.com (Eric Walstad)
Date: Thu, 25 Jan 2007 14:36:49 -0800
Subject: [Tutor] Optimal solution in dealing with huge databases
	in	python
In-Reply-To: <ep9usk$7bt$1@sea.gmane.org>
References: <768410.66504.qm@web38711.mail.mud.yahoo.com>
	<ep9usk$7bt$1@sea.gmane.org>
Message-ID: <45B93101.7060702@ericwalstad.com>

Alan Gauld wrote:
> "Shadab Sayani" <shadabsayani at yahoo.com> wrote 
> 
>> The data I need to deal with is  in 100s of GB.
>> I am using postgresql backend and SQLALCHEMY ORM.
> 
> All ORMs will introduce a significant performance hit.
> If you really need high speed, and populating a 100G+ database 
> probably is included in that, then you should look at raw SQL.
> In fact for really big data loads most databases provide a 
> C api that goes under the SQL, because even SQL is 
> relatively slow.

I've had this experience, too.  I routinely load a couple million
records from a tab delimited file into our PostgreSQL database with
Python.  My import script:
 1. iterates over the tab file a line/record at a time
 2. does some data validation, some data manipulation
 3. writes an SQL file with the massaged data
 4. calls psql <dbname> -f <python-generated sql file>

Generating the SQL file in python goes amazingly fast, considering the
amount of validation and manipulation (normalizing addresses, generating
hashes, etc) - about 1.5minutes/million records.

The SQL it generates does the usual DB stuff including dropping indexes
and constraints, COPY FROM stdin, regenerate indexes, replace
constraints.  In my experience, psql is MUCH faster at these kinds of
imports than even direct python interaction with psycopg.  Adding an ORM
on top of the database connector (psycopg in my case) slows things down
even more.

As a rough metric, the import I described takes a little over 2 hours on
my 2GHz/1GB laptop.

Good luck,

Eric.

From eric at ericwalstad.com  Thu Jan 25 23:57:29 2007
From: eric at ericwalstad.com (Eric Walstad)
Date: Thu, 25 Jan 2007 14:57:29 -0800
Subject: [Tutor] Optimal solution in dealing with huge databases inpython
In-Reply-To: <epap36$dgb$1@sea.gmane.org>
References: <ep9usk$7bt$1@sea.gmane.org>	<889386.70898.qm@web38710.mail.mud.yahoo.com>
	<epap36$dgb$1@sea.gmane.org>
Message-ID: <45B935D9.2010001@ericwalstad.com>

Alan Gauld wrote:
> "Shadab Sayani" <shadabsayani at yahoo.com> wrote 
> 
>> Thank you very much for immediate response.I didnt get
>> the point of loading the data using SQL.What does that
>> mean?
> 
> It means writing a SQL file that can then be run from 
> the database SQL prompt. I don't know what that means 
> in PostGres terms

psql <dbname> -f <loadfile>


> Loadfile.sql would in turn contain lots of SQL commands like:
> 
> INSERT into CUSTOMER 
> VALUES ( 'fred', 'bloggs', 45, '01773-987321');
I think PostgreSQl will wrap each of these INSERT statements into a
transaction, which will add a lot of overhead and slow the process.  I
find the following pattern to result in very fast loads with the psql
command line tool:
"""
ALTER TABLE  <table_name> DROP CONSTRAINT <constraint_name>;
DROP INDEX <index_name>

COPY <table_name> (<list of field names>)
FROM stdin;
<rows of tab delimited field data>
\.

CREATE INDEX <index_name> ON <table_name> (<field/fields>);
ALTER TABLE <table_name> ADD CONSTRAINT <constraint_name> FOREIGN KEY
(<field_name>) REFERENCES <other_table>(<other_field>);
"""
You can wrap parts/all of the above in BEGIN;/COMMIT; if you want them
done in a transaction.


> One thing to note is that due to caching issues you might find 
> it works better if you keep the individual loader files fairly small 
> - say 1000 or so records each. On other databases (DB2 for 
> example) very big data files seem to be faster, it just depends on 
> how the internal SQL engine works.
My SQL files are about 350MB, fwiw.  I haven't tried breaking them down
to smaller files because I haven't read in the PostgreSQL docs, or
forums, that doing so would be helpful.


>> Do have any idea about the C api for Postgresql and
>> some documentation to use it?
I've not used the C interface directly.  I think 'psql' will do what you
want:
man psql
or, just browse the docs online for your db version (psql --version)
<http://www.postgresql.org/docs/>
<http://www.postgresql.org/docs/8.1/interactive/sql-copy.html>


Best regards,

Eric.

From jfabiani at yolo.com  Fri Jan 26 01:39:14 2007
From: jfabiani at yolo.com (johnf)
Date: Thu, 25 Jan 2007 16:39:14 -0800
Subject: [Tutor]
	=?iso-8859-1?q?Optimal_solution_in_dealing_with_huge_data?=
	=?iso-8859-1?q?bases_in=09python?=
In-Reply-To: <45B93101.7060702@ericwalstad.com>
References: <768410.66504.qm@web38711.mail.mud.yahoo.com>
	<ep9usk$7bt$1@sea.gmane.org> <45B93101.7060702@ericwalstad.com>
Message-ID: <200701251639.14606.jfabiani@yolo.com>

On Thursday 25 January 2007 14:36, Eric Walstad wrote:
> Alan Gauld wrote:
> > "Shadab Sayani" <shadabsayani at yahoo.com> wrote
> >
> >> The data I need to deal with is  in 100s of GB.
> >> I am using postgresql backend and SQLALCHEMY ORM.
> >
> > All ORMs will introduce a significant performance hit.
> > If you really need high speed, and populating a 100G+ database
> > probably is included in that, then you should look at raw SQL.
> > In fact for really big data loads most databases provide a
> > C api that goes under the SQL, because even SQL is
> > relatively slow.
>
> I've had this experience, too.  I routinely load a couple million
> records from a tab delimited file into our PostgreSQL database with
> Python.  My import script:
>  1. iterates over the tab file a line/record at a time
>  2. does some data validation, some data manipulation
>  3. writes an SQL file with the massaged data
>  4. calls psql <dbname> -f <python-generated sql file>
>
> Generating the SQL file in python goes amazingly fast, considering the
> amount of validation and manipulation (normalizing addresses, generating
> hashes, etc) - about 1.5minutes/million records.
>
> The SQL it generates does the usual DB stuff including dropping indexes
> and constraints, COPY FROM stdin, regenerate indexes, replace
> constraints.  In my experience, psql is MUCH faster at these kinds of
> imports than even direct python interaction with psycopg.  Adding an ORM
> on top of the database connector (psycopg in my case) slows things down
> even more.
>
> As a rough metric, the import I described takes a little over 2 hours on
> my 2GHz/1GB laptop.
>
> Good luck,
>
> Eric.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

I agree - never thought of automating psql for copy...from action.  But it can 
be done.
-- 
John Fabiani

From carroll at tjc.com  Fri Jan 26 01:44:29 2007
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 25 Jan 2007 16:44:29 -0800 (PST)
Subject: [Tutor] Python re without string consumption
In-Reply-To: <888004.78133.qm@web54111.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0701251639010.26991-100000@violet.rahul.net>

On Thu, 25 Jan 2007, Jacob Abraham wrote:

>    I would like to thank you for the solution and
> the helper funtion that I have written is as follows. 

That's very similar to a solution I coded up for a friend, who was doing 
searches in genetic sequences, and had exactly the same problem  you did.  
My solution:

def myfindall(regex, seq):
   resultlist=[]
   pos=0

   while True:
      result = regex.search(seq, pos)
      if result is None:
         break
      resultlist.append(seq[result.start():result.end()])
      pos = result.start()+1
   return resultlist

Using it:

>>> rexp=re.compile("B.B")
>>> sequence="BABBEBIB"
>>> print myfindall(rexp,sequence)
['BAB', 'BEB', 'BIB']

> But I do hope that future versions of Python include a regular
> expression syntax to handle such cases...

My tongue-in-cheek recommendation was that re.findall be renamed to 
re.findmost.




From alan.gauld at btinternet.com  Fri Jan 26 01:46:38 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 26 Jan 2007 00:46:38 -0000
Subject: [Tutor] Optimal solution in dealing with huge databases inpython
References: <ep9usk$7bt$1@sea.gmane.org>	<889386.70898.qm@web38710.mail.mud.yahoo.com><epap36$dgb$1@sea.gmane.org>
	<45B935D9.2010001@ericwalstad.com>
Message-ID: <epbj1f$akb$1@sea.gmane.org>

"Eric Walstad" <eric at ericwalstad.com> wrote

>> Loadfile.sql would in turn contain lots of SQL commands like:
>>
>> INSERT into CUSTOMER
>> VALUES ( 'fred', 'bloggs', 45, '01773-987321');

> I think PostgreSQl will wrap each of these INSERT statements into a
> transaction, which will add a lot of overhead and slow the process. 
> I

Actually Oracle would do that too, but I didn't know about...

> COPY <table_name> (<list of field names>)
> FROM stdin;
> <rows of tab delimited field data>

...Because in Oracle there is a separate utility (from memory called
sqloader) that is specifically intended for large database loads so
you rarely use the technique I described, unless the schema is very
complex. (There is a COPY command in Oracle but its for copying data
from one database to another across a network...)

> My SQL files are about 350MB, fwiw.  I haven't tried breaking them 
> down
> to smaller files because I haven't read in the PostgreSQL docs, or
> forums, that doing so would be helpful.

In that case big files are probably best. The small file trick is
important if the database tries to cache tables in memory, or
if it creates large memory buffers for bulk writing to disk (via DMA).

Thanks for posting the COPY stuff I hadn't seen it before. Although
not being heavily into Postgres thats not exactly a shock! :-)

Alan G., 



From shadabsayani at yahoo.com  Fri Jan 26 03:15:41 2007
From: shadabsayani at yahoo.com (Shadab Sayani)
Date: Fri, 26 Jan 2007 02:15:41 +0000 (GMT)
Subject: [Tutor] Optimal solution in dealing with huge databases in
	python
In-Reply-To: <200701251020.36033.jfabiani@yolo.com>
Message-ID: <20070126021542.89865.qmail@web38715.mail.mud.yahoo.com>

Hi,
  
I got your point.But before inserting data I need to store it into  a file in a format supported by postgresql.Wont this operation incur a  performance hit as it includes writing to a file which is on disk?
  
  Thanks and Regards,
  Shadab.
  
johnf <jfabiani at yolo.com> wrote:  On Wednesday 24 January 2007 19:22, Shadab Sayani wrote:
> Hi,
>   I am working in a biodatabases project.The data I need to deal with is 
> in 100s of GB.I am using postgresql backend and SQLALCHEMY ORM.I need  to
> read the bio datafiles and parse them and then store them in  database.I am
> in the process of storing them. I used the session,flush concept in
> SQLALCHEMY.Initially I used to  flush every query immediately.Later I
> realised that the queries are  independent of each other and so started
> flushing 3-5 Lakh insert  queries at a time.This increased the response
> time.But the memory is  overflowing.Then I released not-in-use memory using
> del command in  python still there is no use as this del statement can only
> free part  of memory.I need to increase the above 3-5 lakh number to a much
> large  one to get a real time response.Other wise my estimation is it will 
> take 1 year to just insert the data into the database.From postgresql  side
> also I turned off WAL. Please suggest some viable solution to handle such
> enormous data from  python.Is there a better solution than SQL alchemy?Any
> solution that  speeds up my program is highly appreciated. Thanks and
> Regards,
>   Shadab.
>
>  Send instant messages to your online friends http://uk.messenger.yahoo.com

To tell the truth I know nothing about SQLALCHEMY ORM.  But I do know how to 
load large amounts of data into Postgres.  You use the 'copy ... from' 
command.  I once had 2 gigs of data and was surprised how fast it added the 
data.  Two things to remember:
1.  no indexes
2.  you have to format the data correctly - see Postgres DOC's

BTW I use psycopg for my connection
-- 
John Fabiani
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


 Send instant messages to your online friends http://uk.messenger.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070126/1c167d54/attachment-0001.htm 

From eike.welk at gmx.net  Fri Jan 26 04:06:05 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Fri, 26 Jan 2007 04:06:05 +0100
Subject: [Tutor] Optimal solution in dealing with huge databases in
	python
In-Reply-To: <768410.66504.qm@web38711.mail.mud.yahoo.com>
References: <768410.66504.qm@web38711.mail.mud.yahoo.com>
Message-ID: <200701260406.05915.eike.welk@gmx.net>

You could try Pytables:
http://www.pytables.org/moin

It is not a database, but a storage library for large amounts of data.

Regards,
Eike.


From eike.welk at gmx.net  Fri Jan 26 03:55:22 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Fri, 26 Jan 2007 03:55:22 +0100
Subject: [Tutor] Best IDE for Python
In-Reply-To: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
Message-ID: <200701260355.23093.eike.welk@gmx.net>

On Thursday 25 January 2007 04:12, Shadab Sayani wrote:
> Hi,
>   I am using vim editor to code my project in python.Is there a
> good  IDE  where in I type the name of the class object and then
> dot  then all the attributes of the object are displayed so on.I

I use Pydev, it is a plugin for the Eclipse IDE. Pydev does syntax 
completion, and also shows the documentation. It can run pylint and 
then cover your screen with red and yellow marks that show bad code. 

It is however too slow for large packages like numpy or scipy. After 
typing: 'from scipy inport *' it will pause for about half a minute 
when you type a dot. 

It is here:
http://pydev.sourceforge.net/

You must first install Eclipse (SDK) to use it:
http://www.eclipse.org/downloads/


Kind regards,
Eike.


From thian_seng at yahoo.com  Fri Jan 26 08:44:32 2007
From: thian_seng at yahoo.com (Wong Vincent)
Date: Thu, 25 Jan 2007 23:44:32 -0800 (PST)
Subject: [Tutor] how to pause or stop a running python script?
Message-ID: <304097.38777.qm@web32605.mail.mud.yahoo.com>

Hi, 
      If I use run a script which consist the following line:
  -->os.popen("python c:\\test.py") 
   
  Is it possible for me to interrupt the pause/stop the running of "test.py" halfway?
   
  If not,  can you please suggest a way. 
   
  Thanks....
   
  Best regards
  Vincent

 
---------------------------------
Need Mail bonding?
Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070125/bcd85292/attachment.html 

From pythontut at pusspaws.net  Fri Jan 26 09:03:18 2007
From: pythontut at pusspaws.net (Dave S)
Date: Fri, 26 Jan 2007 08:03:18 +0000
Subject: [Tutor] Best IDE for Python
In-Reply-To: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
Message-ID: <200701260803.18735.pythontut@pusspaws.net>

On Thursday 25 January 2007 03:12, Shadab Sayani wrote:
> Hi,
>   I am using vim editor to code my project in python.Is there a good  IDE 
> where in I type the name of the class object and then dot  then all the
> attributes of the object are displayed so on.I tried to  install IDLE but I
> have no idea how to install tkinter? Any help that enables me to use good
> IDE as soon as possible is appreciated Thanks and Regards,
>   Shadab
>

I use ...

http://www.die-offenbachs.de/detlev/eric.html


From zebra05 at gmail.com  Fri Jan 26 09:04:34 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Fri, 26 Jan 2007 10:04:34 +0200
Subject: [Tutor] Best IDE for Python
In-Reply-To: <57B026980605A64F9B23484C5659E32E5B1573@poccso.US.ad.atmel.com>
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
	<57B026980605A64F9B23484C5659E32E5B151E@poccso.US.ad.atmel.com>
	<200701250702.43188.tim@johnsons-web.com>
	<57B026980605A64F9B23484C5659E32E5B1573@poccso.US.ad.atmel.com>
Message-ID: <c7c6f3bc0701260004j6be1e0d5l2dd6492cedf51672@mail.gmail.com>

hi guys,

how useable is vim on Windows? i saw on its site that it was developed
primarily as a Unix tool.

i wish i could learn Unix. which distro do you think is good to learn? ive
been eyeing FreeBSD but ive got untouched Ubuntus.

thanks_up_ front()

"Shortash"

On 1/25/07, Mike Hansen <Mike.Hansen at atmel.com> wrote:
>
>
>
> >
> > > Activestate just released Komodo Edit and Komodo IDE. I
> > believe both do
> > > auto-completion that shows a list of possibilities. Komodo
> > Edit is free
> > > and Komodo IDE cost some $$.
> >
> > IMHO: If one programs in more than one programming language, the
> > ultimate would be an editor/IDE that can accommodate all with similar
> > functionality and behavior for all.
> >
> > MTCW
> > tim
>
> I agree. Depending on what I'm doing, I toggle between VIM and Komodo. I
> like that both can handle multiple languages.
>
> Mike
>
>
> -------------
>
>   NOTICE:  This e-mail transmission and any documents or files attached to
>   it contain information for the sole use of the above-identified
> individual or entity.
>
>   Its contents may be privileged, confidential, and exempt from disclosure
> under the law.
>   Any dissemination, distribution, or copying of this communication is
> strictly prohibited.
>
>   Please notify the sender immediately if you are not the intended
> recipient.
>
> FGNS
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070126/dfa63acb/attachment.htm 

From alan.gauld at btinternet.com  Fri Jan 26 09:30:06 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 26 Jan 2007 08:30:06 -0000
Subject: [Tutor] Best IDE for Python
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com><57B026980605A64F9B23484C5659E32E5B151E@poccso.US.ad.atmel.com><200701250702.43188.tim@johnsons-web.com><57B026980605A64F9B23484C5659E32E5B1573@poccso.US.ad.atmel.com>
	<c7c6f3bc0701260004j6be1e0d5l2dd6492cedf51672@mail.gmail.com>
Message-ID: <epce6g$are$1@sea.gmane.org>


"OkaMthembo" <zebra05 at gmail.com> wrote

> how useable is vim on Windows? 

Very usable.
I'm an old Unix user who used to use emacs primarily. 
But when I moved to Windoze I found I didn't like emacs 
as much so I moved to vim and I don't regret it.

> I saw on its site that it was developed
> primarily as a Unix tool.

Its an "Improved" version of the vi(sual) editor which 
is the standard editor on Unix. But there is nothing 
that is Unix specific about it. But if you have never 
used vi before there is a steep learning curve 
because vi was designed to be "easy to use" for 
experts not novices. ie it concentrates on delivering 
advanced features in minimal keystrokes rather than 
on making the basic features easy to remember. 
It also works best if you are a touch typist since 
the commands are arranged such that the most 
commonly used are the keys under your fingers 
in the home position - efficiency for experts again...

> i wish i could learn Unix. 

Try using cygwin as an intermediate step.
Even if yuou never make the move to unix you will 
have some power tools for Windows. If you do 
move to Unix you will feel at home after using cygwin.

> which distro do you think is good to learn? 

There is too much made of distros IMHO.
Once you have them installed they are all more or 
less the same. The same tools, the same GUIs.
Its only things like the package installers and 
some admin tools that are different.

Alan G.


From alan.gauld at btinternet.com  Fri Jan 26 09:40:40 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 26 Jan 2007 08:40:40 -0000
Subject: [Tutor] Optimal solution in dealing with huge databases inpython
References: <200701251020.36033.jfabiani@yolo.com>
	<20070126021542.89865.qmail@web38715.mail.mud.yahoo.com>
Message-ID: <epceqa$cmd$1@sea.gmane.org>


"Shadab Sayani" <shadabsayani at yahoo.com> wrote
>  
> I got your point.But before inserting data I need to store it 
> into  a file in a format supported by postgresql.Wont this 
> operation incur a  performance hit as it includes writing 
> to a file which is on disk?

Unless your data is already in a format the database 
understands you will have to reformat it before loading it.
There are basically two options:
1) read the unformatted data piece by piece, reformat 
it and load it to the database item by item.
2) read the unformatted data and write it to an 
intermediate file in a format supported by the 
database, then load the formatted data in bulk.

The second approach is nearly always faster than 
the first for large data sets. This is due to many things
including transactional overheads in the first approach,
caching issues, availability of bulk optimisations in 
the database itself, etc.

Writing to a flat file is much faster than writing to a 
database. Reformatting data is a complex business. 
Python is good at complex processing and writing 
to flat files. SQL is good at writing to databases but poor 
at complex processing. So use Python for its 
strengths and SQL for its strengths and you get 
optimal results.

HTH,

Alan G



From alan.gauld at btinternet.com  Fri Jan 26 09:49:52 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 26 Jan 2007 08:49:52 -0000
Subject: [Tutor] how to pause or stop a running python script?
References: <304097.38777.qm@web32605.mail.mud.yahoo.com>
Message-ID: <epcfbh$eb8$1@sea.gmane.org>


"Wong Vincent" <thian_seng at yahoo.com> wrote

>      If I use run a script which consist the following line:
>  -->os.popen("python c:\\test.py")
>
>  Is it possible for me to interrupt the pause/stop the running of 
> "test.py" halfway?

There is a recipe for this somewhere.

I don't think you can do it with vanilla popen because you
need the process ID. You can do some trickery using multiple
threads, or you can use lower level tools to launch the process
(spawn etc).

However you should look at the subprocess module which
supercedes popen. I strongly suspect that the Popen class
will have some options that help here, although I confess I
haven't actually tried it!

http://docs.python.org/lib/node533.html

Alan G. 



From thomas.s.mark at gmail.com  Fri Jan 26 11:07:39 2007
From: thomas.s.mark at gmail.com (Mark Thomas)
Date: Fri, 26 Jan 2007 05:07:39 -0500
Subject: [Tutor] Best IDE for Python
In-Reply-To: <c7c6f3bc0701260004j6be1e0d5l2dd6492cedf51672@mail.gmail.com>
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
	<57B026980605A64F9B23484C5659E32E5B151E@poccso.US.ad.atmel.com>
	<200701250702.43188.tim@johnsons-web.com>
	<57B026980605A64F9B23484C5659E32E5B1573@poccso.US.ad.atmel.com>
	<c7c6f3bc0701260004j6be1e0d5l2dd6492cedf51672@mail.gmail.com>
Message-ID: <7b9699030701260207j1dccba4ara4f5465b31f50167@mail.gmail.com>

On 1/26/07, OkaMthembo <zebra05 at gmail.com> wrote:
> how useable is vim on Windows?

Very! I've used Vim on Windows since the 5.3 version, it only gets
better. Like Alan said there is a learning curve, but once you've "got
it" there is no going back.

> i wish i could learn Unix. which distro do you think is good to learn?

If you just want to have the power of some Unix tools then take a look
at http://gnuwin32.sourceforge.net/ , they all run fine in the
standard Windows shell. If you want to try a Unix variant then find
one of the many "Live" CD's out there which you can use before you
slice up your disk. I'm a big fan of NetBSD but at the moment I'm
running OpenBSD 4.0 on my PIII laptop and it's very nice.

-- 
()  ascii ribbon campaign - against html e-mail
/\  www.asciiribbon.org   - against proprietary attachments

From kent37 at tds.net  Fri Jan 26 12:04:39 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 26 Jan 2007 06:04:39 -0500
Subject: [Tutor] how to pause or stop a running python script?
In-Reply-To: <304097.38777.qm@web32605.mail.mud.yahoo.com>
References: <304097.38777.qm@web32605.mail.mud.yahoo.com>
Message-ID: <45B9E047.3000709@tds.net>

Wong Vincent wrote:
> Hi,
>     If I use run a script which consist the following line:
> -->os.popen("python c:\\test.py")
>  
> Is it possible for me to interrupt the pause/stop the running of 
> "test.py" halfway?

Maybe this thread on c.l.python is helpful...
http://tinyurl.com/2bpvjo

Kent


From perlmunky at googlemail.com  Fri Jan 26 13:01:22 2007
From: perlmunky at googlemail.com (Dan Klose)
Date: Fri, 26 Jan 2007 12:01:22 +0000
Subject: [Tutor] issuing system commands
Message-ID: <b5facd7e0701260401u5480d4c9p554432fb8582ab2e@mail.gmail.com>

Hi All,

I am trying to break my nasty habit of doing EVERYTHING in perl and for this
task I figure python is one of the better options.

I would like to do several things:

1. take user input - this will be a password
2. use some sort of function that converts the unser input to * or the
typical '' no output of linux.
3. Take this input and use it in the os.system to issue an su command.

All I have so far is:

import os, sys
password = raw_input('Enter USER password: ')
print "you entered ", password
os.system("su perlmunky password")

I guess point three is more of a system dependent problem - As I work on a
mac and linux is there a better way of issuing these commands?  All I really
want to do is mount/unmount directories and shift / delete files.  I know
how to do this in perl, but as I said I really want to kick the habit.

Any help - pointers - advice would be most welcome.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070126/8c158557/attachment.htm 

From kent37 at tds.net  Fri Jan 26 13:30:27 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 26 Jan 2007 07:30:27 -0500
Subject: [Tutor] issuing system commands
In-Reply-To: <b5facd7e0701260401u5480d4c9p554432fb8582ab2e@mail.gmail.com>
References: <b5facd7e0701260401u5480d4c9p554432fb8582ab2e@mail.gmail.com>
Message-ID: <45B9F463.3090002@tds.net>

Dan Klose wrote:
> Hi All,
> 
> I am trying to break my nasty habit of doing EVERYTHING in perl and for 
> this task I figure python is one of the better options.
> 
> I would like to do several things:
> 
> 1. take user input - this will be a password
> 2. use some sort of function that converts the unser input to * or the 
> typical '' no output of linux.

See getpass.getpass()

> 3. Take this input and use it in the os.system to issue an su command.
> 
> All I have so far is:
> 
> import os, sys
> password = raw_input('Enter USER password: ')
> print "you entered ", password
> os.system("su perlmunky password")
> 
> I guess point three is more of a system dependent problem - As I work on 
> a mac and linux is there a better way of issuing these commands?  All I 
> really want to do is mount/unmount directories and shift / delete 
> files.  I know how to do this in perl, but as I said I really want to 
> kick the habit.

Not sure what you mean by mounting a directory but you can manipulate 
files and directories directly in Python. See the os and shutil modules.

Kent


From wesbrooks at gmail.com  Fri Jan 26 14:27:03 2007
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Fri, 26 Jan 2007 13:27:03 +0000
Subject: [Tutor] Inheriting Classes and __init__
Message-ID: <eec9f8ee0701260527g3b2dd734q60ee2b2b89e2eebb@mail.gmail.com>

Dear Users,

I would like a class to inherit the methods from wxVTKRenderWindow,
but to add a few lines of code to __init__ . I would prefer not to
copy the whole init method from the inherited class into the
inheriting class. What is the best approach for this? I guess that if
I have an init in the inheriting class it would overide the init in
the inherited class?

Yours faithfully,

Wesley Brooks

From kent37 at tds.net  Fri Jan 26 15:03:30 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 26 Jan 2007 09:03:30 -0500
Subject: [Tutor] Inheriting Classes and __init__
In-Reply-To: <eec9f8ee0701260527g3b2dd734q60ee2b2b89e2eebb@mail.gmail.com>
References: <eec9f8ee0701260527g3b2dd734q60ee2b2b89e2eebb@mail.gmail.com>
Message-ID: <45BA0A32.6050200@tds.net>

Wesley Brooks wrote:
> Dear Users,
> 
> I would like a class to inherit the methods from wxVTKRenderWindow,
> but to add a few lines of code to __init__ . I would prefer not to
> copy the whole init method from the inherited class into the
> inheriting class. What is the best approach for this? I guess that if
> I have an init in the inheriting class it would overide the init in
> the inherited class?

Yes, your __init__() will override the base class __init__(). To include 
the base class functionality, just call the base class __init__() from 
your __init__(). The syntax for this is a little different from the 
usual method call; in your __init__() include this call:
   wxVTKRenderWindow.__init__(self, args)

where args is whatever argument list you want to pass to the base class 
__init__().



From wesbrooks at gmail.com  Fri Jan 26 15:09:09 2007
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Fri, 26 Jan 2007 14:09:09 +0000
Subject: [Tutor] Inheriting Classes and __init__
In-Reply-To: <45BA0A32.6050200@tds.net>
References: <eec9f8ee0701260527g3b2dd734q60ee2b2b89e2eebb@mail.gmail.com>
	<45BA0A32.6050200@tds.net>
Message-ID: <eec9f8ee0701260609o2f060575xde977c8215decfa9@mail.gmail.com>

Thanks again, that is a great help.

Wesley Brooks

On 26/01/07, Kent Johnson <kent37 at tds.net> wrote:
> Wesley Brooks wrote:
> > Dear Users,
> >
> > I would like a class to inherit the methods from wxVTKRenderWindow,
> > but to add a few lines of code to __init__ . I would prefer not to
> > copy the whole init method from the inherited class into the
> > inheriting class. What is the best approach for this? I guess that if
> > I have an init in the inheriting class it would overide the init in
> > the inherited class?
>
> Yes, your __init__() will override the base class __init__(). To include
> the base class functionality, just call the base class __init__() from
> your __init__(). The syntax for this is a little different from the
> usual method call; in your __init__() include this call:
>    wxVTKRenderWindow.__init__(self, args)
>
> where args is whatever argument list you want to pass to the base class
> __init__().
>
>
>

From jfabiani at yolo.com  Fri Jan 26 15:20:18 2007
From: jfabiani at yolo.com (johnf)
Date: Fri, 26 Jan 2007 06:20:18 -0800
Subject: [Tutor] Optimal solution in dealing with huge databases inpython
In-Reply-To: <epceqa$cmd$1@sea.gmane.org>
References: <200701251020.36033.jfabiani@yolo.com>
	<20070126021542.89865.qmail@web38715.mail.mud.yahoo.com>
	<epceqa$cmd$1@sea.gmane.org>
Message-ID: <200701260620.18436.jfabiani@yolo.com>

On Friday 26 January 2007 00:40, Alan Gauld wrote:
> "Shadab Sayani" <shadabsayani at yahoo.com> wrote
>
> > I got your point.But before inserting data I need to store it
> > into  a file in a format supported by postgresql.Wont this
> > operation incur a  performance hit as it includes writing
> > to a file which is on disk?
>
> Unless your data is already in a format the database
> understands you will have to reformat it before loading it.
> There are basically two options:
> 1) read the unformatted data piece by piece, reformat
> it and load it to the database item by item.
> 2) read the unformatted data and write it to an
> intermediate file in a format supported by the
> database, then load the formatted data in bulk.
>
> The second approach is nearly always faster than
> the first for large data sets. This is due to many things
> including transactional overheads in the first approach,
> caching issues, availability of bulk optimisations in
> the database itself, etc.
>
> Writing to a flat file is much faster than writing to a
> database. Reformatting data is a complex business.
> Python is good at complex processing and writing
> to flat files. SQL is good at writing to databases but poor
> at complex processing. So use Python for its
> strengths and SQL for its strengths and you get
> optimal results.
>
> HTH,
>
> Alan G

This subject has come up several times in the psycopg mailing list.  The 
author of psycopg (Federico Di Gregorio) has suggested the best to handle 
this is as follows:
"When I'd have some more time I'll write a
class to do that without the need to create a temporary file. Now that I
think about it probably the best way would be to use two threads
writing/reading from a pipe, so that the postgresql one doesn't have to
wait for the other and data is always ready." 

In response too:
This is a copout and uses temporary files, but does the trick:

Usage is pretty simple:

orac = ora.cursor()
orac.execute('select * from gene.geneinfo')
orac.arraysize=100000
oraf = OracleFile2(orac)
pgc = pg.cursor()
pgc.copy_from(oraf,'loader.gene_info')


------------------------------------------------
class CursorFile(object):

? ? def __init__(self,cursor):
? ? ? ? self._cursor = cursor
? ? ? ? self._file = tempfile.TemporaryFile()
? ? ? ? self.write_file()

? ? def write_file(self):
? ? ? ? print 'fetching'
? ? ? ? dat = self._cursor.fetchmany()
? ? ? ? while len(dat)>0:
? ? ? ? ? ? print 'writing'
? ? ? ? ? ? for row in dat:
? ? ? ? ? ? ? ? self._file.writelines("\t".join(map(str,row)) + "\n")
? ? ? ? ? ? print "fetching"
? ? ? ? ? ? dat = self._cursor.fetchmany()
? ? ? ? print 'done writing'
? ? ? ? self._file.flush()
? ? ? ? self._file.seek(0)

? ? def read(self,size=-1):
? ? ? ? dat = self._file.read(size)
? ? ? ? return dat
? ? ? ? 
? ? def readline(self,size=-1):
? ? ? ? return self._file.readline(size)

I hope this helps
-- 
John Fabiani

From nephish at gmail.com  Fri Jan 26 16:30:03 2007
From: nephish at gmail.com (shawn bright)
Date: Fri, 26 Jan 2007 09:30:03 -0600
Subject: [Tutor] question about *args and functions
Message-ID: <384c93600701260730o3e4c6e12q69936c706bd13ba4@mail.gmail.com>

lo there all,

if i have a function that sometimes needs a value passed to it and sometimes
not, is this where i use *args ?

like this

def some_function(req_var, req_var2, un_req_var):
    do some stuff
    return value

how would i use this if sometimes i need to process un_req_var and sometimes
not ?

thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070126/4562cd34/attachment.htm 

From kent37 at tds.net  Fri Jan 26 16:40:46 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 26 Jan 2007 10:40:46 -0500
Subject: [Tutor] question about *args and functions
In-Reply-To: <384c93600701260730o3e4c6e12q69936c706bd13ba4@mail.gmail.com>
References: <384c93600701260730o3e4c6e12q69936c706bd13ba4@mail.gmail.com>
Message-ID: <45BA20FE.7050709@tds.net>

shawn bright wrote:
> lo there all,
> 
> if i have a function that sometimes needs a value passed to it and 
> sometimes not, is this where i use *args ?

No, use an optional argument.

> 
> like this
> 
> def some_function(req_var, req_var2, un_req_var):
>     do some stuff
>     return value
> 
> how would i use this if sometimes i need to process un_req_var and 
> sometimes not ?

def some_function(req_var, req_var2, un_req_var=None):
     do some stuff
     return value

Now the caller can write some_function(1, 2) or some_function(1, 2, 3). 
You can distinguish the two by checking for 'un_req_var is None'.

If None is a legitimate value for un_req_var then you need to pick some 
other sentinal value. If there is no built-in value that works, create 
your own:

missing = object()
def some_function(req_var, req_var2, un_req_var=missing):

Kent


From andreengels at gmail.com  Fri Jan 26 16:41:00 2007
From: andreengels at gmail.com (Andre Engels)
Date: Fri, 26 Jan 2007 16:41:00 +0100
Subject: [Tutor] question about *args and functions
In-Reply-To: <384c93600701260730o3e4c6e12q69936c706bd13ba4@mail.gmail.com>
References: <384c93600701260730o3e4c6e12q69936c706bd13ba4@mail.gmail.com>
Message-ID: <6faf39c90701260741l343637e4x892d62a5667d19b9@mail.gmail.com>

2007/1/26, shawn bright <nephish at gmail.com>:
>
> lo there all,
>
> if i have a function that sometimes needs a value passed to it and
> sometimes not, is this where i use *args ?


No. *args is used if there are arguments that could occur more than once.

like this
>
> def some_function(req_var, req_var2, un_req_var):
>     do some stuff
>     return value
>
> how would i use this if sometimes i need to process un_req_var and
> sometimes not ?
>

Use:
def some_function(req_var, req_var2, un_req_var = None):
    do some stuff
    return value

Now, the function can be called both with and without un_req_var, and if it
is called without un_req_var, within the function body un_req_var is
considered to be None.


-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070126/9adc05a4/attachment.htm 

From wesbrooks at gmail.com  Fri Jan 26 16:44:37 2007
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Fri, 26 Jan 2007 15:44:37 +0000
Subject: [Tutor] question about *args and functions
In-Reply-To: <384c93600701260730o3e4c6e12q69936c706bd13ba4@mail.gmail.com>
References: <384c93600701260730o3e4c6e12q69936c706bd13ba4@mail.gmail.com>
Message-ID: <eec9f8ee0701260744o456885f6ydaf275a24a90bf0c@mail.gmail.com>

Greetings,

You could default it to None and check in your script to see if it has changed.
def some_function(req_var, req_var2, un_req_var=None):
   if un_req_var != None:
       dosomething
   else:
       dosomethingelse

Wesley Brooks.

On 26/01/07, shawn bright <nephish at gmail.com> wrote:
> lo there all,
>
> if i have a function that sometimes needs a value passed to it and sometimes
> not, is this where i use *args ?
>
> like this
>
> def some_function(req_var, req_var2, un_req_var):
>     do some stuff
>     return value
>
> how would i use this if sometimes i need to process un_req_var and sometimes
> not ?
>
> thanks
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>

From nephish at gmail.com  Fri Jan 26 16:52:20 2007
From: nephish at gmail.com (shawn bright)
Date: Fri, 26 Jan 2007 09:52:20 -0600
Subject: [Tutor] question about *args and functions
In-Reply-To: <eec9f8ee0701260744o456885f6ydaf275a24a90bf0c@mail.gmail.com>
References: <384c93600701260730o3e4c6e12q69936c706bd13ba4@mail.gmail.com>
	<eec9f8ee0701260744o456885f6ydaf275a24a90bf0c@mail.gmail.com>
Message-ID: <384c93600701260752u3f30767fq878fb35ea5875f68@mail.gmail.com>

Great, gents, thanks.

tried it out and is working fine, this will clean up a lot of stuff for me.
thanks for your help !

shawn

On 1/26/07, Wesley Brooks <wesbrooks at gmail.com> wrote:
>
> Greetings,
>
> You could default it to None and check in your script to see if it has
> changed.
> def some_function(req_var, req_var2, un_req_var=None):
>    if un_req_var != None:
>        dosomething
>    else:
>        dosomethingelse
>
> Wesley Brooks.
>
> On 26/01/07, shawn bright <nephish at gmail.com> wrote:
> > lo there all,
> >
> > if i have a function that sometimes needs a value passed to it and
> sometimes
> > not, is this where i use *args ?
> >
> > like this
> >
> > def some_function(req_var, req_var2, un_req_var):
> >     do some stuff
> >     return value
> >
> > how would i use this if sometimes i need to process un_req_var and
> sometimes
> > not ?
> >
> > thanks
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070126/fd3dbe97/attachment.htm 

From rdm at rcblue.com  Fri Jan 26 21:16:01 2007
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 26 Jan 2007 12:16:01 -0800
Subject: [Tutor] How to use diff.py?
Message-ID: <7.0.1.0.2.20070126120656.01100dc8@rcblue.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070126/21c483a1/attachment.html 

From hugonz-lists at h-lab.net  Thu Jan 25 23:24:41 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Thu, 25 Jan 2007 16:24:41 -0600
Subject: [Tutor] Python code to connect using PPPoE
In-Reply-To: <20070124134939.119611669D@mail.accesstel.co.za>
References: <20070124134939.119611669D@mail.accesstel.co.za>
Message-ID: <45B92E29.3070704@h-lab.net>

Hi Johan,

PPPoE is both in the Linux Kernel (for the low level work) and as some 
executables and scripts.

It fou want to establish a connection from a Python script (E.G. ehn the 
computer has no internet access and you need it) The best way would be 
to call the appropriate utilities, and parse their output. This means 
calling adsl-connect, ficonfig, and the like, maybe parsing the output 
from ifconfig. Take a look at the module named subprocess to do that.

Reimplementing these utilities in Python is some work, but doable. 
Implementing PPPoE in Python, reading the device files and all that... 
well... it's almost nonsense. For this, you have to use the kernel.

Johan Geldenhuys wrote:
> Kent,
> I want to establish the connection with Python. I think in Linux you can use
> a PPPoE package to make life easier, but I don't want to use the Kernel to
> do that.
> 
> Johan 
> 


From hugonz at h-lab.net  Fri Jan 26 22:55:22 2007
From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Fri, 26 Jan 2007 15:55:22 -0600
Subject: [Tutor] Cause-Effect, Isikawa, fishbone diagram
In-Reply-To: <OF29022A1B.C511615C-ONC125726D.00719F2F-C125726D.0074A255@velux.com>
References: <OF29022A1B.C511615C-ONC125726D.00719F2F-C125726D.0074A255@velux.com>
Message-ID: <45BA78CA.4090800@h-lab.net>

Hi J?nos,

Reportlab is a very complete PDF library, but it is not very simple, and 
does not have shortcuts for what you need to do. You'd have to come up 
with the code to get a fishbone diagram from the textfile. But it does 
help you with the PDF.

There are some graphing packages, but they're most for scientific 
graphs. Like http://matplotlib.sourceforge.net/

Hope that helps,

Hugo

J?nos Juh?sz wrote:
> Dear All,
> 
> does someone know any python based solution to draw a 
> cause-effect diagram into PDF from a simple textfile ?
> 
> It is also called a Fishbone Diagram, because of its shape, 
> or an Ishikawa Chart, after its originator, Kaoru Ishikawa
> I feel, it can be converted from a structure like this.
> 
> Title
> Effect
>   Cause1
>     Secundary
>       Tertiary
>       Tertiary
>   Cause2
>     Secundary
>       Tertiary
>   Cause3
>     Secundary
>       Tertiary
> 
> It is probably a simple function.
> 
> 
> 
> Yours sincerely,
> ______________________________
> Janos Juhasz
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From nswitanek at stanford.edu  Sat Jan 27 02:48:21 2007
From: nswitanek at stanford.edu (Switanek, Nick)
Date: Fri, 26 Jan 2007 17:48:21 -0800
Subject: [Tutor] converting tab-delimited text files to csv
Message-ID: <21EB45BA6A0A4844B97D46A7721CFDF202DE399B@gsb-exchmb02.stanford.edu>

I have a long tab-delimited text file that I'd like to convert into csv
format so I can read it into a statistics package. 

I've been using Excel to do the format conversion up till now, but now I
have more rows than Excel can handle, and would like to avoid going
through Excel if possible. 

 

I've found the csv module but am confused by its documentation, as I am
with the few threads on the subject generally. 

 

Here's what I've tried to do:

 

import csv

inputFileList = file('input.txt').readlines()

writer = csv.writer(file('output.csv', 'wb'))

writer.writerows(inputFileList)

del writer

 

When I try to open the resulting file in Excel (I've used a sample file
of 100 rows), however, it appears that I'm delimiting every character,
as each character has its own column. The rows in the original text file
are combinations of integers and character strings (some of which
include double quotes). Do I need to alter the 'dialect' or what?

 

Many thanks in advance for your help!

 

Nick

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070126/4a5e019c/attachment.htm 

From rabidpoobear at gmail.com  Sat Jan 27 04:01:56 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 26 Jan 2007 21:01:56 -0600
Subject: [Tutor] converting tab-delimited text files to csv
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF202DE399B@gsb-exchmb02.stanford.edu>
References: <21EB45BA6A0A4844B97D46A7721CFDF202DE399B@gsb-exchmb02.stanford.edu>
Message-ID: <45BAC0A4.3040106@gmail.com>

Switanek, Nick wrote:
>
> I have a long tab-delimited text file that I?d like to convert into 
> csv format so I can read it into a statistics package.
>
> I?ve been using Excel to do the format conversion up till now, but now 
> I have more rows than Excel can handle, and would like to avoid going 
> through Excel if possible.
>
> I?ve found the csv module but am confused by its documentation, as I 
> am with the few threads on the subject generally.
>
> Here?s what I?ve tried to do:
>
> import csv
>
> inputFileList = file(?input.txt?).readlines()
>
> writer = csv.writer(file(?output.csv', 'wb'))
>
> writer.writerows(inputFileList)
>
> del writer
>
> When I try to open the resulting file in Excel (I?ve used a sample 
> file of 100 rows), however, it appears that I?m delimiting every 
> character, as each character has its own column. The rows in the 
> original text file are combinations of integers and character strings 
> (some of which include double quotes). Do I need to alter the 
> ?dialect? or what?
>
> Many thanks in advance for your help!
>
csv is comma-separated values, right?
you should be able to just do a string replace of tabs -> commas on each 
line in the new file...
or is the csv format more complicated than that?
-Luke

From kent37 at tds.net  Sat Jan 27 04:39:17 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 26 Jan 2007 22:39:17 -0500
Subject: [Tutor] converting tab-delimited text files to csv
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF202DE399B@gsb-exchmb02.stanford.edu>
References: <21EB45BA6A0A4844B97D46A7721CFDF202DE399B@gsb-exchmb02.stanford.edu>
Message-ID: <45BAC965.4070704@tds.net>

Switanek, Nick wrote:
> I have a long tab-delimited text file that I?d like to convert into csv 
> format so I can read it into a statistics package.

Are you sure the statistics package can't read tab-delimited data 
directly? For example in R you can use read.delim().

> Here?s what I?ve tried to do:
> 
>  
> 
> import csv
> 
> inputFileList = file(?input.txt?).readlines()
> 
> writer = csv.writer(file(?output.csv', 'wb'))
> 
> writer.writerows(inputFileList)
> 
> del writer
> 
> When I try to open the resulting file in Excel (I?ve used a sample file 
> of 100 rows), however, it appears that I?m delimiting every character, 
> as each character has its own column. The rows in the original text file 
> are combinations of integers and character strings (some of which 
> include double quotes). Do I need to alter the ?dialect? or what?

The argument to writerows() should be a list of sequences. You are 
passing a list of strings, so the strings are interpreted as sequences 
of characters.

You need to divide the input rows at the tabs. You will also want to 
strip the trailing newlines off the input lines. Try this:

inputFileList = [ line.rstrip('\n').split('\t') for line in 
open('input.txt') ]

Kent


From kent37 at tds.net  Sat Jan 27 04:40:24 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 26 Jan 2007 22:40:24 -0500
Subject: [Tutor] converting tab-delimited text files to csv
In-Reply-To: <45BAC0A4.3040106@gmail.com>
References: <21EB45BA6A0A4844B97D46A7721CFDF202DE399B@gsb-exchmb02.stanford.edu>
	<45BAC0A4.3040106@gmail.com>
Message-ID: <45BAC9A8.4060204@tds.net>

Luke Paireepinart wrote:
> csv is comma-separated values, right?
> you should be able to just do a string replace of tabs -> commas on each 
> line in the new file...
> or is the csv format more complicated than that?

Yes, it is more complicated than that because the data itself may 
contain commas.

Kent


From rdm at rcblue.com  Sat Jan 27 11:38:40 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 27 Jan 2007 02:38:40 -0800
Subject: [Tutor] How to use diff.py?
In-Reply-To: <7.0.1.0.2.20070126120656.01100dc8@rcblue.com>
References: <7.0.1.0.2.20070126120656.01100dc8@rcblue.com>
Message-ID: <7.0.1.0.2.20070127023605.076d2e78@rcblue.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070127/74efe5ba/attachment.htm 

From rdm at rcblue.com  Sat Jan 27 11:58:38 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 27 Jan 2007 02:58:38 -0800
Subject: [Tutor] Best IDE for Python
In-Reply-To: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
Message-ID: <7.0.1.0.2.20070127025526.076d4ea8@rcblue.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070127/071d3907/attachment.html 

From kent37 at tds.net  Sat Jan 27 13:54:29 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 27 Jan 2007 07:54:29 -0500
Subject: [Tutor] How to use diff.py?
In-Reply-To: <7.0.1.0.2.20070127023605.076d2e78@rcblue.com>
References: <7.0.1.0.2.20070126120656.01100dc8@rcblue.com>
	<7.0.1.0.2.20070127023605.076d2e78@rcblue.com>
Message-ID: <45BB4B85.6090802@tds.net>

Dick Moores wrote:
> At 12:16 PM 1/26/2007, you wrote:
>> I've found diff.py in Python25\Tools\Scripts. But I don't see how to 
>> use it to find the differences between 2 files, say file1.txt and 
>> file2.txt. I was hoping it would work like unix's diff, but could 
>> someone explain?
> 
> Here's one way: http://tinyurl.com/2lsleq

Did that answer your question?

You can run diff.py from the command line, e.g.
py c:/python25/tools/scripts/diff.py -c FindE3Audio.py FindE3NoAudio.py

Here is an example of using difflib:
http://personalpages.tds.net/~kent37/blog/arch_m1_2004_06.html#e47

Kent


From vikramumanathshenoy at gmail.com  Sat Jan 27 15:40:31 2007
From: vikramumanathshenoy at gmail.com (Vikram Shenoy)
Date: Sat, 27 Jan 2007 20:10:31 +0530
Subject: [Tutor] Needed Python 2.5 quick reference.
Message-ID: <1ac2c0030701270640w13376fck7c7e5af95fe8d281@mail.gmail.com>

Hi All,

The link for the python 2.5 quick reference (
http://rgruet.free.fr/PQR25/PQR2.5.html) doesn't seem to be working. Can
anybody point me to any mirror link or share the document if you have
downloaded it already ? A4 PDF version will be great.

Regards,
Vikram U Shenoy.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070127/d7268ccf/attachment.htm 

From nephish at gmail.com  Sat Jan 27 17:47:37 2007
From: nephish at gmail.com (shawn bright)
Date: Sat, 27 Jan 2007 10:47:37 -0600
Subject: [Tutor] Best IDE for Python
In-Reply-To: <7.0.1.0.2.20070127025526.076d4ea8@rcblue.com>
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
	<7.0.1.0.2.20070127025526.076d4ea8@rcblue.com>
Message-ID: <384c93600701270847q42a5c4a9wfe418ae04aa3cde3@mail.gmail.com>

i think pydev ( an eclipse plugin ) can too.
shawn

On 1/27/07, Dick Moores <rdm at rcblue.com> wrote:
>
>  At 07:12 PM 1/24/2007, Shadab Sayani wrote:
>
> Hi,
> I am using vim editor to code my project in python.Is there a good IDE
> where in I type the name of the class object and then dot then all the
> attributes of the object are displayed so on.
>
>
> Ulipad can do this.
>
> Dick Moores
>
>  UliPad <<The Python Editor>>: http://wiki.woodpecker.org.cn/moin/UliPad
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070127/41e1e97f/attachment.html 

From sigzero at gmail.com  Sat Jan 27 18:40:41 2007
From: sigzero at gmail.com (Robert Hicks)
Date: Sat, 27 Jan 2007 12:40:41 -0500
Subject: [Tutor] Needed Python 2.5 quick reference.
In-Reply-To: <1ac2c0030701270640w13376fck7c7e5af95fe8d281@mail.gmail.com>
References: <1ac2c0030701270640w13376fck7c7e5af95fe8d281@mail.gmail.com>
Message-ID: <epg2qp$ju4$1@sea.gmane.org>

Vikram Shenoy wrote:
> Hi All,
> 
> The link for the python 2.5 quick reference 
> (http://rgruet.free.fr/PQR25/PQR2.5.html) doesn't seem to be working. 
> Can anybody point me to any mirror link or share the document if you 
> have downloaded it already ? A4 PDF version will be great.
> 
> Regards,
> Vikram U Shenoy.
> 

I just opened a few of the pdf's from here without a problem:

http://rgruet.free.fr/#QuickRef

Robert


From rdm at rcblue.com  Sun Jan 28 17:23:00 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 28 Jan 2007 08:23:00 -0800
Subject: [Tutor] How to use diff.py?
In-Reply-To: <45BB4B85.6090802@tds.net>
References: <7.0.1.0.2.20070126120656.01100dc8@rcblue.com>
	<7.0.1.0.2.20070127023605.076d2e78@rcblue.com>
	<45BB4B85.6090802@tds.net>
Message-ID: <7.0.1.0.2.20070128082030.03699250@rcblue.com>

At 04:54 AM 1/27/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>At 12:16 PM 1/26/2007, you wrote:
>>>I've found diff.py in Python25\Tools\Scripts. But I don't see how 
>>>to use it to find the differences between 2 files, say file1.txt 
>>>and file2.txt. I was hoping it would work like unix's diff, but 
>>>could someone explain?
>>Here's one way: http://tinyurl.com/2lsleq
>
>Did that answer your question?

Yes. I found I like the -m option.

>You can run diff.py from the command line, e.g.
>py c:/python25/tools/scripts/diff.py -c FindE3Audio.py FindE3NoAudio.py

or py c:/python25/tools/scripts/diff.py -m FindE3Audio.py 
FindE3NoAudio.py > Audio.htm

Thanks, Kent.

Dick



From nephish at gmail.com  Sun Jan 28 20:39:43 2007
From: nephish at gmail.com (shawn bright)
Date: Sun, 28 Jan 2007 13:39:43 -0600
Subject: [Tutor] question about a list of lists
Message-ID: <384c93600701281139xf74fdbbxbbf2750fab7c224d@mail.gmail.com>

lo there all.

i have a list of lists that i want to build, only if an item is not in the
list already.

kinda like this
new_list = []
for item in lists: # item will look something like [var1, var2, var3]
    if item[0] in new_list ( only the first element of each list ) like
new_list[0][0]

basicly, i want to know if item[0]   is one of the items[0] in my new_list

whats a good pythonic way to do this? i mean, i have a couple of way to do
this, but they are ugly.

shawn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070128/d1aa7704/attachment.htm 

From thian_seng at yahoo.com  Sun Jan 28 20:11:47 2007
From: thian_seng at yahoo.com (Wong Vincent)
Date: Sun, 28 Jan 2007 11:11:47 -0800 (PST)
Subject: [Tutor] Does Python have any callback function?
Message-ID: <102441.35019.qm@web32612.mail.mud.yahoo.com>

Dear tutor,
     My current application has 2 python scripts running in parallel, say script A and B. 
  script A: GUI
  script B: data processing.
   
  A will invoke B to run. If I would like B to update processing status to A(so that user is able to see realtime status), how can I do it?
   
  Appreciate your guidance...
   
  Best regards
  Vincent

 
---------------------------------
Don't be flakey. Get Yahoo! Mail for Mobile and 
always stay connected to friends.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070128/8699b499/attachment.html 

From clsdaniel at gmail.com  Sun Jan 28 22:22:32 2007
From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela)
Date: Sun, 28 Jan 2007 14:22:32 -0700
Subject: [Tutor] Does Python have any callback function?
In-Reply-To: <102441.35019.qm@web32612.mail.mud.yahoo.com>
References: <102441.35019.qm@web32612.mail.mud.yahoo.com>
Message-ID: <4fae7dfa0701281322g272d8d46h853c1de85b221cc0@mail.gmail.com>

That depends very much on how you are running both scripts in
parallel, if you are using Threads or process.

If using threads you can share a variable or object between the
scripts read it on A to check for updates and lock and update on B
(using semaphores for examples), there is an Event object on the
threading module but i have never used it.

If you are using process (via system call or something like that, not
threading) then you need an IPC mechanism, like sockets, signals or
RPC.

There is many ways to approach this problem really, these are just my
2 cents :-).

Good luck.

On 1/28/07, Wong Vincent <thian_seng at yahoo.com> wrote:
> Dear tutor,
>    My current application has 2 python scripts running in parallel, say
> script A and B.
> script A: GUI
> script B: data processing.
>
> A will invoke B to run. If I would like B to update processing status to
> A(so that user is able to see realtime status), how can I do it?
>
> Appreciate your guidance...
>
> Best regards
> Vincent
>
>  ________________________________
> Don't be flakey. Get Yahoo! Mail for Mobile and
> always stay connected to friends.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>

From newtopython at gmail.com  Sun Jan 28 23:57:04 2007
From: newtopython at gmail.com (Python Freak)
Date: Sun, 28 Jan 2007 17:57:04 -0500
Subject: [Tutor] Help Please
In-Reply-To: <e24ab5e80701281445j4e530836vb4dd5328dbd918a8@mail.gmail.com>
References: <e24ab5e80701281445j4e530836vb4dd5328dbd918a8@mail.gmail.com>
Message-ID: <e24ab5e80701281457j2982e651la6da6cb48bf1e6be@mail.gmail.com>

Hi,

This may be too elementary for most of you, but could you please help me
with the following question? I would like to use comprehensive lists and
lists of lists. Where do I start?

Question:

Consider a digraph with 10 vertices, labeled 1 through 10. You are given the
following adjacency list representation, where we first list the vertices
adjacent to vertex 1, and so on.

1*; *2; 2*; *3; 3*; *4; 4*; *5; 5*; *6; 6*; *7; 7*; *8; 8*; *9; 9*; *10; 10.


a) Write code to turn the adjacency list into an incidence list and an an
adjacency matrix.

b) Write code to turn the incidence list into an adjacency matrix.

Hint: You may find it useful to note that one incidence list representation
is (1*; *1), (2*; *2), (3*; *3), (4*; *4), (5*; *5),(6*; *6), (7*; *7), (8*;
*8), (9*; *9), (10*; *10), (1*; *2), (2*; *3), (3*; *4), (4*; *5), (5*; *6),
(6*; *7), (7*; *8), (8*; *9), (9*; *10).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070128/a887a1a9/attachment.html 

From dyoo at hkn.eecs.berkeley.edu  Mon Jan 29 00:48:31 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Jan 2007 15:48:31 -0800 (PST)
Subject: [Tutor] Help Please
In-Reply-To: <e24ab5e80701281457j2982e651la6da6cb48bf1e6be@mail.gmail.com>
References: <e24ab5e80701281445j4e530836vb4dd5328dbd918a8@mail.gmail.com>
	<e24ab5e80701281457j2982e651la6da6cb48bf1e6be@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0701281542070.31157@hkn.eecs.berkeley.edu>



> This may be too elementary for most of you, but could you please help me
> with the following question?

This is almost certainly a homework problem.  We are very restricted in 
what we can do to help.  See:

     http://www.catb.org/~esr/faqs/smart-questions.html#homework


> I would like to use comprehensive lists and lists of lists. Where do I 
> start?


These are basic list manipulation concepts.  See any Python tutorial that 
talk about lists.  For example:

     http://www.ibiblio.org/obp/thinkCSpy/chap08.html


Other than refering you to tutorials, I don't think I can do much else 
here.  Good luck.

From anilmrn at yahoo.com  Mon Jan 29 01:23:54 2007
From: anilmrn at yahoo.com (anil maran)
Date: Sun, 28 Jan 2007 16:23:54 -0800 (PST)
Subject: [Tutor] Best IDE for Python
In-Reply-To: <384c93600701270847q42a5c4a9wfe418ae04aa3cde3@mail.gmail.com>
Message-ID: <20070129002354.94546.qmail@web55207.mail.re4.yahoo.com>

Vim and emacs are equally good
shawn bright <nephish at gmail.com> wrote: i think pydev ( an eclipse plugin ) can too.
shawn

On 1/27/07, Dick Moores <rdm at rcblue.com> wrote:   At 07:12 PM 1/24/2007, Shadab Sayani wrote:
 Hi,
 I am using vim editor to code my project in python.Is there a good IDE  where in I type the name of the class object and then dot then all the attributes of the object are displayed so on.
 Ulipad can do this.

 Dick Moores

  UliPad <<The Python Editor>>:  http://wiki.woodpecker.org.cn/moin/UliPad 

    
_______________________________________________
Tutor maillist  -  Tutor at python.org
 http://mail.python.org/mailman/listinfo/tutor




 _______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


 
---------------------------------
Any questions?  Get answers on any topic at Yahoo! Answers. Try it now.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070128/61a1a9c9/attachment.html 

From alan.gauld at btinternet.com  Mon Jan 29 01:57:27 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 29 Jan 2007 00:57:27 -0000
Subject: [Tutor] Does Python have any callback function?
References: <102441.35019.qm@web32612.mail.mud.yahoo.com>
Message-ID: <epjgpq$mhq$1@sea.gmane.org>

"Wong Vincent" <thian_seng at yahoo.com> wrote

> My current application has 2 python scripts running in parallel, say 
> script A and B.
> script A: GUI
> script B: data processing.

OK, Thats a slightly unusual way to do things unless the data
processing is acting as a server for multiple clients. Normally
we would write the data processing as a module that exposed
some functions (or classes) that are called from the GUI and
the GUI then updates the interface with the result.

But assuming you must use two separate scripts running as
two processes then you can still get them to interwork. Take
a look at my tutorial under the topic inter-process-communication
for how to use pipes. If it is a multi-client server (or iof the 
serrver
is on another machine from the GUI) then sockets may be more
appropriate (I haven't gotten round to finishing that topic yet! :-)

>  A will invoke B to run. If I would like B to update processing
> status to A

But since you say A invokles B I suspect pipes will be fine.
But equally rewriting B as a module will be even better.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Mon Jan 29 01:59:39 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 29 Jan 2007 00:59:39 -0000
Subject: [Tutor] question about a list of lists
References: <384c93600701281139xf74fdbbxbbf2750fab7c224d@mail.gmail.com>
Message-ID: <epjgtu$mq0$1@sea.gmane.org>


"shawn bright" <nephish at gmail.com> wrote

> new_list = []
> for item in lists: # item will look something like [var1, var2, 
> var3]
>    if item[0] in new_list

> basicly, i want to know if item[0]   is one of the items[0] in my 
> new_list

Your pseudo code is pretty much exactly right.
What more are you looking for?

Alan G. 



From alan.gauld at btinternet.com  Mon Jan 29 02:04:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 29 Jan 2007 01:04:05 -0000
Subject: [Tutor] Help Please
References: <e24ab5e80701281445j4e530836vb4dd5328dbd918a8@mail.gmail.com>
	<e24ab5e80701281457j2982e651la6da6cb48bf1e6be@mail.gmail.com>
Message-ID: <epjh68$ng2$1@sea.gmane.org>


"Python Freak" <newtopython at gmail.com> wrote

> This may be too elementary for most of you, but could you please 
> help me
> with the following question? I would like to use comprehensive lists 
> and
> lists of lists. Where do I start?

Assuming you mean list comprehensions and lists of
lists then most web tutorials (including mine) should
include those topics

What exactly don you not understand? The more specific the question
the more specific will be the answer.


> Question:
>
> Consider a digraph with 10 vertices, labeled 1 through 10. You are 
> given the
> following adjacency list representation, where we first list the 
> vertices
> adjacent to vertex 1, and so on.
>
> 1*; *2; 2*; *3; 3*; *4; 4*; *5; 5*; *6; 6*; *7; 7*; *8; 8*; *9; 9*; 
> *10; 10.

Thats pretty specific but looks like a homework.
We won't do your homework for you but we will help you with
specific bits if you get stuck. But you need to show us that
you are  making a fair attempt yourself.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From keosophon at khmeros.info  Mon Jan 29 02:45:39 2007
From: keosophon at khmeros.info (Keo Sophon)
Date: Mon, 29 Jan 2007 08:45:39 +0700
Subject: [Tutor] Internal Python memory dump
Message-ID: <200701290845.39553.keosophon@khmeros.info>

Hi,

Does anyone know where I can find documents of Internal python memory dump?

thanks,
Phon

From newtopython at gmail.com  Sun Jan 28 23:54:58 2007
From: newtopython at gmail.com (Python Freak)
Date: Sun, 28 Jan 2007 17:54:58 -0500
Subject: [Tutor] Help Please
In-Reply-To: <e24ab5e80701281445j4e530836vb4dd5328dbd918a8@mail.gmail.com>
References: <e24ab5e80701281445j4e530836vb4dd5328dbd918a8@mail.gmail.com>
Message-ID: <e24ab5e80701281454i4b12fe69yc85e08b73b3b4975@mail.gmail.com>

Hi,

This may be too elementary for most of you, but could you please help me
with the following question? I would like to use comprehensive lists and
lists of lists. Where do I start?

Question:

Consider a digraph with 10 vertices, labeled 1 through 10. You are given the
following adjacency list representation, where we first list the vertices
adjacent to vertex 1, and so on.

1*; *2; 2*; *3; 3*; *4; 4*; *5; 5*; *6; 6*; *7; 7*; *8; 8*; *9; 9*; *10; 10.


a) Write code to turn the adjacency list into an incidence list and an an
adjacency matrix.

b) Write code to turn the incidence list into an adjacency matrix.

Hint: You may find it useful to note that one incidence list representation
is (1*; *1), (2*; *2), (3*; *3), (4*; *4), (5*; *5),(6*; *6), (7*; *7), (8*;
*8), (9*; *9), (10*; *10), (1*; *2), (2*; *3), (3*; *4), (4*; *5), (5*; *6),
(6*; *7), (7*; *8), (8*; *9), (9*; *10).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070128/409850af/attachment.htm 

From kent37 at tds.net  Mon Jan 29 04:19:38 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 28 Jan 2007 22:19:38 -0500
Subject: [Tutor] question about a list of lists
In-Reply-To: <384c93600701281139xf74fdbbxbbf2750fab7c224d@mail.gmail.com>
References: <384c93600701281139xf74fdbbxbbf2750fab7c224d@mail.gmail.com>
Message-ID: <45BD67CA.60405@tds.net>

shawn bright wrote:
> lo there all.
> 
> i have a list of lists that i want to build, only if an item is not in 
> the list already.
> 
> kinda like this
> new_list = []
> for item in lists: # item will look something like [var1, var2, var3]
>     if item[0] in new_list ( only the first element of each list ) like 
> new_list[0][0]
> 
> basicly, i want to know if item[0]   is one of the items[0] in my new_list
> 
> whats a good pythonic way to do this? i mean, i have a couple of way to 
> do this, but they are ugly.

One way to do this is to keep a helper set that contains the first 
elements of each list. Something like
new_list = []
firsts = set()
for item in lists:
   if item[0] not in firsts:
     new_list.append(item)
     firsts.add(item[0]

If you don't care about the order of the result, and if two lists have 
duplicate first items you are happy to use the first, then you could use 
a dict mapping first item to list:

new_list = dict((item[0], item) for item in lists).values()

Kent


From sanelson at gmail.com  Mon Jan 29 13:29:32 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Mon, 29 Jan 2007 12:29:32 +0000
Subject: [Tutor] Variable Swap
Message-ID: <b6131fdc0701290429u378daad9g1f3dcdae335a3cc6@mail.gmail.com>

Hello,

I understand the use of xor to do a variable swap without a temporary variable:

>>> x=2
>>> y=3
>>> y=x^y
>>> x=x^y
>>> y=x^y
>>> x
3
>>> y
2


However, why do I see this?

>>> y=x^y
>>> y
1

S.

From kent37 at tds.net  Mon Jan 29 13:51:14 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 29 Jan 2007 07:51:14 -0500
Subject: [Tutor] Variable Swap
In-Reply-To: <b6131fdc0701290429u378daad9g1f3dcdae335a3cc6@mail.gmail.com>
References: <b6131fdc0701290429u378daad9g1f3dcdae335a3cc6@mail.gmail.com>
Message-ID: <45BDEDC2.4040405@tds.net>

Steve Nelson wrote:
> Hello,
> 
> I understand the use of xor to do a variable swap without a temporary variable:
> 
>>>> x=2
>>>> y=3
>>>> y=x^y
>>>> x=x^y
>>>> y=x^y
>>>> x
> 3
>>>> y
> 2
> 
> 
> However, why do I see this?
> 
>>>> y=x^y
>>>> y
> 1

Because 2 ^ 3 == 1, right? Are you sure you understand what xor does? It 
is a bitwise exclusive or:
http://en.wikipedia.org/wiki/Xor#Bitwise_operation

By the way in Python you can write
x, y = y, x
as a readable alternative.

Kent


From tinoloc at gmail.com  Mon Jan 29 15:27:55 2007
From: tinoloc at gmail.com (Tino Dai)
Date: Mon, 29 Jan 2007 09:27:55 -0500
Subject: [Tutor] Advanced tutorial on pygtk
Message-ID: <e033edfb0701290627p267c56a7pf17b58e046a4b630@mail.gmail.com>

Hi there Everybody,

      I'm currently writing a program in pygtk, and I'm looking for a more
advanced tutorial in pygtk. I have read the one that is on the
pygtk.orgsite, and that has given a me a good basis from which to
start. Now, I am
looking to expand my range of knowledge. Also with that, I looking for good
programming practices in reference to GUIs. Could anybody recommend a site
tutorial that fits the bill?


Thanks!
-Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070129/7932f78d/attachment.html 

From nephish at gmail.com  Mon Jan 29 15:53:21 2007
From: nephish at gmail.com (shawn bright)
Date: Mon, 29 Jan 2007 08:53:21 -0600
Subject: [Tutor] question about a list of lists
In-Reply-To: <45BD67CA.60405@tds.net>
References: <384c93600701281139xf74fdbbxbbf2750fab7c224d@mail.gmail.com>
	<45BD67CA.60405@tds.net>
Message-ID: <384c93600701290653i3042ebe9i48cf965d54f49d7e@mail.gmail.com>

Thanks Kent,
   i am going with option A, the helper set, because i also need to count
the occurances and this seems to be the easiest solution.

thanks for your help.

shawn

On 1/28/07, Kent Johnson <kent37 at tds.net> wrote:
>
> shawn bright wrote:
> > lo there all.
> >
> > i have a list of lists that i want to build, only if an item is not in
> > the list already.
> >
> > kinda like this
> > new_list = []
> > for item in lists: # item will look something like [var1, var2, var3]
> >     if item[0] in new_list ( only the first element of each list ) like
> > new_list[0][0]
> >
> > basicly, i want to know if item[0]   is one of the items[0] in my
> new_list
> >
> > whats a good pythonic way to do this? i mean, i have a couple of way to
> > do this, but they are ugly.
>
> One way to do this is to keep a helper set that contains the first
> elements of each list. Something like
> new_list = []
> firsts = set()
> for item in lists:
>    if item[0] not in firsts:
>      new_list.append(item)
>      firsts.add(item[0]
>
> If you don't care about the order of the result, and if two lists have
> duplicate first items you are happy to use the first, then you could use
> a dict mapping first item to list:
>
> new_list = dict((item[0], item) for item in lists).values()
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070129/db94acc0/attachment.htm 

From kent37 at tds.net  Mon Jan 29 16:06:50 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 29 Jan 2007 10:06:50 -0500
Subject: [Tutor] question about a list of lists
In-Reply-To: <384c93600701290653i3042ebe9i48cf965d54f49d7e@mail.gmail.com>
References: <384c93600701281139xf74fdbbxbbf2750fab7c224d@mail.gmail.com>	
	<45BD67CA.60405@tds.net>
	<384c93600701290653i3042ebe9i48cf965d54f49d7e@mail.gmail.com>
Message-ID: <45BE0D8A.2090907@tds.net>

shawn bright wrote:
> Thanks Kent,
>    i am going with option A, the helper set, because i also need to 
> count the occurances and this seems to be the easiest solution.

If you need the number of unique items that is just the length of the 
final list. If you need the number of occurrences of each initial item 
then a dict mapping initial item to count (or maybe a list of lists) 
would be the way to go.

Kent

> 
> thanks for your help.
> 
> shawn
> 
> On 1/28/07, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> wrote:
> 
>     shawn bright wrote:
>      > lo there all.
>      >
>      > i have a list of lists that i want to build, only if an item is
>     not in
>      > the list already.
>      >
>      > kinda like this
>      > new_list = []
>      > for item in lists: # item will look something like [var1, var2,
>     var3]
>      >     if item[0] in new_list ( only the first element of each list
>     ) like
>      > new_list[0][0]
>      >
>      > basicly, i want to know if item[0]   is one of the items[0] in my
>     new_list
>      >
>      > whats a good pythonic way to do this? i mean, i have a couple of
>     way to
>      > do this, but they are ugly.
> 
>     One way to do this is to keep a helper set that contains the first
>     elements of each list. Something like
>     new_list = []
>     firsts = set()
>     for item in lists:
>        if item[0] not in firsts:
>          new_list.append(item)
>          firsts.add(item[0]
> 
>     If you don't care about the order of the result, and if two lists have
>     duplicate first items you are happy to use the first, then you could use
>     a dict mapping first item to list:
> 
>     new_list = dict((item[0], item) for item in lists).values()
> 
>     Kent
> 
> 



From perlmunky at googlemail.com  Mon Jan 29 16:13:54 2007
From: perlmunky at googlemail.com (Daniel Klose)
Date: Mon, 29 Jan 2007 15:13:54 +0000
Subject: [Tutor] learning curve
In-Reply-To: <b6131fdc0701290429u378daad9g1f3dcdae335a3cc6@mail.gmail.com>
References: <b6131fdc0701290429u378daad9g1f3dcdae335a3cc6@mail.gmail.com>
Message-ID: <45BE0F32.70804@googlemail.com>

Hi all,

All I would like to do is take a file and count the number of times a
letter occurs in it.  It so happens that there letters are amino acids.
There are also some other checks in the script but these are not a
concern just yet.

What I would like to do is create a dictionary of arrays.
In perl (my current scripting language of choice) I would simply put:
 ${$dictionary{$key}}[$element] += 1
I have no idea how to create this kind of structure in python.

Also I have a while loop.  If this were perl, rather than using the i =
0 while(i < len(x)):
I would do : for (my $i = 0; $i < @array; $i++) {}.  I have found the
range function but I am not sure how to use it properly.
What I would like to do is create an index that allows me to access the
same element in two arrays (lists) of identical size.

I have pasted in my current code below, I would be very grateful if you
could help me trim up this code.
#!/usr/bin/python

import sys, os

structDir = '/home/danny/dataset/structure/'
seqDir   = '/home/danny/dataset/sequence/'

target = sys.argv[1]

seqFile = seqDir      + target
strFile = structDir   + target

seqDictionary = {}

if (os.path.isfile(seqFile) and os.path.isfile(strFile)):
   
    structureHandle = open(strFile)
    structureString = structureHandle.readline()
   
    sequenceHandle  = open(seqFile)
    sequenceString = sequenceHandle.readline()
   
    strArray = list(structureString)
    seqArray = list(sequenceString)

    if len(strArray) == len(seqArray):
        print "Length match\n"
       
        i=0
        while(i < len(strArray)):
            if seqDictionary.has_key(seqArray[i]):
                seqDictionary[seqArray[i]] += 1
            else:
                seqDictionary[seqArray[i]] = 1
               
            i += 1
           
else:
    print "Some data is missing!\n"

From kent37 at tds.net  Mon Jan 29 16:56:02 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 29 Jan 2007 10:56:02 -0500
Subject: [Tutor] learning curve
In-Reply-To: <45BE0F32.70804@googlemail.com>
References: <b6131fdc0701290429u378daad9g1f3dcdae335a3cc6@mail.gmail.com>
	<45BE0F32.70804@googlemail.com>
Message-ID: <45BE1912.2060209@tds.net>

Daniel Klose wrote:
> Hi all,
> 
> All I would like to do is take a file and count the number of times a
> letter occurs in it.  It so happens that there letters are amino acids.
> There are also some other checks in the script but these are not a
> concern just yet.
> 
> What I would like to do is create a dictionary of arrays.
> In perl (my current scripting language of choice) I would simply put:
>  ${$dictionary{$key}}[$element] += 1
> I have no idea how to create this kind of structure in python.

I don't speak perl much but it looks like you have a dict whose values 
are lists. Not quite the same as what you have below, which is a dict 
whose values are integers.
> 
> Also I have a while loop.  If this were perl, rather than using the i =
> 0 while(i < len(x)):
> I would do : for (my $i = 0; $i < @array; $i++) {}.  I have found the
> range function but I am not sure how to use it properly.

You could use
   for i in range(len(strArray)):
but this is not good usage; better to iterate over strArray directly.

> What I would like to do is create an index that allows me to access the
> same element in two arrays (lists) of identical size.

You can use the zip() function to process two lists in parallel:
for x, y in zip(xlist, ylist):
   # x is an element from xlist
   # y is the corresponding element from ylist
> 
> I have pasted in my current code below, I would be very grateful if you
> could help me trim up this code.
> #!/usr/bin/python
> 
> import sys, os
> 
> structDir = '/home/danny/dataset/structure/'
> seqDir   = '/home/danny/dataset/sequence/'
> 
> target = sys.argv[1]
> 
> seqFile = seqDir      + target
> strFile = structDir   + target

os.path.join() would be more idiomatic here though what you have works.
> 
> seqDictionary = {}
> 
> if (os.path.isfile(seqFile) and os.path.isfile(strFile)):
>    
>     structureHandle = open(strFile)
>     structureString = structureHandle.readline()
>    
>     sequenceHandle  = open(seqFile)
>     sequenceString = sequenceHandle.readline()
>    
>     strArray = list(structureString)
>     seqArray = list(sequenceString)

You don't have to convert to lists; strings are already sequences.
> 
>     if len(strArray) == len(seqArray):
>         print "Length match\n"
>        
>         i=0
>         while(i < len(strArray)):
>             if seqDictionary.has_key(seqArray[i]):
>                 seqDictionary[seqArray[i]] += 1
>             else:
>                 seqDictionary[seqArray[i]] = 1
>                
>             i += 1

The idiomatic way to iterate over sequenceString is just
   for c in sequenceString:

You don't seem to be using strArray except to get the length. Maybe this 
is where you need zip()? For example you could say
   for structChr, seqChr in zip(structureString, sequenceString):

An alternative to your conditional with has_key() is to use dict.get() 
with a default value:
   seqDictionary[c] = seqDictionary.get(c, 0) + 1

so the whole loop becomes just
   for c in sequenceString:
     seqDictionary[c] = seqDictionary.get(c, 0) + 1

In Python 2.5 you can use defaultdict to create a dict with a default 
value of 0:
from collections import defaultdict
seqDictionary = defaultdict(int)

then in the loop you can say
     seqDictionary[c] += 1

Kent


From gsf at panix.com  Mon Jan 29 17:10:08 2007
From: gsf at panix.com (Gabriel Farrell)
Date: Mon, 29 Jan 2007 11:10:08 -0500
Subject: [Tutor] Best IDE for Python
In-Reply-To: <7.0.1.0.2.20070127025526.076d4ea8@rcblue.com>
References: <20070125031221.27723.qmail@web38713.mail.mud.yahoo.com>
	<7.0.1.0.2.20070127025526.076d4ea8@rcblue.com>
Message-ID: <20070129161008.GA26408@panix.com>

On Sat, Jan 27, 2007 at 02:58:38AM -0800, Dick Moores wrote:
> <html>
> <body>
> At 07:12 PM 1/24/2007, Shadab Sayani wrote:<br>
> <blockquote type=cite class=cite cite="">Hi,<br>
> I am using vim editor to code my project in python.Is there a good
> IDE&nbsp; where in I type the name of the class object and then dot then
> all the attributes of the object are displayed so on.</blockquote><br>
> Ulipad can do this.<br><br>
> Dick Moores<br><br>
> <x-sigsep><p></x-sigsep>
> UliPad &lt;&lt;The Python Editor&gt;&gt;:
> <a href="http://wiki.woodpecker.org.cn/moin/UliPad">
> http://wiki.woodpecker.org.cn/moin/UliPad</a> </body>
> </html>
> 

If you want to stick with VIM, you can get the functionality you're
looking for if it's 7.0+ and compiled with +python.  A web search for
"omnicomplete python vim" (no quotes) brings up some useful pages.

Gabe


From perlmunky at googlemail.com  Mon Jan 29 17:32:59 2007
From: perlmunky at googlemail.com (Daniel Klose)
Date: Mon, 29 Jan 2007 16:32:59 +0000
Subject: [Tutor] learning curve
In-Reply-To: <45BE1912.2060209@tds.net>
References: <b6131fdc0701290429u378daad9g1f3dcdae335a3cc6@mail.gmail.com>
	<45BE0F32.70804@googlemail.com> <45BE1912.2060209@tds.net>
Message-ID: <45BE21BB.6010607@googlemail.com>

Thanks Kent,

I now have:

target = sys.argv[1]

seqDictionary =  {} # python 2.5 import defaultdict from collections.
structureArray = [0, 0, 0]

#THIS TAKES THE PLACE OF THE STANDARD PERL $DIR,$file
#shorter to do the os.path.join once to a variable.
if (os.path.isfile(os.path.join(structDir, target)) and
os.path.isfile(os.path.join(seqDir, target))):
    structureHandle = open(os.path.join(structDir, target))
    structureString = structureHandle.readline()
   
    sequenceHandle  = open(os.path.join(seqDir, target))
    sequenceString = sequenceHandle.readline()

    if len(structureString) == len(sequenceString):
       
        for strChar, seqChar in zip(structureString, sequenceString):
            #SET DEFAULT VALUE AS ZERO ELSE INCREMENT
            seqDictionary[seqChar] = seqDictionary.get(seqChar, 0) + 1
            if (strChar.count('-')):
                structureArray[0] += 1
            elif (strChar.count('H')):
                structureArray[1] += 1
            elif (strChar.count('E')):
                structureArray[2] += 1
            else:
                print strChar, " is not valid"
                break;
else:
    print "Some data is missing!\n"

The reason I want to create a dictionary of lists is because for each of
the keys in the dictionary I wanted to keep tabs on the associated
structure.  For example:

dictionary[A] = [0,0,0]

list x element = A
list y element = '-'

then dictionary[A][0] = 1

print dictionary[A]
: [1, 0, 0]

I thought that a dictionary would be the best way (it is the same way as
I have done it in perl and java).  I am using google but having limited
success.

*Do you folks bottom post or top post?  The users of the perl list are
sensitive about this stuff!

I am only running python 2.4 and the system admin doesn't like me so I
won't ask him to upgrade it.

Kent Johnson wrote:
> Daniel Klose wrote:
>> Hi all,
>>
>> All I would like to do is take a file and count the number of times a
>> letter occurs in it.  It so happens that there letters are amino acids.
>> There are also some other checks in the script but these are not a
>> concern just yet.
>>
>> What I would like to do is create a dictionary of arrays.
>> In perl (my current scripting language of choice) I would simply put:
>>  ${$dictionary{$key}}[$element] += 1
>> I have no idea how to create this kind of structure in python.
>
> I don't speak perl much but it looks like you have a dict whose values
> are lists. Not quite the same as what you have below, which is a dict
> whose values are integers.
>>
>> Also I have a while loop.  If this were perl, rather than using the i =
>> 0 while(i < len(x)):
>> I would do : for (my $i = 0; $i < @array; $i++) {}.  I have found the
>> range function but I am not sure how to use it properly.
>
> You could use
>   for i in range(len(strArray)):
> but this is not good usage; better to iterate over strArray directly.
>
>> What I would like to do is create an index that allows me to access the
>> same element in two arrays (lists) of identical size.
>
> You can use the zip() function to process two lists in parallel:
> for x, y in zip(xlist, ylist):
>   # x is an element from xlist
>   # y is the corresponding element from ylist
>>
>> I have pasted in my current code below, I would be very grateful if you
>> could help me trim up this code.
>> #!/usr/bin/python
>>
>> import sys, os
>>
>> structDir = '/home/danny/dataset/structure/'
>> seqDir   = '/home/danny/dataset/sequence/'
>>
>> target = sys.argv[1]
>>
>> seqFile = seqDir      + target
>> strFile = structDir   + target
>
> os.path.join() would be more idiomatic here though what you have works.
>>
>> seqDictionary = {}
>>
>> if (os.path.isfile(seqFile) and os.path.isfile(strFile)):
>>        structureHandle = open(strFile)
>>     structureString = structureHandle.readline()
>>        sequenceHandle  = open(seqFile)
>>     sequenceString = sequenceHandle.readline()
>>        strArray = list(structureString)
>>     seqArray = list(sequenceString)
>
> You don't have to convert to lists; strings are already sequences.
>>
>>     if len(strArray) == len(seqArray):
>>         print "Length match\n"
>>                i=0
>>         while(i < len(strArray)):
>>             if seqDictionary.has_key(seqArray[i]):
>>                 seqDictionary[seqArray[i]] += 1
>>             else:
>>                 seqDictionary[seqArray[i]] = 1
>>                            i += 1
>
> The idiomatic way to iterate over sequenceString is just
>   for c in sequenceString:
>
> You don't seem to be using strArray except to get the length. Maybe
> this is where you need zip()? For example you could say
>   for structChr, seqChr in zip(structureString, sequenceString):
>
> An alternative to your conditional with has_key() is to use dict.get()
> with a default value:
>   seqDictionary[c] = seqDictionary.get(c, 0) + 1
>
> so the whole loop becomes just
>   for c in sequenceString:
>     seqDictionary[c] = seqDictionary.get(c, 0) + 1
>
> In Python 2.5 you can use defaultdict to create a dict with a default
> value of 0:
> from collections import defaultdict
> seqDictionary = defaultdict(int)
>
> then in the loop you can say
>     seqDictionary[c] += 1
>
> Kent
>
>



From kent37 at tds.net  Mon Jan 29 18:04:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 29 Jan 2007 12:04:18 -0500
Subject: [Tutor] learning curve
In-Reply-To: <45BE21BB.6010607@googlemail.com>
References: <b6131fdc0701290429u378daad9g1f3dcdae335a3cc6@mail.gmail.com>
	<45BE0F32.70804@googlemail.com> <45BE1912.2060209@tds.net>
	<45BE21BB.6010607@googlemail.com>
Message-ID: <45BE2912.2090902@tds.net>

Daniel Klose wrote:
> Thanks Kent,
> 
> I now have:
> 
> target = sys.argv[1]
> 
> seqDictionary =  {} # python 2.5 import defaultdict from collections.
> structureArray = [0, 0, 0]
> 
> #THIS TAKES THE PLACE OF THE STANDARD PERL $DIR,$file
> #shorter to do the os.path.join once to a variable.
> if (os.path.isfile(os.path.join(structDir, target)) and
> os.path.isfile(os.path.join(seqDir, target))):
>     structureHandle = open(os.path.join(structDir, target))
>     structureString = structureHandle.readline()
>    
>     sequenceHandle  = open(os.path.join(seqDir, target))
>     sequenceString = sequenceHandle.readline()
> 
>     if len(structureString) == len(sequenceString):
>        
>         for strChar, seqChar in zip(structureString, sequenceString):
>             #SET DEFAULT VALUE AS ZERO ELSE INCREMENT
>             seqDictionary[seqChar] = seqDictionary.get(seqChar, 0) + 1
>             if (strChar.count('-')):

Since strChar is a single character you can just do
   if strChar == '-':
etc.

>                 structureArray[0] += 1
>             elif (strChar.count('H')):
>                 structureArray[1] += 1
>             elif (strChar.count('E')):
>                 structureArray[2] += 1
>             else:

You could put all of the above into a dict lookup, something like

offsets = { '-': 0, 'H': 1, 'E': 2 }	# this can be defined outside the loop
offset = offsets.get(strChr)
if offset is None:
   print strChar, " is not valid"
else:
   structureArray[offset] += 1

Or you could just use another dict for structureArray and index it by 
strChar directly.

>                 print strChar, " is not valid"
>                 break;
> else:
>     print "Some data is missing!\n"
> 
> The reason I want to create a dictionary of lists is because for each of
> the keys in the dictionary I wanted to keep tabs on the associated
> structure.  For example:
> 
> dictionary[A] = [0,0,0]
> 
> list x element = A
> list y element = '-'
> 
> then dictionary[A][0] = 1
> 
> print dictionary[A]
> : [1, 0, 0]
> 
> I thought that a dictionary would be the best way (it is the same way as
> I have done it in perl and java).  I am using google but having limited
> success.

You can easily make a dict whose values are lists or dicts. I'm not sure 
how the above pseudo-code fits in to your code but maybe you want 
something like this:

structureArray = structureDict.get(seqChar, [0, 0, 0])
# figure out offset as above
structureArray[offset] = 1 # or += 1 if you are keeping counts.

> *Do you folks bottom post or top post?  The users of the perl list are
> sensitive about this stuff!

We're pretty casual here on python-tutors but on comp.lang.python you 
will get scolded for top-posting and bottom-posting is more common here 
as well.
> 
> I am only running python 2.4 and the system admin doesn't like me so I
> won't ask him to upgrade it.


From Barry.Carroll at psc.com  Mon Jan 29 20:09:25 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Mon, 29 Jan 2007 11:09:25 -0800
Subject: [Tutor] converting tab-delimited text files to csv
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595AB5@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> Date: Fri, 26 Jan 2007 22:40:24 -0500
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] converting tab-delimited text files to csv
> To: Luke Paireepinart <rabidpoobear at gmail.com>
> Cc: tutor at python.org
> Message-ID: <45BAC9A8.4060204 at tds.net>
> Content-Type: text/plain; charset=windows-1252; format=flowed
> 
> Luke Paireepinart wrote:
> > csv is comma-separated values, right?
> > you should be able to just do a string replace of tabs -> commas on
each
> > line in the new file...
> > or is the csv format more complicated than that?
> 
> Yes, it is more complicated than that because the data itself may
> contain commas.
> 
> Kent


Greetings:

It's useful to recall that the Python CSV module was written to handle
Microsoft's implementation of the format.  According to Wikipedia

	(http://en.wikipedia.org/wiki/Comma-separated_values)

there is no formal specification. The article includes these two links:

	http://tools.ietf.org/html/rfc4180
	http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm

Here's another link that I've found useful:

	http://object-craft.com.au/projects/csv/

HTH.

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




From tim at johnsons-web.com  Mon Jan 29 23:35:22 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Mon, 29 Jan 2007 13:35:22 -0900
Subject: [Tutor] site-packages and permissions to byte-compile
Message-ID: <200701291335.22797.tim@johnsons-web.com>

Hello:

I just installed python 2.5 on Linux/Slackware 10.0

I have placed three files in the root of site-packages
on my machine that is 
/usr/local/lib/python2.5/site-packages

python appears to be importing this files with no complaint, but
they are not being byte-compiled. 

Note: I see that MySQLdb files are being byte-compiled.
Their ownership is root:root and permissions are 644
I've set the same ownership and permissions for the other
files to same.

What do I need to do to insure that they are byte-compiled?

Thanks
Tim

From dkuhlman at rexx.com  Tue Jan 30 01:17:53 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Mon, 29 Jan 2007 16:17:53 -0800
Subject: [Tutor] site-packages and permissions to byte-compile
In-Reply-To: <200701291335.22797.tim@johnsons-web.com>
References: <200701291335.22797.tim@johnsons-web.com>
Message-ID: <20070130001753.GA60115@cutter.rexx.com>

On Mon, Jan 29, 2007 at 01:35:22PM -0900, Tim Johnson wrote:
> Hello:
> 
> I just installed python 2.5 on Linux/Slackware 10.0
> 
> I have placed three files in the root of site-packages
> on my machine that is 
> /usr/local/lib/python2.5/site-packages
> 
> python appears to be importing this files with no complaint, but
> they are not being byte-compiled. 
> 
> Note: I see that MySQLdb files are being byte-compiled.
> Their ownership is root:root and permissions are 644
> I've set the same ownership and permissions for the other
> files to same.
> 
> What do I need to do to insure that they are byte-compiled?

They do not compile because you are importing these files as a user
that does not have permission to write in the directory containing
those modules.

Your Python distribution should have a Python script called
compileall.py.  You can run that as root to compile *all* the files
in a directory.

For individual files, there is a module named py_compile.py.  Here
is an example of its use on my machine:

    $ python /usr/local/lib/python2.5/py_compile.py test_path.py

Again, you will need write privileges to the directory containing
the module to be compiled (in this case test_path.py).

See the modules py_compile and compileall in the Python standard
library.

You may notice that when you install Python packages (e.g. using
setup.py), compiling happens automatically for you.

Another alternative is to put those modules in a directory in which
you *do* have write access and then add that directory to your
PYTHONPATH.

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From rob.andrews at gmail.com  Tue Jan 30 01:48:15 2007
From: rob.andrews at gmail.com (Rob Andrews)
Date: Mon, 29 Jan 2007 18:48:15 -0600
Subject: [Tutor] [OT?] PyCon
Message-ID: <8d757d2e0701291648w55ee2f20g93cf22ea37e56fb4@mail.gmail.com>

I hope it's not unforgivably off-topic to ask if anyone's planning on
attending PyCon in Feb.

My manager gave a thumbs-up for me to attend today.

-Rob

From tim at johnsons-web.com  Tue Jan 30 02:43:42 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Mon, 29 Jan 2007 16:43:42 -0900
Subject: [Tutor] site-packages and permissions to byte-compile
In-Reply-To: <20070130001753.GA60115@cutter.rexx.com>
References: <200701291335.22797.tim@johnsons-web.com>
	<20070130001753.GA60115@cutter.rexx.com>
Message-ID: <200701291643.42253.tim@johnsons-web.com>

On Monday 29 January 2007 03:17 pm, Dave Kuhlman wrote:
> On Mon, Jan 29, 2007 at 01:35:22PM -0900, Tim Johnson wrote:
> > Hello:
> >
> > I just installed python 2.5 on Linux/Slackware 10.0
> >
> > I have placed three files in the root of site-packages
> > on my machine that is
> > /usr/local/lib/python2.5/site-packages
> >
> > python appears to be importing this files with no complaint, but
> > they are not being byte-compiled.
> >
> > Note: I see that MySQLdb files are being byte-compiled.
> > Their ownership is root:root and permissions are 644
> > I've set the same ownership and permissions for the other
> > files to same.
> >
> > What do I need to do to insure that they are byte-compiled?
>
> They do not compile because you are importing these files as a user
> that does not have permission to write in the directory containing
> those modules.
>
> Your Python distribution should have a Python script called
> compileall.py.  You can run that as root to compile *all* the files
> in a directory.

Yes. That was the solution.
Thank you Dave.
tj

> For individual files, there is a module named py_compile.py.  Here
> is an example of its use on my machine:
>
>     $ python /usr/local/lib/python2.5/py_compile.py test_path.py
>
> Again, you will need write privileges to the directory containing
> the module to be compiled (in this case test_path.py).
>
> See the modules py_compile and compileall in the Python standard
> library.
>
> You may notice that when you install Python packages (e.g. using
> setup.py), compiling happens automatically for you.
>
> Another alternative is to put those modules in a directory in which
> you *do* have write access and then add that directory to your
> PYTHONPATH.
>
> Dave

From johan at accesstel.co.za  Tue Jan 30 05:25:53 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Tue, 30 Jan 2007 06:25:53 +0200
Subject: [Tutor] Python code to connect using PPPoE
In-Reply-To: <45B92E29.3070704@h-lab.net>
Message-ID: <200701300421.l0U4Lkmm001972@mail.mtn.co.za>

Thanks,

Unfortunately I am on a device that does not have this in the kernel and I
can't recompile the kernel to include PPPoE nor can I load other utils to do
tasks for me. 

So I must do it all in Python.
I found Scapy that seems to support PPPoE connections, but finding out how
that can be used, seems to be a trial and error process. The scapy mailing
list does seem to be so helpful than this one.

Any other suggestions would be appreciated.
Thanks

Johan 

-----Original Message-----
From: tutor-bounces+johan=accesstel.co.za at python.org
[mailto:tutor-bounces+johan=accesstel.co.za at python.org] On Behalf Of Hugo
Gonz?lez Monteverde
Sent: 26 January 2007 12:25 AM
To: tutor at python.org
Subject: Re: [Tutor] Python code to connect using PPPoE

Hi Johan,

PPPoE is both in the Linux Kernel (for the low level work) and as some
executables and scripts.

It fou want to establish a connection from a Python script (E.G. ehn the
computer has no internet access and you need it) The best way would be to
call the appropriate utilities, and parse their output. This means calling
adsl-connect, ficonfig, and the like, maybe parsing the output from
ifconfig. Take a look at the module named subprocess to do that.

Reimplementing these utilities in Python is some work, but doable. 
Implementing PPPoE in Python, reading the device files and all that... 
well... it's almost nonsense. For this, you have to use the kernel.

Johan Geldenhuys wrote:
> Kent,
> I want to establish the connection with Python. I think in Linux you 
> can use a PPPoE package to make life easier, but I don't want to use 
> the Kernel to do that.
> 
> Johan
> 

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor

-- 
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.11/652 - Release Date: 2007/01/25
03:32 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.12/655 - Release Date: 2007/01/28
01:12 PM
 


From vgvr620034 at gmail.com  Tue Jan 30 06:42:28 2007
From: vgvr620034 at gmail.com (vanam)
Date: Tue, 30 Jan 2007 11:12:28 +0530
Subject: [Tutor] Diff between opening files in 'r' and 'r+' mode
Message-ID: <bedebdfb0701292142t152be911ha5c81ec165a58bfb@mail.gmail.com>

i want to know the difference between 'r' mode and 'r+' mode
1.i = open('c:\python25\integer.txt','w')-------->for writiing
  i.write('hai')--------->written some content in text file
  i = open('c:\python25\integer.txt','r')---->for reading
  print i.read()---->for printing the contents in that text file
  i = open('c:\python25\integer.txt','w')---------->for writing
  i.write('how')-----------?Rewrite the contents
  print i.read()
[MY QUESTION]:i want to read the text file contents cant it be done by
giving (print i.read())?
Before going to next question [I deleted all the contents in the text file]

2.i = open('c:\python25\integer.txt','r+')-----For reading and writing
   i.write('hai')--------->written some content  to text file
   print i.read()--------->{?
?('c:\python25\integer.txt','w')
                               i write('')
                               print i.read()how')
                               i = open('c:\python25\integer.txt','r')
                               print i.read()
                               i = open('c:\python25\integer.txt','w')
                               i.write()
                               i = open('c:\python25\integer.txt','r')
                              print i.read() } --->Thats what i saw on
interpreter(In curly braces) when  i ran the script
[MY QUESTION]:1.from where the above in curly braces is printed?and i have
written only 'hai' to the text file
                          2.Should i recall again the opening of the file in
'r' mode to read the file?

-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070130/446175a4/attachment.htm 

From vgvr620034 at gmail.com  Tue Jan 30 08:11:16 2007
From: vgvr620034 at gmail.com (vanam)
Date: Tue, 30 Jan 2007 12:41:16 +0530
Subject: [Tutor] Explanation of Pickle
Message-ID: <bedebdfb0701292311i7fcdf0bcvfba01e2a33f1a33a@mail.gmail.com>

can any one explain about pickle i read in the book but they have not
provided any example for that so please explain with a simple example

-- 

                                           Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070130/57dbf186/attachment.html 

From cappy2112 at gmail.com  Tue Jan 30 09:22:13 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Tue, 30 Jan 2007 00:22:13 -0800
Subject: [Tutor] reassigning/replacing sys.stdout
Message-ID: <8249c4ac0701300022p16bea5e6ha33adae9b7f030ec@mail.gmail.com>

I'm writing a python gui app that will call a python cmd line app. The gui
will take users input, pass it to the cmd line app, then display the cmd app
program output. The idea is to give users who aren't comfortable with the
cmd line a way to run the program, without having to open a shell window (on
Linux) or cmd prompt  (On Windows) and get hung up on syntax or shell
issues. It's a crutch.

The author of the cmd line app suggested I temporarily replace
sys.stdout'with a file descriptor class that can write directly to the
gui'.
The author is now out of communications for a few weeks,  so I can't
elaborate.

However, I've opened a file which writes to the disk, and replaced that
sys.stdout with that file descriptor.
I can then close and open that file and have the output of his program.
Now I can just put this in a textbox on the gui and display it to the user.

Writing to a file on disk, then reading it back in seems a bit clunky to me.
While I did somewhat do what the author had suggested (although I didn't
make a class out of the file descriptor), and it works, is there a better
way?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070130/89f38a10/attachment.htm 

From rabidpoobear at gmail.com  Tue Jan 30 09:50:10 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 30 Jan 2007 02:50:10 -0600
Subject: [Tutor] reassigning/replacing sys.stdout
In-Reply-To: <8249c4ac0701300022p16bea5e6ha33adae9b7f030ec@mail.gmail.com>
References: <8249c4ac0701300022p16bea5e6ha33adae9b7f030ec@mail.gmail.com>
Message-ID: <45BF06C2.8060302@gmail.com>

Tony Cappellini wrote:
>
> I'm writing a python gui app that will call a python cmd line app. The 
> gui will take users input, pass it to the cmd line app, then display 
> the cmd app program output. The idea is to give users who aren't 
> comfortable with the cmd line a way to run the program, without having 
> to open a shell window (on Linux) or cmd prompt  (On Windows) and get 
> hung up on syntax or shell issues. It's a crutch.
>
> The author of the cmd line app suggested I temporarily replace 
> sys.stdout 'with a file descriptor class that can write directly to 
> the gui'.
> The author is now out of communications for a few weeks,  so I can't 
> elaborate.
>
> However, I've opened a file which writes to the disk, and replaced 
> that sys.stdout with that file descriptor.
> I can then close and open that file and have the output of his program.
> Now I can just put this in a textbox on the gui and display it to the 
> user.
>
> Writing to a file on disk, then reading it back in seems a bit clunky 
> to me.
> While I did somewhat do what the author had suggested (although I 
> didn't make a class out of the file descriptor), and it works, is 
> there a better way?
print 'bob'
is the same as
sys.stdout.write('bob')
sys.stdout.write('\n')

In python, since this 'sys....' function call doesn't check what type of 
object it's calling,
just that it has a method called 'write', you can write your own object 
and drop it in here.

E.G.

class GuiUpdater(object):
    def write(astring):
        #update your textbox here.

sys.stdout = GuiUpdater
print 'teststr'

Hmm, actually that might not work since it's not an instance of a class.
But that's the general idea/strategy.

HTH,
-Luke

From cappy2112 at gmail.com  Tue Jan 30 09:54:10 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Tue, 30 Jan 2007 00:54:10 -0800
Subject: [Tutor] reassigning/replacing sys.stdout
In-Reply-To: <45BF06C2.8060302@gmail.com>
References: <8249c4ac0701300022p16bea5e6ha33adae9b7f030ec@mail.gmail.com>
	<45BF06C2.8060302@gmail.com>
Message-ID: <8249c4ac0701300054n813563ax3b23f52624c8706e@mail.gmail.com>

got it -thanks

On 1/30/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
>
> Tony Cappellini wrote:
> >
> > I'm writing a python gui app that will call a python cmd line app. The
> > gui will take users input, pass it to the cmd line app, then display
> > the cmd app program output. The idea is to give users who aren't
> > comfortable with the cmd line a way to run the program, without having
> > to open a shell window (on Linux) or cmd prompt  (On Windows) and get
> > hung up on syntax or shell issues. It's a crutch.
> >
> > The author of the cmd line app suggested I temporarily replace
> > sys.stdout 'with a file descriptor class that can write directly to
> > the gui'.
> > The author is now out of communications for a few weeks,  so I can't
> > elaborate.
> >
> > However, I've opened a file which writes to the disk, and replaced
> > that sys.stdout with that file descriptor.
> > I can then close and open that file and have the output of his program.
> > Now I can just put this in a textbox on the gui and display it to the
> > user.
> >
> > Writing to a file on disk, then reading it back in seems a bit clunky
> > to me.
> > While I did somewhat do what the author had suggested (although I
> > didn't make a class out of the file descriptor), and it works, is
> > there a better way?
> print 'bob'
> is the same as
> sys.stdout.write('bob')
> sys.stdout.write('\n')
>
> In python, since this 'sys....' function call doesn't check what type of
> object it's calling,
> just that it has a method called 'write', you can write your own object
> and drop it in here.
>
> E.G.
>
> class GuiUpdater(object):
>     def write(astring):
>         #update your textbox here.
>
> sys.stdout = GuiUpdater
> print 'teststr'
>
> Hmm, actually that might not work since it's not an instance of a class.
> But that's the general idea/strategy.
>
> HTH,
> -Luke
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070130/adb94230/attachment.htm 

From alan.gauld at btinternet.com  Tue Jan 30 11:20:45 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 30 Jan 2007 10:20:45 -0000
Subject: [Tutor] Diff between opening files in 'r' and 'r+' mode
References: <bedebdfb0701292142t152be911ha5c81ec165a58bfb@mail.gmail.com>
Message-ID: <epn665$t6r$1@sea.gmane.org>

Hi Vanam,

I'm a wee bit confused by your email.

> i want to know the difference between 'r' mode and 'r+' mode

r+ allows you to both read and write to the file without having
to close in between. But its up to you to control where the
"cursor" is within the file so that you write in the correct places.

>>>>>>>>>>>
1.i = open('c:\python25\integer.txt','w')-------->for writiing
  i.write('hai')--------->written some content in text file
  i = open('c:\python25\integer.txt','r')---->for reading
  print i.read()---->for printing the contents in that text file
  i = open('c:\python25\integer.txt','w')---------->for writing
  i.write('how')-----------?Rewrite the contents
  print i.read()
[MY QUESTION]:i want to read the text file contents cant it be done by
giving (print i.read())?
>>>>>>>>>>>

Yes you can print i.read()
But in the sequence above you never close the file which may
result in strangeness. For example your writes may not actually
get sent to disk... It is always good practice to close a file before
trying to reopen it.

In the examples above, what are you expecting to see?
I asume 'hai' the first time and 'how' the second? But on the
second you don't even open i for reading following the write....

>>>>>>>>>>>>
2.i = open('c:\python25\integer.txt','r+')-----For reading and writing
   i.write('hai')--------->written some content  to text file
   print i.read()--------->{?
?('c:\python25\integer.txt','w')
                               i write('')
                               print i.read()how')
                               i = open('c:\python25\integer.txt','r')
                               print i.read()
                               i = open('c:\python25\integer.txt','w')
                               i.write()
                               i = open('c:\python25\integer.txt','r')
                              print i.read() } --->Thats what i saw on
interpreter(In curly braces) when  i ran the script
>>>>>>>>>>>>

> [MY QUESTION]:1.from where the above in curly braces
> is printed?and i have written only 'hai' to the text file

I have no idea!
What I would expect to happen is that you write 'hai' to the
start of the file then the read will read in the contents of the file,
except for the hai which you have written. But you may
need to use flush() to force the write first. But whether
the stuff above is the file contents I don't know. - what
happens if you open the file in a text editor?

> 2.Should i recall again the opening of the file in
> 'r' mode to read the file?

r+ should allow you to read but depending on what you need
you may need to position the cursor using seek() first. In general
I don't encourage the use of r+ because it does require careful
control of exactly where you are in the file, which can be difficult.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Tue Jan 30 11:24:24 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 30 Jan 2007 10:24:24 -0000
Subject: [Tutor] Explanation of Pickle
References: <bedebdfb0701292311i7fcdf0bcvfba01e2a33f1a33a@mail.gmail.com>
Message-ID: <epn6cs$tqc$1@sea.gmane.org>

"vanam" <vgvr620034 at gmail.com> wrote

> can any one explain about pickle i read in the book but they have 
> not
> provided any example for that so please explain with a simple 
> example

Conceptually it is very simple. Pickle takes a python object
and serialises it to a sequence of bytes which it stores in a
text file. The text file can be unpickled by reading it back
and de-serialising it. The object you wind up with should be
exactly the same as the object you started with. The idea
being that you can store (or persist) your objects even while
your program is not running. The pickle module provides the
functions to do all of that.

Are there  any more specific problems you are having?

Alan G. 



From alan.gauld at btinternet.com  Tue Jan 30 11:29:28 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 30 Jan 2007 10:29:28 -0000
Subject: [Tutor] reassigning/replacing sys.stdout
References: <8249c4ac0701300022p16bea5e6ha33adae9b7f030ec@mail.gmail.com>
Message-ID: <epn6mc$utu$1@sea.gmane.org>


"Tony Cappellini" <cappy2112 at gmail.com> wrote

> The author of the cmd line app suggested I temporarily replace
> sys.stdout'with a file descriptor class that can write directly to 
> the
> gui'.

I'm not sure that would be such a great idea since the
command line tool knows nothing about the GUI - size,
height, fonts etc.

A more common approach would be to use popen() to capture
the output as a string and then the GUI can format it
appropriately for display. popen effectively captures stdout
(and stderr if needed).

Of course to be totally 'correct' you should use the new
subprocess module to do the same thing...

I suspect that is both easier and would give a better
quality result to your users.

Alan G. 



From kent37 at tds.net  Tue Jan 30 12:02:31 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 30 Jan 2007 06:02:31 -0500
Subject: [Tutor] Explanation of Pickle
In-Reply-To: <bedebdfb0701292311i7fcdf0bcvfba01e2a33f1a33a@mail.gmail.com>
References: <bedebdfb0701292311i7fcdf0bcvfba01e2a33f1a33a@mail.gmail.com>
Message-ID: <45BF25C7.9050107@tds.net>

vanam wrote:
> can any one explain about pickle i read in the book but they have not 
> provided any example for that so please explain with a simple example

There are examples in the docs:
http://docs.python.org/lib/pickle-example.html

Kent


From sanelson at gmail.com  Tue Jan 30 13:09:22 2007
From: sanelson at gmail.com (Steve Nelson)
Date: Tue, 30 Jan 2007 12:09:22 +0000
Subject: [Tutor] Variable Swap
In-Reply-To: <45BDEDC2.4040405@tds.net>
References: <b6131fdc0701290429u378daad9g1f3dcdae335a3cc6@mail.gmail.com>
	<45BDEDC2.4040405@tds.net>
Message-ID: <b6131fdc0701300409p2f0ab85ua044d849415b68c5@mail.gmail.com>

On 1/29/07, Kent Johnson <kent37 at tds.net> wrote:
> Because 2 ^ 3 == 1, right? Are you sure you understand what xor does? It
> is a bitwise exclusive or:

Yes... at a binary level, it returns true if either input is true, but not both:

A B Q
0 0 0
0 1 1
1 0 1
1 1 0

Thus it has the effect of swapping / reversing.

For some reason I had not been thinking straight, and had thought we
might just see a toggle of the value of the variable, which is, of
course, nonsense.

So in my example:

2 = 00000010
3 = 00000011

xor:

Q = 00000001

Lesson: think first... was just me being blind.

> x, y = y, x

Doesn't this use temporary variables?

> Kent

S.

From simon at brunningonline.net  Tue Jan 30 13:40:05 2007
From: simon at brunningonline.net (Simon Brunning)
Date: Tue, 30 Jan 2007 12:40:05 +0000
Subject: [Tutor] Variable Swap
In-Reply-To: <b6131fdc0701300409p2f0ab85ua044d849415b68c5@mail.gmail.com>
References: <b6131fdc0701290429u378daad9g1f3dcdae335a3cc6@mail.gmail.com>
	<45BDEDC2.4040405@tds.net>
	<b6131fdc0701300409p2f0ab85ua044d849415b68c5@mail.gmail.com>
Message-ID: <8c7f10c60701300440m39d61c9cncc9baa0fda9c64c0@mail.gmail.com>

On 1/30/07, Steve Nelson <sanelson at gmail.com> wrote:
> > x, y = y, x
>
> Doesn't this use temporary variables?

Python doesn't really *have* variables, as such, so no. What it does
is to create a tuple referring to the objects (or just possibly one
object) referred to by the names 'y' and 'x', then re-binds the
objects from the tuple to the names 'x' and 'y' respectively.

Reset your brain! <http://effbot.org/zone/python-objects.htm>

-- 
Cheers,
Simon B
simon at brunningonline.net
http://www.brunningonline.net/simon/blog/

From kent37 at tds.net  Tue Jan 30 13:47:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 30 Jan 2007 07:47:40 -0500
Subject: [Tutor] Variable Swap
In-Reply-To: <b6131fdc0701300409p2f0ab85ua044d849415b68c5@mail.gmail.com>
References: <b6131fdc0701290429u378daad9g1f3dcdae335a3cc6@mail.gmail.com>	
	<45BDEDC2.4040405@tds.net>
	<b6131fdc0701300409p2f0ab85ua044d849415b68c5@mail.gmail.com>
Message-ID: <45BF3E6C.9040704@tds.net>

Steve Nelson wrote:
>> x, y = y, x
> 
> Doesn't this use temporary variables?

Yes, behind the scenes maybe it does. It may create a temporary list, 
then unpack it - that is what the syntax actually means. Let's take a look:

In [1]: import dis

In [2]: def f(x, y):
    ...:     x, y = y, x
    ...:
    ...:

In [3]: dis.dis(f)
   2           0 LOAD_FAST                1 (y)
               3 LOAD_FAST                0 (x)
               6 ROT_TWO
               7 STORE_FAST               0 (x)
              10 STORE_FAST               1 (y)
              13 LOAD_CONST               0 (None)
              16 RETURN_VALUE

So it is actually using the stack to store the variables. In a sense it 
is a temporary but it is not using an actual variable location and it is 
pretty efficient; much more so than your xor trick:

In [6]: def h(x, y):
    ...:     y=x^y
    ...:     x=x^y
    ...:     y=x^y
    ...:
    ...:

In [7]: dis.dis(h)
   2           0 LOAD_FAST                0 (x)
               3 LOAD_FAST                1 (y)
               6 BINARY_XOR
               7 STORE_FAST               1 (y)

   3          10 LOAD_FAST                0 (x)
              13 LOAD_FAST                1 (y)
              16 BINARY_XOR
              17 STORE_FAST               0 (x)

   4          20 LOAD_FAST                0 (x)
              23 LOAD_FAST                1 (y)
              26 BINARY_XOR
              27 STORE_FAST               1 (y)
              30 LOAD_CONST               0 (None)
              33 RETURN_VALUE

Surprisingly, the stack optimization even works with three variables:
In [4]: def g(x, y, z):
    ...:     x, y, z = z, y, x
    ...:
    ...:

In [5]: dis.dis(g)
   2           0 LOAD_FAST                2 (z)
               3 LOAD_FAST                1 (y)
               6 LOAD_FAST                0 (x)
               9 ROT_THREE
              10 ROT_TWO
              11 STORE_FAST               0 (x)
              14 STORE_FAST               1 (y)
              17 STORE_FAST               2 (z)
              20 LOAD_CONST               0 (None)
              23 RETURN_VALUE

I wonder why it doesn't just load them in the reverse order of the store 
and dispense with the ROT opcodes?

Kent


From lnhaig at gmail.com  Tue Jan 30 13:37:11 2007
From: lnhaig at gmail.com (Lance Haig)
Date: Tue, 30 Jan 2007 12:37:11 +0000
Subject: [Tutor] OT: Would this be difficult to do?
Message-ID: <45BF3BF7.6060706@gmail.com>

Hi,

I have a need for a file system scanning tool that produces csv files of
data that is older than a specified date.

All the commercial ones I have found just don't quite do what I want.

I have been a lurker on this list for some time and was wondering if
this would be very difficult to do?

Any suggestions would be appreciated

Thanks

Lance

P.S. I an still learning Python. busy with Alan's tutorial




From kent37 at tds.net  Tue Jan 30 14:13:32 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 30 Jan 2007 08:13:32 -0500
Subject: [Tutor] OT: Would this be difficult to do?
In-Reply-To: <45BF3BF7.6060706@gmail.com>
References: <45BF3BF7.6060706@gmail.com>
Message-ID: <45BF447C.3080806@tds.net>

Lance Haig wrote:
> Hi,
> 
> I have a need for a file system scanning tool that produces csv files of
> data that is older than a specified date.
> 
> All the commercial ones I have found just don't quite do what I want.
> 
> I have been a lurker on this list for some time and was wondering if
> this would be very difficult to do?

No, not difficult at all. Use os.walk() to walk the file system, 
os.path.getmtime() to get the time of last modification, the csv module 
to write the csv file. Use datetime.datetime for time arithmetic and to 
format the times if you want that in the csv file. It's probably a 20-30 
line program if you just want a list of file names and dates.

You might also like to use the path module instead of os.walk() etc:
http://www.jorendorff.com/articles/python/path/index.html

Kent


From hmm at woolgathering.cx  Tue Jan 30 17:13:23 2007
From: hmm at woolgathering.cx (William O'Higgins Witteman)
Date: Tue, 30 Jan 2007 11:13:23 -0500
Subject: [Tutor] Getting HTTP response codes
Message-ID: <20070130161323.GA5557@sillyrabbi.dyndns.org>

I am looking to get the HTTP response from a URI - 200, 404, etc.  I'm
not sure which module I should look at.  I've looked at urllib and
urllib2, but they only seem to provide this information in Exceptions,
and then only if there is an error.  That's fine if I'm only looking for
implicit 200's, but I'm actually looking for the HTTP response code.

I initially thought that httplib would be the way to go, but it does not
seems to be very user-friendly.  There seems to be a class for HTTP
response codes, but I don't know how to use it.  Can anyone point the
way?  Thanks.
-- 

yours,

William

From eike.welk at gmx.net  Tue Jan 30 17:34:31 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Tue, 30 Jan 2007 17:34:31 +0100
Subject: [Tutor] Explanation of Pickle
In-Reply-To: <bedebdfb0701292311i7fcdf0bcvfba01e2a33f1a33a@mail.gmail.com>
References: <bedebdfb0701292311i7fcdf0bcvfba01e2a33f1a33a@mail.gmail.com>
Message-ID: <200701301734.31148.eike.welk@gmx.net>

Hello Vanam!

On Tuesday 30 January 2007 08:11, vanam wrote:
> can any one explain about pickle i read in the book but they have
> not provided any example for that so please explain with a simple
> example
A class can pickle itself like this:


class foo(object):
    #lots of code here

    def _loadPickle(self, fileName):
        '''Load data from a file in pickle format.'''
        f = open(fileName, 'rb')
        newStore = cPickle.load(f) 
        self.__dict__ = newStore.__dict__ #copy the data attributes
        f.close()

    def _savePickle(self, fileName):
        '''Dump the data into a binary pickle file'''
        f = open(fileName, 'wb')
        cPickle.dump(self, f, 2)
        f.close()


Kind regards,
Eike.


From dyoo at hkn.eecs.berkeley.edu  Tue Jan 30 17:58:56 2007
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Jan 2007 08:58:56 -0800 (PST)
Subject: [Tutor] reassigning/replacing sys.stdout
In-Reply-To: <8249c4ac0701300022p16bea5e6ha33adae9b7f030ec@mail.gmail.com>
References: <8249c4ac0701300022p16bea5e6ha33adae9b7f030ec@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0701300854170.31844@hkn.eecs.berkeley.edu>

> The author of the cmd line app suggested I temporarily replace 
> sys.stdout'with a file descriptor class that can write directly to the 
> gui'. The author is now out of communications for a few weeks, so I 
> can't elaborate.

It sounds like the subprocess module might be very useful here:

     http://www.python.org/doc/lib/node529.html

The reason is because you can use the PIPE option, which gives you a 
file-like object of the other process's stdout.  There's an example of 
this in action here:

     http://www.python.org/doc/lib/node536.html

If you have more questions, please feel free to ask.  Best of wishes!

From kent37 at tds.net  Tue Jan 30 18:05:34 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 30 Jan 2007 12:05:34 -0500
Subject: [Tutor] Getting HTTP response codes
In-Reply-To: <20070130161323.GA5557@sillyrabbi.dyndns.org>
References: <20070130161323.GA5557@sillyrabbi.dyndns.org>
Message-ID: <45BF7ADE.70508@tds.net>

William O'Higgins Witteman wrote:
> I am looking to get the HTTP response from a URI - 200, 404, etc.  I'm
> not sure which module I should look at.  I've looked at urllib and
> urllib2, but they only seem to provide this information in Exceptions,
> and then only if there is an error.  That's fine if I'm only looking for
> implicit 200's, but I'm actually looking for the HTTP response code.
> 
> I initially thought that httplib would be the way to go, but it does not
> seems to be very user-friendly.  There seems to be a class for HTTP
> response codes, but I don't know how to use it.  Can anyone point the
> way?  Thanks.

I have done this using httplib.HTTPConnection. Here is a snippet. 
self.server is e.g. 'www.google.com'; self.path is the rest of the URL 
starting with '/':

             conn = HTTPConnection(self.server)
#            conn.set_debuglevel(1)
             conn.request('GET', self.path)

             resp = conn.getresponse()
             data = resp.read()
             status = resp.status

             conn.close()

             if status == 200:
                 # etc

Kent


From cappy2112 at gmail.com  Tue Jan 30 18:42:49 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Tue, 30 Jan 2007 09:42:49 -0800
Subject: [Tutor] reassigning/replacing sys.stdout
In-Reply-To: <Pine.LNX.4.64.0701300854170.31844@hkn.eecs.berkeley.edu>
References: <8249c4ac0701300022p16bea5e6ha33adae9b7f030ec@mail.gmail.com>
	<Pine.LNX.4.64.0701300854170.31844@hkn.eecs.berkeley.edu>
Message-ID: <8249c4ac0701300942v679f6825wa6567c1fa0648433@mail.gmail.com>

That would be ideal- but I'm using 2.4 now, and the people using the app
would also have to upgrade to 2.5.
I don't like upgrading unless there's a pressing need.


On 1/30/07, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
> > The author of the cmd line app suggested I temporarily replace
> > sys.stdout'with a file descriptor class that can write directly to the
> > gui'. The author is now out of communications for a few weeks, so I
> > can't elaborate.
>
> It sounds like the subprocess module might be very useful here:
>
>      http://www.python.org/doc/lib/node529.html
>
> The reason is because you can use the PIPE option, which gives you a
> file-like object of the other process's stdout.  There's an example of
> this in action here:
>
>      http://www.python.org/doc/lib/node536.html
>
> If you have more questions, please feel free to ask.  Best of wishes!
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070130/a2def359/attachment-0001.htm 

From kent37 at tds.net  Tue Jan 30 18:54:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 30 Jan 2007 12:54:06 -0500
Subject: [Tutor] reassigning/replacing sys.stdout
In-Reply-To: <8249c4ac0701300942v679f6825wa6567c1fa0648433@mail.gmail.com>
References: <8249c4ac0701300022p16bea5e6ha33adae9b7f030ec@mail.gmail.com>	<Pine.LNX.4.64.0701300854170.31844@hkn.eecs.berkeley.edu>
	<8249c4ac0701300942v679f6825wa6567c1fa0648433@mail.gmail.com>
Message-ID: <45BF863E.5050700@tds.net>

Tony Cappellini wrote:
> That would be ideal- but I'm using 2.4 now, and the people using the app 
> would also have to upgrade to 2.5.
> I don't like upgrading unless there's a pressing need.

subprocess was added in Python 2.4. Older Python versions have similar 
functionality in os.popen* and popen2.

Kent

> On 1/30/07, *Danny Yoo* <dyoo at hkn.eecs.berkeley.edu 
> <mailto:dyoo at hkn.eecs.berkeley.edu>> wrote:
>     It sounds like the subprocess module might be very useful here:
> 
>          http://www.python.org/doc/lib/node529.html


From jeff at taupro.com  Tue Jan 30 21:35:27 2007
From: jeff at taupro.com (Jeff Rush)
Date: Tue, 30 Jan 2007 14:35:27 -0600
Subject: [Tutor] [OT?] PyCon
In-Reply-To: <8d757d2e0701291648w55ee2f20g93cf22ea37e56fb4@mail.gmail.com>
References: <8d757d2e0701291648w55ee2f20g93cf22ea37e56fb4@mail.gmail.com>
Message-ID: <45BFAC0F.3050404@taupro.com>

Rob Andrews wrote:
> I hope it's not unforgivably off-topic to ask if anyone's planning on
> attending PyCon in Feb.
> 
> My manager gave a thumbs-up for me to attend today.

Alright!  It's going to be a lot of fun.

BTW, if you need a hotel room, the price goes up Feb 1st from the con rate of 
$79/night to the hotel's normal rate of $279 or so.

This year we've tried to especially support those new to Python, with the 
Python 101 tutorial on Thursday, the Python Lab on Friday night and a few more 
activities under wraps for the evenings.  That's besides talks we selected 
specifically to introduce attendees to specific topics such as Python Eggs and 
Stackless.

See you there!

-Jeff


From cappy2112 at gmail.com  Wed Jan 31 02:44:05 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Tue, 30 Jan 2007 17:44:05 -0800
Subject: [Tutor] Purging/deleting the logfile with the logging module
Message-ID: <8249c4ac0701301744l76a2b283ycfed5796a3bda19d@mail.gmail.com>

I want to purge (empty) or delete the logfile created by the logging module,
and reopen it for a new session.

There is reference to a close function in the 2.3 docs, but I don't see how
I can purge or delete the file, since I don't have access to the file
descriptor.
 *close*( ) Tidy up any resources used by the handler. This version does
nothing and is intended to be implemented by subclasses. How can I
purge/delete & reopen the logfile?

thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070130/45b3f972/attachment.html 

From kent37 at tds.net  Wed Jan 31 04:00:38 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 30 Jan 2007 22:00:38 -0500
Subject: [Tutor] Purging/deleting the logfile with the logging module
In-Reply-To: <8249c4ac0701301744l76a2b283ycfed5796a3bda19d@mail.gmail.com>
References: <8249c4ac0701301744l76a2b283ycfed5796a3bda19d@mail.gmail.com>
Message-ID: <45C00656.8090803@tds.net>

Tony Cappellini wrote:
> 
> 
> I want to purge (empty) or delete the logfile created by the logging 
> module, and reopen it for a new session.
> 
> There is reference to a close function in the 2.3 docs, but I don't see 
> how I can purge or delete the file, since I don't have access to the 
> file descriptor.
> 
> *close*( 	)
> 
>     Tidy up any resources used by the handler. This version does nothing
>     and is intended to be implemented by subclasses. 
> 
> How can I purge/delete & reopen the logfile?

FileHandler has a close() method that presumably does something useful. 
So I guess you have to get ahold of the FileHandler. One way to do that 
would be to configure the logging in code instead of in a config file or 
basicConfig(). There is an example of doing this with a SocketHandler here:
http://docs.python.org/lib/network-logging.html

The code to set up a FileHandler would be very similar.

Kent


From cappy2112 at gmail.com  Wed Jan 31 04:15:28 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Tue, 30 Jan 2007 19:15:28 -0800
Subject: [Tutor] Purging/deleting the logfile with the logging module
In-Reply-To: <45C00656.8090803@tds.net>
References: <8249c4ac0701301744l76a2b283ycfed5796a3bda19d@mail.gmail.com>
	<45C00656.8090803@tds.net>
Message-ID: <8249c4ac0701301915o4681b6b4ybfa17ab31aaf0abe@mail.gmail.com>

> *close*(      )

> >
> >     Tidy up any resources used by the handler. This version does nothing
> >     and is intended to be implemented by subclasses.
> >
> > How can I purge/delete & reopen the logfile?
>
> >>FileHandler has a close() method that presumably does something useful.


see above-
It says it does nothing, but it does close the file. This is the first step.

Will see what the socket handler does.

thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070130/f113a8c2/attachment.htm 

From kent37 at tds.net  Wed Jan 31 04:30:08 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 30 Jan 2007 22:30:08 -0500
Subject: [Tutor] Purging/deleting the logfile with the logging module
In-Reply-To: <8249c4ac0701301915o4681b6b4ybfa17ab31aaf0abe@mail.gmail.com>
References: <8249c4ac0701301744l76a2b283ycfed5796a3bda19d@mail.gmail.com>	
	<45C00656.8090803@tds.net>
	<8249c4ac0701301915o4681b6b4ybfa17ab31aaf0abe@mail.gmail.com>
Message-ID: <45C00D40.8040507@tds.net>

Tony Cappellini wrote:
>  > *close*(      )
> 
>      >
>      >     Tidy up any resources used by the handler. This version does
>     nothing
>      >     and is intended to be implemented by subclasses.
>      >
>      > How can I purge/delete & reopen the logfile?
> 
>      >>FileHandler has a close() method that presumably does something
>     useful.
> 
> 
> see above-
> It says it does nothing, but it does close the file. This is the first step.

The docs for FileHandler.close() say, "Closes the file."
> 
> Will see what the socket handler does.

I'm not suggesting that you use SocketHandler, only that the example on 
that page might be useful. Use FileHandler instead of SocketHandler.

Kent
> 
> thanks
> 
> 
>  
> 
> 



From anup.rao at philips.com  Wed Jan 31 09:04:24 2007
From: anup.rao at philips.com (Anup Rao)
Date: Wed, 31 Jan 2007 13:34:24 +0530
Subject: [Tutor] Regarding licensing GPL terms
In-Reply-To: <mailman.10197.1170135751.32030.tutor@python.org>
Message-ID: <OF6A94BF84.30C97BF5-ON65257274.002BF49F-65257274.002C93AF@philips.com>

Hi,

I am writing an application that uses a python libary  (a *.so file) 
generated using SWIG.
This library  makes direct system calls to the Linux kernel. 
This raises three questions.

a> Does this mean that the library must be distributed under GPL terms?

b> Can I distribute it as LGPL?

c> Also, does any python script that uses this module have to be 
distributed under GPL , LGPL, or is the PSF license sufficient? 
     My preference would be the PSF but I am not sure if it is ok.


Regards,
Anup 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070131/385019d5/attachment.html 

From klappnase at freenet.de  Wed Jan 31 11:42:11 2007
From: klappnase at freenet.de (Michael Lange)
Date: Wed, 31 Jan 2007 11:42:11 +0100
Subject: [Tutor] Regarding licensing GPL terms
In-Reply-To: <OF6A94BF84.30C97BF5-ON65257274.002BF49F-65257274.002C93AF@philips.com>
References: <mailman.10197.1170135751.32030.tutor@python.org>
	<OF6A94BF84.30C97BF5-ON65257274.002BF49F-65257274.002C93AF@philips.com>
Message-ID: <20070131114211.1b42fb13.klappnase@freenet.de>

On Wed, 31 Jan 2007 13:34:24 +0530
Anup Rao <anup.rao at philips.com> wrote:

> Hi,
> 
> I am writing an application that uses a python libary  (a *.so file) 
> generated using SWIG.
> This library  makes direct system calls to the Linux kernel. 
> This raises three questions.
> 
> a> Does this mean that the library must be distributed under GPL terms?
> 
> b> Can I distribute it as LGPL?
> 
> c> Also, does any python script that uses this module have to be 
> distributed under GPL , LGPL, or is the PSF license sufficient? 
>      My preference would be the PSF but I am not sure if it is ok.
> 
> 

Hi Anup,

maybe it is not the perfect place for this question here :)

You could start looking here:

http://www.gnu.org/philosophy/license-list.html

This page also contains a contact address that seems to be what you need:

<quote>
If you want help choosing a license, evaluating a license, or have any other questions about licenses, you can email us at <licensing at gnu.org>.
</quote>

I hope this helps

Michael


From anball at gmail.com  Wed Jan 31 12:04:01 2007
From: anball at gmail.com (Andrew Ball)
Date: Wed, 31 Jan 2007 06:04:01 -0500
Subject: [Tutor] Fwd:  Regarding licensing GPL terms
In-Reply-To: <b3bd3a9d0701310122v6135d6f5jfb85a561cc895fa7@mail.gmail.com>
References: <mailman.10197.1170135751.32030.tutor@python.org>
	<OF6A94BF84.30C97BF5-ON65257274.002BF49F-65257274.002C93AF@philips.com>
	<b3bd3a9d0701310122v6135d6f5jfb85a561cc895fa7@mail.gmail.com>
Message-ID: <b3bd3a9d0701310304g19e51071h4bf5ac4cf17b458@mail.gmail.com>

Forwarding this to the list in case it didn't make it there earlier.

If you're doing this for work or school, please contact any IP lawyers
your organization with your questions.  Nonetheless, this information
and the link from Michael Lange should help.

Excellent book:

http://www.amazon.com/Open-Source-Licensing-Software-Intellectual/dp/0131487876/sr=8-1/qid=1170241424/ref=pd_bbs_sr_1/104-1060065-2524701?ie=UTF8&s=books

---------- Forwarded message ----------
From: Andrew Ball <anball at gmail.com>
Date: Jan 31, 2007 4:22 AM
Subject: Re: [Tutor] Regarding licensing GPL terms
To: Anup Rao <anup.rao at philips.com>



On 1/31/07, Anup Rao <anup.rao at philips.com> wrote:
>
>
> Hi,
>
> I am writing an application that uses a python libary  (a *.so file)
> generated using SWIG.
> This library  makes direct system calls to the Linux kernel.


That generally means that it uses libc, which makes syscalls via software
interrupts.
libc is under the Lesser GNU Public License,


This raises three questions.
>
> a> Does this mean that the library must be distributed under GPL terms?


No.


b> Can I distribute it as LGPL?


Yes.


c> Also, does any python script that uses this module have to be distributed
> under GPL , LGPL, or is the PSF license sufficient?
>      My preference would be the PSF but I am not sure if it is ok.


I think that you're free to choose the license for your module -- at least
PSF or LPGL
should work.


Good luck!

Be sure to check with a local expert -- I may be missing some details.

Peace.
Andrew

Regards,
> Anup
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
=======================
Andrew D. Ball
???
anball at gmail.com
http://filebox.vt.edu/~anball1/ <http://filebox.vt.edu/%7Eanball1/>
"Festina lente" $\approx$ "Make haste slowly"
    -- Caesar Augustus

-- 
=======================
Andrew D. Ball
???
anball at gmail.com
http://filebox.vt.edu/~anball1/
"Festina lente" $\approx$ "Make haste slowly"
    -- Caesar Augustus
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070131/57feffd4/attachment.htm 

From kent37 at tds.net  Wed Jan 31 12:08:23 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 31 Jan 2007 06:08:23 -0500
Subject: [Tutor] Regarding licensing GPL terms
In-Reply-To: <OF6A94BF84.30C97BF5-ON65257274.002BF49F-65257274.002C93AF@philips.com>
References: <OF6A94BF84.30C97BF5-ON65257274.002BF49F-65257274.002C93AF@philips.com>
Message-ID: <45C078A7.4040901@tds.net>

Anup Rao wrote:
> 
> Hi,
> 
> I am writing an application that uses a python libary  (a *.so file) 
> generated using SWIG.
> This library  makes direct system calls to the Linux kernel.
> This raises three questions.
> 
> a> Does this mean that the library must be distributed under GPL terms?

I don't think so. I believe Linux has a library exception to the GPL 
that permits linking against it, though I can't find a reference to this 
at the moment.
> 
> b> Can I distribute it as LGPL?

I think so.
> 
> c> Also, does any python script that uses this module have to be 
> distributed under GPL , LGPL, or is the PSF license sufficient?
>      My preference would be the PSF but I am not sure if it is ok.

The PSF itself discourages using the PSF license for non-PSF code. You 
should probably consider a BSD or MIT license if you want something more 
liberal than LGPL.

I am not a lawyer and I could be wrong!

Kent


From anball at gmail.com  Wed Jan 31 12:54:25 2007
From: anball at gmail.com (Andrew Ball)
Date: Wed, 31 Jan 2007 06:54:25 -0500
Subject: [Tutor] Regarding licensing GPL terms
In-Reply-To: <OF27B4EBBA.99FD2ED9-ON65257274.00410ED7-65257274.004126FE@philips.com>
References: <b3bd3a9d0701310122v6135d6f5jfb85a561cc895fa7@mail.gmail.com>
	<OF27B4EBBA.99FD2ED9-ON65257274.00410ED7-65257274.004126FE@philips.com>
Message-ID: <b3bd3a9d0701310354m29b7327dw3f29873433c1f2bf@mail.gmail.com>

Cool!

Do you know about rpath/conary?  It may not be worth tons here, but
it is good for custom Linux distributions.

http://www.rpath.com/corp/

On 1/31/07, Anup Rao <anup.rao at philips.com> wrote:
>
>
> Hi Andrew,
>
> A minor correction in the URL
>
> it is  *http://sarovar.org/projects/pylinux/*
>
> Sorry for the inconvenience.
>
> Regards
> Anup
>



-- 
=======================
Andrew D. Ball
???
anball at gmail.com
http://filebox.vt.edu/~anball1/
"Festina lente" $\approx$ "Make haste slowly"
    -- Caesar Augustus
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070131/0f79e557/attachment.htm 

From zebra05 at gmail.com  Wed Jan 31 13:34:09 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Wed, 31 Jan 2007 14:34:09 +0200
Subject: [Tutor] youtube & yelp
Message-ID: <c7c6f3bc0701310434yd2cc9bbw59d98fa9f8068cef@mail.gmail.com>

Hi folks,

im of the beaten path here, but does anyone know what frameworks YouTube and
Yelp use? i know/ read that they use python.

Thankee

"shortash"

-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070131/dcd83b66/attachment.html 

From David.Barton at nottingham.ac.uk  Wed Jan 31 14:16:03 2007
From: David.Barton at nottingham.ac.uk (Barton David)
Date: Wed, 31 Jan 2007 13:16:03 -0000
Subject: [Tutor] Generating all possible hits of a regex pattern
Message-ID: <BAA2EE790D828F4E8B262F17B3B0A7A302CAEE0F@VUIEXCH1.ad.nottingham.ac.uk>

I don't suppose there's a nifty trick (exploiting the internal workings
of the re module perhaps) to generate all possible hits of a given regex
pattern?
 
Something like:
 
>>> import re
>>> mypattern=re.compile( "[AB]C{1,2}D?" )
>>> print list( all_pattern_generator( mypattern ) )
["AC","BC","ACC","BCC","ACD","BCD","ACCD","BCCD"]
 
Or would I have to do this the hard way, parsing the expression myself
etc?
 
I suppose you might have to be a little careful what expression you put
into this: "A*" would produce an infinite number of results. But if it
was in a generator function that wouldn't necessarily be a problem,
and/or perhaps I could pre-check 'mypattern' and warn if it was.
 
cheers
Dave
 
 
 
 
 
 

This message has been checked for viruses but the contents of an attachment
may still contain software viruses, which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070131/4e6a25e1/attachment.htm 

From kent37 at tds.net  Wed Jan 31 14:35:51 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 31 Jan 2007 08:35:51 -0500
Subject: [Tutor] Generating all possible hits of a regex pattern
In-Reply-To: <BAA2EE790D828F4E8B262F17B3B0A7A302CAEE0F@VUIEXCH1.ad.nottingham.ac.uk>
References: <BAA2EE790D828F4E8B262F17B3B0A7A302CAEE0F@VUIEXCH1.ad.nottingham.ac.uk>
Message-ID: <45C09B37.606@tds.net>

Barton David wrote:
> I don't suppose there's a nifty trick (exploiting the internal workings 
> of the re module perhaps) to generate all possible hits of a given regex 
> pattern?
>  
> Something like:
>  
>> >> import re
>> >> mypattern=re.compile( "[AB]C{1,2}D?" )
>> >> print list( all_pattern_generator( mypattern ) )
> ["AC","BC","ACC","BCC","ACD","BCD","ACCD","BCCD"]
>  
> Or would I have to do this the hard way, parsing the expression myself etc?

See this discussion:
http://tinyurl.com/22xsxg

Kent


From gamito at gmail.com  Wed Jan 31 21:06:50 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Wed, 31 Jan 2007 20:06:50 +0000
Subject: [Tutor] Is there anyone running planetplanet (coded in Python) ?
Message-ID: <45C0F6DA.5050704@gmail.com>

Hi,

I'm running planetplanet and i'd like to add archiving and pagination to 
the software.

I intend to use MySQL to store the feeds information and already 
installed python-MySQLdb.

I'm not much of a Python programmer.
My problem is that i can't see very well where are the variables that 
hold the feeds info.

My bet is that the best solution is to hack cache.py file, but i'm not sure.

Any help would be appreciated.

Warm Regards,
M?rio Gamito

From kent37 at tds.net  Wed Jan 31 21:30:04 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 31 Jan 2007 15:30:04 -0500
Subject: [Tutor] Is there anyone running planetplanet (coded in Python) ?
In-Reply-To: <45C0F6DA.5050704@gmail.com>
References: <45C0F6DA.5050704@gmail.com>
Message-ID: <45C0FC4C.4000504@tds.net>

M?rio Gamito wrote:
> Hi,
> 
> I'm running planetplanet and i'd like to add archiving and pagination to 
> the software.

You will probably do better asking this on the planet developer list:
http://lists.planetplanet.org/mailman/listinfo/devel

Kent


From frank.hoffsummer at gmail.com  Wed Jan 31 21:34:47 2007
From: frank.hoffsummer at gmail.com (frank h.)
Date: Wed, 31 Jan 2007 21:34:47 +0100
Subject: [Tutor] local daynames in unicode
Message-ID: <60fae7c30701311234t5256e4d0n6cf003c5e5db80b7@mail.gmail.com>

Hello all,
using python 2.4.4, I have the following session on Mac OS X:

import datetime, locale
locale.setlocale(locale.LC_ALL, 'se_SE')
t=datetime.date(2007,01,29).strftime("%A")
t
'M?\xa5ndag'
type(t)
<type 'str'>
t.decode('utf8')
u'M\xe5ndag'

fantastic! I just got the unicode version of the swedish name for "Monday"

now I want to do the same on my PC (also python 2.4.4)

import datetime, locale
locale.setlocale(locale.LC_ALL, 'swedish')
t=datetime.date(2007,01,29).strftime("%A")
t
'm\xa5ndag'
type(t)
<type 'str'>
t.decode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "c:\Python24\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-3: invalid
data

...ups?!?! how can that be? what am I doing wrong? I just don't get it
thanks for any insight you might have!!
-frank
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070131/48dc3e5e/attachment.htm 

From gamito at gmail.com  Wed Jan 31 21:45:52 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Wed, 31 Jan 2007 20:45:52 +0000
Subject: [Tutor] Is there anyone running planetplanet (coded in Python) ?
In-Reply-To: <45C0FC4C.4000504@tds.net>
References: <45C0F6DA.5050704@gmail.com> <45C0FC4C.4000504@tds.net>
Message-ID: <45C10000.3040301@gmail.com>

Hi Kent,

> You will probably do better asking this on the planet developer list:
> http://lists.planetplanet.org/mailman/listinfo/devel
Already did.
No reply.

Regards,
M?rio Gamito

From gamito at gmail.com  Wed Jan 31 20:14:50 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Wed, 31 Jan 2007 19:14:50 +0000
Subject: [Tutor] Is there anyone running planetplanet (coded in Python) ?
Message-ID: <45C0EAAA.30209@gmail.com>

Hi,

I'm running planetplanet and i'd like to add archiving and pagination to 
the software.

I intend to use MySQL to store the feeds information and already 
installed python-MySQLdb.

I'm not much of a Python programmer.
My problem is that i can't see very well where are the variable that 
hold the feeds info.

My bet is that the best solution is to hack cache.py file, but i'm not sure.

Any help would be appreciated.

Warm Regards,
M?rio Gamito

From gamito at gmail.com  Wed Jan 31 20:15:01 2007
From: gamito at gmail.com (=?ISO-8859-1?Q?M=E1rio_Gamito?=)
Date: Wed, 31 Jan 2007 19:15:01 +0000
Subject: [Tutor] Is there anyone running planetplanet (coded in Python) ?
Message-ID: <45C0EAB5.7040204@gmail.com>

Hi,

I'm running planetplanet and i'd like to add archiving and pagination to 
the software.

I intend to use MySQL to store the feeds information and already 
installed python-MySQLdb.

I'm not much of a Python programmer.
My problem is that i can't see very well where are the variables that 
hold the feeds info.

My bet is that the best solution is to hack cache.py file, but i'm not sure.

Any help would be appreciated.

Warm Regards,
M?rio Gamito

From frank.hoffsummer at gmail.com  Wed Jan 31 22:35:42 2007
From: frank.hoffsummer at gmail.com (frank h.)
Date: Wed, 31 Jan 2007 22:35:42 +0100
Subject: [Tutor] local daynames in unicode
In-Reply-To: <60fae7c30701311234t5256e4d0n6cf003c5e5db80b7@mail.gmail.com>
References: <60fae7c30701311234t5256e4d0n6cf003c5e5db80b7@mail.gmail.com>
Message-ID: <60fae7c30701311335t4cdb8a7an5f632ecd9a5d80e@mail.gmail.com>

hm I guess I found an answer myself

on windows, the default encoding is not 'utf8'
thus, if I use

encoding = locale.getlocale()[1]
t.decode(encoding)

instead of

t.decode('utf8')

it works

On 1/31/07, frank h. <frank.hoffsummer at gmail.com> wrote:
>
> Hello all,
> using python 2.4.4, I have the following session on Mac OS X:
>
> import datetime, locale
> locale.setlocale(locale.LC_ALL, 'se_SE')
> t=datetime.date(2007,01,29).strftime("%A")
> t
> 'M?\xa5ndag'
> type(t)
> <type 'str'>
> t.decode('utf8')
> u'M\xe5ndag'
>
> fantastic! I just got the unicode version of the swedish name for "Monday"
>
> now I want to do the same on my PC (also python 2.4.4)
>
> import datetime, locale
> locale.setlocale(locale.LC_ALL, 'swedish')
> t=datetime.date(2007,01,29).strftime("%A")
> t
> 'm\xa5ndag'
> type(t)
> <type 'str'>
> t.decode('utf8')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "c:\Python24\lib\encodings\utf_8.py", line 16, in decode
>     return codecs.utf_8_decode(input, errors, True)
> UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-3:
> invalid data
>
> ...ups?!?! how can that be? what am I doing wrong? I just don't get it
> thanks for any insight you might have!!
> -frank
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070131/de56c351/attachment.htm