From alan.gauld@bt.com  Mon Jul  1 00:06:58 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 1 Jul 2002 00:06:58 +0100
Subject: [Tutor] Matrix class problems
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6C7@mbtlipnt02.btlabs.bt.co.uk>

>     Firstly, I would like to know what exactly repr() does. I read the
> docs, and this is what I got :
> ...
> Return the canonical string representation of the object.
> For most object types, eval(repr(object)) == object.
> """
> 
> What does this mean and how is this different from str() ?

repr is a pythonic representation of an object as a string.
str is a human readable version.

You can see the difference at the prompt by typing values 
with and without the print command:

>>> print 5   # uses str()
5
>>> 5         # uses repr()
5
>>>  # the above are identical
>>> s = "Hello world"
>>> print s
Hello world
>>> s
"Hello world"
>>> # notice repr added qutes whereas str didn't

Coming back to the doc string comment consider what 
happens with eval:

eval(Hello world)  # error, looks for variables called hello & world
eval ("Hello world")   # works. It gives us a string back

Hope that makes the diffrence a bt clearer

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From kalle@lysator.liu.se  Mon Jul  1 01:09:17 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Mon, 1 Jul 2002 02:09:17 +0200
Subject: [Tutor] [OT] TECO and Emacs (Was: pair programming.)
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6C3@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6C3@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020701000917.GA1912@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[alan.gauld@bt.com]
> > The biggest problem with modality in vi*'s is that you may be in
> > command mode but think you're in insert and type some stuff which
> > will garble your text in a scary random-looking manner. 
> 
> > I myself never found this to be much of a problem, but I know some
> > people do..
> 
> Those folks obviously never used Tico... ;-)
> 
> The standard programmers game in Tico was to type your name and 
> try to guess what the effect would be on your code(*)! The only good 
> thing I can say about Tico is that it was so bad it drove 
> James Gosling to invent the original Emacs!

I think you mean TECO.  Also, Gosling didn't write the first Emacs.
Richard M. Stallman did that, merging two existing TECO macro
packages.  Gosling wrote the first implementation of Emacs in C.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9H51ndNeA1787sd0RAiWgAJsFoQVjuPc3f7OLdkeYhkd41AOpSQCfbtJ+
KPwATVaoV1rIlc9x/FuR59o=
=z3Y/
-----END PGP SIGNATURE-----



From ak@silmarill.org  Mon Jul  1 08:13:53 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 1 Jul 2002 03:13:53 -0400
Subject: [Tutor] random distribution question
Message-ID: <20020701071353.GA9208@ak.silmarill.org>

Hello tutors,

I have a tough and interesting problem here, I think..

In my player cymbaline, each track has a score from 0 to 100; tracks
with high scores play more often in random mode. There is a setting
called random slope that dictates just how much more often they play.

Here's how it was implemented until now:

runs = 0
while 1:
    n = -5
    for i in range(slope):
	n = random.randrange(n, 101)
    track = random.choice(rand_list)
    if track.score >= n or runs > 50:
	break
    runs += 1

slope was an int from 1 to 5. The higher it is, more likely would
high-scored tracks play, but I'm not too sure just how much more
likely..

Now I'm re-hauling all of the code (most of it is 1-2 years old).

Here's what I came up with:

import random, operator
slope = 1
runs = 0
c = []
for i in range(10):
    while 1:
	n = -5
	n = random.randrange(n, 101)
	left = 100 - n
	cutoff = n + left*slope/11
	c.append(cutoff)
	if runs>50:
	    break
	runs += 1

    csum = reduce(operator.add, c)
    print "avg is ", csum/len(c)

Where slope is from 0 to 10.

To be honest, I have a hard time even stating what the uniform
distribution should be like here. At slope=5, should top 10% of scores
be picked 5 times more often than bottom 10%? I guess at slope=1, we
want the lowest possible difference that'd still be notable to the
user, that would perhaps be 100score be 2 times more likely to be
picked than 0 score, and uniformly increasing from ~1.1 at 1score to
~1.9 at 99score.

At 10slope, let's say 100 times more likely to pick 100score than
0score, uniformly increasing from 0 to 100.

And this relation has to also uniformly increase for 1=>10 slope.

I looked at random module and there's a bunch of distribution functions
but I'm not sure if any of them would apply here.

Anybody got any ideas on this?

Thanks,

 - Andrei

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From csmith@blakeschool.org  Mon Jul  1 14:11:16 2002
From: csmith@blakeschool.org (Christopher Smith)
Date: Mon, 01 Jul 2002 08:11:16 -0500
Subject: [Tutor] Matrix class problems
Message-ID: <fc.004c4b6b009eae14004c4b6b009eae14.9eae80@blakeschool.org>

>[Tutor] Matrix class problems
>
>Hi,
>
>    I have recently got back to exploring python, and, being a Maths
>student, I decided to test my skills on a simple Matrix class. Now, I
>came across some questions which I hope you will help clear.
<cut>
>
>Also, I wrote a __mul__() function, which looks like so :
>
>"""
>    def __mul__ (self, other) :
>        if type(other) == type(0) :
>            return self._scalar_multiply(other)
>        else :
>            return self._matrix_multiply(other)
>"""
>
<cut>
>
>>>> print (m*2) 
>[ 2, 0, 0 ]
>[ 0, 2, 0 ]
>[ 0, 0, 2 ]
>>>> print (2*m) 
>Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>TypeError: unsupported operand type(s) for *: 'int' and 'instance'
>
>"""
>
>    I understand that, in the first case, I am calling the function I
>wrote, but in the second case I am calling the equivalent __mul__
>function of an 'int' object. My question is, how do I make the latter
>point to the former ? Although this is not a major issue, it bugs me
>because I tend to write the number first, and the matrix later by habit.
>
>    I hope I have been clear enough.

Try defining the __rmul__ method which is called whenever an 
instance of your class is the *right* operand and the left operand is 
not an instance:

class m:
	def __init__(self,x):
		self.x = x
	def __mul__(self,y):
		print "do mul"
	def __rmul__(self,y):
		print "do rmul"

a = m(2)
2*a #rmul <<----
a*2 #mul
a*a #mul

'''
output:
	do rmul
	do mul
	do mul
'''
>
>pv.
>
>ps. For those of you who study Maths, I have been racking my brains as
>to how to get the determinant of a Matrix, and have been unsuccessful.
>
>How do I find the minor matrix ? Aaaarggghhh !!

When I was on that rack my kind math teacher reminded me 
that by reducing the matrix to an upper diagonal form through the 
swapping, multiplying, and adding rows together the determinant is 
found as the product of the diagonal.

1	2
2	3	det = 3-4 = -1

subtract 2*row1 from row2:

1	2
0	-1	det = 1*-1 = -1

You can find such algorithms in Gauss elimination routines.

/c




From terjeja@hotmail.com  Mon Jul  1 15:52:54 2002
From: terjeja@hotmail.com (Terje Johan Abrahamsen)
Date: Mon, 01 Jul 2002 14:52:54 +0000
Subject: [Tutor] Dictionaries [lists]
Message-ID: <F155xmxqjcyPUn2v7Vg00002d01@hotmail.com>

Hello and thank you so much,

    I got it up and running now. This would probably have taken me just 
about forever before I had been able to figure it out by myself....

Have a great day,
Terje


>From: "Gregor Lingl" <glingl@aon.at>
>To: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>,"Terje Johan Abrahamsen" 
><terjeja@hotmail.com>
>CC: <tutor@python.org>
>Subject: Re: [Tutor] Dictionaries    [lists]
>Date: Sat, 29 Jun 2002 10:24:08 +0200
>
>
>----- Original Message -----
>From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
>To: "Terje Johan Abrahamsen" <terjeja@hotmail.com>
>Cc: <tutor@python.org>
>
>I'll post below one small correction of a type in Danny's explanation
>- and a slightly different version of his code. Therefore do also
>
> > Skip if you don't want to be spoiled.  *grin*
> >
> > *** Spoiler space ahead ***
> >
> >
> >
> >
> >
> >
> >
> >
> >
> >
> >
> >
> >
> >
> >
> >
> > *** Spoiler space ***
> >
> > ###
> > def allSums(numbers):
> >     """Returns all possible sums of any nonempty subset of elements
> > in 'numbers'."""
> >     possible_sums = [numbers[0]]
> >     for n in numbers[1:]:
> >         possible_sums.extend([n + sum for sum in possible_sums])
> >         possible_sums.append(n)
> >     return possible_sums
> > ###
> >
> >
> > How would this calculate allSums([3, 4, 5])?
> >
> > It first tries to figure out allSums([3]), and this one is really easy.
> >
> >     allSums([3]) == [3]
> >
> > There's only one sum involved here, so we can just say that if we're
> > trying to find all possible sums from [3], that just comes out to [3].
> >
> >
> > The second answer ia also pretty easy: if we know allSums([3]), then we
> > can either add 4, or not add 4, or start off a new sum by using 4:
> >
> >     allSums([3, 4]) ==
> >         ... Just the values of allSums([3])
> >
> >         ... plus all the results of:  [(4 + sum)
> >                                        for sum in allSums([3])]
> >         ... plus just plain "4".
> >
> >
> > The third answer is also pretty easy: if we know allSums([3, 4]), then 
>we
> > can either add 5, or not add 5, or start off a new sum by using 5:
> >
> >     allSums([3, 4, 5]) ==
> >         ... Just the values of allSums([3, 4])
>
>##################################
> >         ... plus all the results of:  [(5 + sum)   ## correction: here 5
>instead of 4
>
>##################################
> >                                        for sum in allSums([3, 4])]
> >         ... plus just plain "5".
> >
>
>If you don't mind to include 0 as the sum of the empty list, you may code
>it - slightly more compact - this way:
>
>def allSums(numbers):
>     """Returns all possible sums of any subset of elements in 
>'numbers'."""
>     possible_sums = [0]
>     for n in numbers:
>         possible_sums.extend([n + sum for sum in possible_sums])
>     return possible_sums
>
>     # However, if you don't like this first "0", you should
>     # return possible_sums[1:]




_________________________________________________________________
Join the world’s largest e-mail service with MSN Hotmail. 
http://www.hotmail.com




From shendric@arches.uga.edu  Mon Jul  1 17:29:55 2002
From: shendric@arches.uga.edu (shendric@arches.uga.edu)
Date: Mon,  1 Jul 2002 11:29:55 -0500
Subject: [Tutor] Mac and Tkinter
Message-ID: <1025537395.smmsdV1.1.1@mail.arches.uga.edu>

Hi all,

Are there any MacPython folks out there who might have tried to use 
Tkinter?  I'm primarily a Windows programmer, but I wanted to make a Mac 
version of a little application I wrote.  It involves Tkinter, but when 
I try to run the program, it tells me that "Tkinter not supported under 
Carbon (yet)".  I've heard of Carbon, but I've no experience with it.  
Does anyone have any suggestions for places I should look for more 
information on this issue?  I've been to the MacPython page, but still 
no luck.  I'm probably looking in the wrong places.

Sean





From scott@zenplex.com  Mon Jul  1 16:42:45 2002
From: scott@zenplex.com (Scott Comboni)
Date: 01 Jul 2002 11:42:45 -0400
Subject: [Tutor] Progress Bar Help.
In-Reply-To: <20020628211827.GB12819@marcolab.proconet>
References: <1025291948.3126.7.camel@scott.zenplex.com>
 <20020628211827.GB12819@marcolab.proconet>
Message-ID: <1025538166.2890.21.camel@scott.zenplex.com>

Thanks I will take a look.
Scott

On Fri, 2002-06-28 at 17:18, Marc wrote:
> Scott Comboni (scott@zenplex.com) wrote:
> 
> > I recently wrote a simple python script to install a bunch of software
> > apps and would like to jazz it up with some sort of graphical progress
> > bar.  Is there some URL someone can point me too to get some ideas on
> > how to code/create something like this?
> 
> You may find this module useful:
> http://www.chrisarndt.de/software/python/#xdialog
> 
> It's a wrapper for the great Xdialog program ,that, among other
> things, have a progress bar example.
> Hope that helps.
> 
> -- 
> I SeE NeRD pEoPle.
> .:: MarcoLinux ::.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
-- 
_________




From dyoo@hkn.eecs.berkeley.edu  Mon Jul  1 17:51:55 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 1 Jul 2002 09:51:55 -0700 (PDT)
Subject: [Tutor] Dictionaries [lists]
In-Reply-To: <F155xmxqjcyPUn2v7Vg00002d01@hotmail.com>
Message-ID: <Pine.LNX.4.44.0207010941490.22613-100000@hkn.eecs.berkeley.edu>


On Mon, 1 Jul 2002, Terje Johan Abrahamsen wrote:

> I got it up and running now. This would probably have taken me just
> about forever before I had been able to figure it out by myself....

I'm glad it works now!


If you want to look at this problem more, you can pick up any CS textbook
on the topic of "change-making".  Change-making is the problem of trying
to make change out of an unlimited number of quarters, dimes, nickels, and
pennies --- it's a "classic" problem that CS students hear about when
they're introducted to dynamic programming.

Here's one link that talks about the problem:

http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_idx_728

What you were working on is almost exactly like change-making, except that
we're using a limited number of coins.


Best of wishes to you!




From dyoo@hkn.eecs.berkeley.edu  Mon Jul  1 18:03:20 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 1 Jul 2002 10:03:20 -0700 (PDT)
Subject: [Tutor] Mac and Tkinter
In-Reply-To: <1025537395.smmsdV1.1.1@mail.arches.uga.edu>
Message-ID: <Pine.LNX.4.44.0207010953570.22613-100000@hkn.eecs.berkeley.edu>


On Mon, 1 Jul 2002 shendric@arches.uga.edu wrote:

> Are there any MacPython folks out there who might have tried to use
> Tkinter?  I'm primarily a Windows programmer, but I wanted to make a Mac
> version of a little application I wrote.  It involves Tkinter, but when
> I try to run the program, it tells me that "Tkinter not supported under
> Carbon (yet)".  I've heard of Carbon, but I've no experience with it.
> Does anyone have any suggestions for places I should look for more
> information on this issue?  I've been to the MacPython page, but still
> no luck.  I'm probably looking in the wrong places.

Hi Sean,

I'm not too familiar with Mac OS X either, but I think that Carbon is a
compatibility layer to make it easy to port older, OS 9-based programs.

I did a quick look on the "pythonmac" Special Interest Group, and Tony
Lownds's packaging of Python 2.2 appears to have native Tkinter working!

    http://tony.lownds.com/macosx/
    http://sourceforge.net/project/showfiles.php?group_id=10894

It's still experimental, so you might run into a few snags, but it sounds
like it works.  Hey, there's one more reason to try out a Mac.  *grin*


You may want to subscribe to pythonmac-sig and ask your question there
too; they're probably much more knowledgable about this.  Here's a link to
their mailing list:

    http://mail.python.org/mailman/listinfo/pythonmac-sig



Best of wishes to you!




From alan.gauld@bt.com  Mon Jul  1 18:09:41 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 1 Jul 2002 18:09:41 +0100
Subject: [Tutor] drag-and-drop argument passing
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6D3@mbtlipnt02.btlabs.bt.co.uk>

------_=_NextPart_001_01C22122.16EA8C70
Content-type: text/plain; charset="iso-8859-1"

 > Now, there is only one thing left in my way, but it is very vexing.  
 
>  I don't know how to generate raw strings on the fly.  
>  For example: this path would choke my script,  
>  because "\f" is a token: 
>  >>> "c:\ftp\test.txt" 
 
So use forward slashes Unix style.
 
If reading from a user raw_input will correctly escape 
the backslashes for you:
 
C:\\ftp\\test.txt
 
 >   But how do I turn a string in a list, like sys.argv[], into a raw
string?  
 >  for path in sys.argv[1:]:
 >       make_raw(path) 
 
Aha! Good example. Tricky that one, I don't know!
 
I look forward to seeing an answer.
 
Alan G

------_=_NextPart_001_01C22122.16EA8C70
Content-type: text/html; charset="iso-8859-1"

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">


<META content="MSHTML 5.50.4807.2300" name=GENERATOR></HEAD>
<BODY>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;&gt; </FONT></SPAN>Now, there is only one thing left in my way, but 
it is very vexing.&nbsp;<SPAN class=970570117-01072002><FONT face="Courier New" 
color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>I don't know how to generate raw strings on the 
fly.&nbsp;<SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>For example: this path would choke my 
script,&nbsp;<SPAN class=970570117-01072002><FONT face="Courier New" 
color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>because "\f" is a token:<SPAN 
class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>&gt;&gt;&gt; "c:\ftp\test.txt"<SPAN 
class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>So use forward slashes Unix style.</FONT></SPAN></DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>If reading from a user raw_input will correctly escape 
</FONT></SPAN></DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>the backslashes for you:</FONT></SPAN></DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>C:\\ftp\\test.txt</FONT></SPAN></DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=970570117-01072002><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;&gt; </FONT>&nbsp; </SPAN>But how do I turn a string in a list, 
like sys.argv[], into a raw string?&nbsp;<SPAN class=970570117-01072002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=970570117-01072002><FONT face="Courier New" 
color=#0000ff size=2>&nbsp;&gt; &nbsp;</FONT></SPAN>for path in 
sys.argv[1:]:</DIV>
<DIV dir=ltr><SPAN class=970570117-01072002><FONT face="Courier New" 
color=#0000ff size=2>&nbsp;&gt;&nbsp;</FONT></SPAN>&nbsp;&nbsp;&nbsp;&nbsp;<SPAN 
class=970570117-01072002><FONT face="Courier New" color=#0000ff size=2>&nbsp; 
</FONT></SPAN>make_raw(path)<SPAN class=970570117-01072002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=970570117-01072002><FONT face="Courier New" 
color=#0000ff size=2></FONT></SPAN>&nbsp;</DIV>
<DIV dir=ltr><SPAN class=970570117-01072002><FONT face="Courier New" 
color=#0000ff size=2>Aha! </FONT></SPAN><SPAN class=970570117-01072002><FONT 
face="Courier New" color=#0000ff size=2>Good example. Tricky that one, I don't 
know!</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=970570117-01072002></SPAN><FONT face="Courier New" 
color=#0000ff size=2></FONT>&nbsp;</DIV>
<DIV dir=ltr><FONT face="Courier New"><FONT color=#0000ff size=2><SPAN 
class=970570117-01072002>I look forward to seeing an 
answer.</SPAN></FONT></FONT></DIV>
<DIV dir=ltr><FONT face="Courier New"><FONT color=#0000ff size=2><SPAN 
class=970570117-01072002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV dir=ltr><FONT face="Courier New"><FONT color=#0000ff size=2><SPAN 
class=970570117-01072002>Alan G</SPAN></FONT></FONT></DIV></BODY></HTML>

------_=_NextPart_001_01C22122.16EA8C70--



From alan.gauld@bt.com  Mon Jul  1 18:12:26 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 1 Jul 2002 18:12:26 +0100
Subject: [Tutor] Re: pair programming.
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6D4@mbtlipnt02.btlabs.bt.co.uk>

> Those folks obviously never used Tico... ;-)

Old age is catching up. Its been pointed out that it was 
actually called teco.

ONe of the more interesting features was that it didn't 
display a cursor so you just had to remember where the 
cursor should be....

> PS Anyone on a Vax running VMS can still experience Tico by typing
> EDIT/TICO at a DCL prompt - Good luck!!

So that'll be EDIT/TECO

Alan g.



From aicolburn@yahoo.com  Mon Jul  1 18:28:47 2002
From: aicolburn@yahoo.com (Alan Colburn)
Date: Mon, 1 Jul 2002 10:28:47 -0700 (PDT)
Subject: [Tutor] OOP Newbie Q
Message-ID: <20020701172847.77395.qmail@web20510.mail.yahoo.com>

Hi all--

As I work through various tutorials, trying to
understand OOP fundamentals, I keep bumping into the
same question -- how do you set up a user interfact to
instatiate (or create :-) multiple objects of the same
type?

An example would probably make my question clearer. In
honor of Alan Gauld's nice tutorial, I'll use his OOP
example -- a program to work with bank accounts, via a
class called BankAccount. To create a new account
object, of course, you just write:

<object name>=BankAccount()

filling <object name> with a different name for each
account holder. Presumably a bank would have hundreds
of BankAccount objects in its program.

My question is about how I'd set up a user interface
to create a new account. How can you create a new
object without having to manually enter the source
code each time?

a=BankAccount()
b=BankAccount()
c=BankAccount()
 
This would get a bit tedious after awhile! I get stuck
because if you ask the user for info that could lead
to an account name, with something like the raw_input
statement, the resulting information is string type,
so I can't use it to create the object. In other
words, code like this wouldn't work for creating a new
BankAccount object:

acctName=raw_input("Account name? ")
acctName=BankAccount()

Any thoughts? Thanks! -- Al C.

__________________________________________________
Do You Yahoo!?
Yahoo! - Official partner of 2002 FIFA World Cup
http://fifaworldcup.yahoo.com



From kalle@lysator.liu.se  Mon Jul  1 18:29:17 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Mon, 1 Jul 2002 19:29:17 +0200
Subject: [Tutor] drag-and-drop argument passing
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6D3@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6D3@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020701172917.GA509@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[somebody]
> But how do I turn a string in a list, like sys.argv[], into a raw
> string?
>  for path in sys.argv[1:]:
>       make_raw(path) 

I don't understand this question.  "Raw" is a property of string
literals, it doesn't make sense for string objects.  Or is this
another "raw" than r''?

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9IJErdNeA1787sd0RAj1vAJ9invGmLo2rykHk1aevX9N6QZ/o7gCgui8i
WN46fW/C0wVpc4eBHbHed/4=
=Ti2I
-----END PGP SIGNATURE-----



From alan.gauld@bt.com  Mon Jul  1 18:24:58 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 1 Jul 2002 18:24:58 +0100
Subject: [Tutor] Mac and Tkinter
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6D6@mbtlipnt02.btlabs.bt.co.uk>

> Are there any MacPython folks out there who might have tried to use 
> Tkinter?  

I'm toying with Python on my iBook just now. I haven't got Tk working 
yet but the web suggests that it will work under XonX.

That means you must run X windows on the Mac under MocOS X.

The other way is to load the TCL/Tk version for MacOS 9 and in 
theory Tkinter should work with that but again I haven't tried yet.

HTH,

Alan g



From jeff@ccvcorp.com  Mon Jul  1 18:39:29 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 01 Jul 2002 10:39:29 -0700
Subject: [Tutor] drag-and-drop argument passing
References: <ISPFE8z0b4djKMQzfyB0002120c@mail.takas.lt>
Message-ID: <3D2093D1.34A4E80B@ccvcorp.com>


Pijus Virketis wrote:

> But how do I turn a string in a list, like sys.argv[], into a raw
> string? Is there a conversion function between the two or
> something?Then, I could do (pseudocode):for path in sys.argv[1:]:
> make_raw(path)

No, there isn't a conversion, because you don't need one.  The
difference between raw and not-raw strings exists only for string
literals that appear in your code -- it's a question of how you spell
a given sequence of bytes, not a difference in how those bytes are
stored, if that makes any sense.  In other words,

>>> x = "c:\\windows\\temp"
>>> y = r"c:\windows\temp"

These two strings, one raw and the other not, are the exact same
sequence of bytes.  In fact, if you "intern" the first string, then
the second one could well be the exact same object in memory.

Keep in mind that raw strings exist in order to avoid interpreting
control characters.  Control characters, in turn, are
multiple-character representations of a single, nonprintable
character.  Since I can't just type a tab character, for instance,
into my string, I use '\t' to represent that character instead, and
the interpreter will store that character sequence as a single byte
(0x09).  But what happens if I really want the two characters instead
of 0x09?  That's where raw strings come in -- by declaring a string as
raw, I'm telling the interpreter to *not* substitute any values, even
if a sequence *looks* like a control character sequence.

When you get strings from some source of input (whether it be
raw_input(), reading from a file, or from sys.argv), the strings are
already in internal representation -- that means that the distinction
between raw and not-raw strings is meaningless.  Any unprintable
characters will be passed in in their true form (0x09, for instance),
so there's no need to interpret any character sequences as anything
special.

Hope that this makes sense -- if not, I'll try to explain a bit
better.  :)

In other words, your make_raw() function could be written like this --

def make_raw(text):
    return text

... and you'll get exactly the results you want.  ;)

Jeff Shannon
Technician/Programmer
Credit International





From alan.gauld@bt.com  Mon Jul  1 18:20:38 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 1 Jul 2002 18:20:38 +0100
Subject: [Tutor] [OT] TECO and Emacs (Was: pair programming.)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6D5@mbtlipnt02.btlabs.bt.co.uk>

> > thing I can say about Tico is that it was so bad it drove 
> > James Gosling to invent the original Emacs!
> 
> I think you mean TECO.  Also, Gosling didn't write the first Emacs.
> Richard M. Stallman did that, merging two existing TECO macro
> packages.  Gosling wrote the first implementation of Emacs in C.

I wondered who would bite :-) but I beg to differ. 

Gosling wrote his "Editing MACroS" package in TECO macro language. 
Stallman used it at MIT and wrote the first C/Lisp emacs vesion. 
After that its very confusing who wrote what. Depending on whether 
you read the GNU or the Unipress(*) history of emacs you get 
different stories. Depending on whether you count the TECO 
macros as a real emacs matters too. Since the commands Gosling 
defined were the same ones that Stallman used, I'm inclined 
to count it. (But that still doesn't excuse him foisting Java on us!)

Alan g.

(*)Unipress are the company who (still?) sell Goslings emacs as a 
commercial package. I used it in preference to GNU emacs from 
1990 - 1994 coz it had proper GUI support for X windows...



From gjlee@seri.co.uk  Mon Jul  1 17:22:32 2002
From: gjlee@seri.co.uk (Geonjae Lee)
Date: Mon, 1 Jul 2002 17:22:32 +0100
Subject: [Tutor] Question about Tkinter
Message-ID: <341710540F08E34498A057DEE04DAAD71295AC@ex1.seri.co.uk>

Hi, whoever you're, thanks for the answer for the previous question.
But I met another problem. Following is the my(from manual) code.
sorry it's a bit long. -.-;;

File 1 : quitter.py
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D
from Tkinter import *
from tkMessageBox import askokcancel

class Quitter(Frame):
    def __init__(self, parent=3DNone):
        Frame.__init__(self, parent)
        self.pack()
        widget =3D Button(self, text=3D'Quit', command=3Dself.quit)
        widget.pack(side=3DLEFT)

    def quit(self):
        ans =3D askokcancel('Verify exit', 'Really quit?')
        if ans:
            Frame.quit(self)

if __name__ =3D=3D '__main__':
    Quitter().mainloop()
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D


File 2 : dialogTable.py
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D
from tkFileDialog   import askopenfilename
from tkColorChooser import askcolor
from tkMessageBox   import askquestion, showerror
from tkSimpleDialog import askfloat

demos =3D {
    'Open': askopenfilename,
    'Color': askcolor,
    'Query': lambda: askquestion('Warning', 'Are you sure?'),
    'Error': lambda: showerror('Error!', "He's dead, Jim"),
    'Input': lambda: askfloat('Entry', 'Enter credit card number')
        }
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D


File 3 : demodlg.py
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D
from Tkinter import *
from dialogTable import demos
from quitter import Quitter

class Demo(Frame):
    def __init__(self, parent=3DNone):
        Frame.__init__(self, parent)
        self.pack()
        Label(self, text=3D"Basic demos").pack()
        for (key, value) in demos.items():
            Button(self, text=3Dkey, command=3Dvalue).pack(side=3DTOP, =
fill=3DBOTH)
        Quitter(self).pack(side=3DTOP, fill=3DBOTH)

if __name__ =3D=3D '__main__':
    Demo().mainloop()
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D

When I execute File3 (demodlg.py), I got a window which got a 6 buttons =
in it.
First 5 button are displayed as what I expected (I mean it's centered =
and all same size - same as the those in the book).
But the last one created by the line 'Quitter(self).pack(side=3DTOP, =
fill=3DBOTH)' (which is 12 line of File3)
is located left sided not centered as in the book.
I tried not giving the option in the pack method of File1 for this line=20
from=20
        widget.pack(side=3DLEFT)
to
        widget.pack()

After this change, I got a little change in display which is this time =
the last button is located centered but
the size is not same as the others. (It's smaller than others).
By result, It seems the option (side=3DTOP, fill=3DBOTH) of pack method =
of the line  -Quitter(self).pack(side=3DTOP, fill=3DBOTH) -
in File3 doesn't do anything at all.

Could anybody explain me why this happens ?=20
Thanks in advance.

ThomasLee (KJ Lee)











From kalle@lysator.liu.se  Mon Jul  1 18:52:48 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Mon, 1 Jul 2002 19:52:48 +0200
Subject: [Tutor] [OT] TECO and Emacs (Was: pair programming.)
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6D5@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6D5@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020701175248.GB509@i92.ryd.student.liu.se>

[alan.gauld@bt.com]
> > > thing I can say about Tico is that it was so bad it drove 
> > > James Gosling to invent the original Emacs!

[me]
> > I think you mean TECO.  Also, Gosling didn't write the first Emacs.
> > Richard M. Stallman did that, merging two existing TECO macro
> > packages.  Gosling wrote the first implementation of Emacs in C.

[alan again]
> I wondered who would bite :-) but I beg to differ. 
> 
> Gosling wrote his "Editing MACroS" package in TECO macro language. 
> Stallman used it at MIT and wrote the first C/Lisp emacs vesion. 

Have you got any web pages or other references supporting your
version?  I didn't find any (admittedly, I didn't look very hard).  On
the other hand, I found several supporting mine:

http://www.jwz.org/doc/emacs-timeline.html
http://www.abc.se/~jp/articles/computer/editor/emacshis.txt
http://www.lysator.liu.se/history/garb/txt/87-1-emacs.txt
http://www.emacswiki.org/cgi-bin/wiki.pl?CategoryHistory

Only one of the pages above is explicitly written by RMS, and one is
written by Jamie Zawinski (lead developer of Lucid Emacs, not known
for his love of RMS).

But as I was -4 years old in 1976, I obviously don't have any
first-hand information.  I might well be wrong.

Peace,
  Kalle
-- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.



From glingl@aon.at  Mon Jul  1 21:31:00 2002
From: glingl@aon.at (Gregor Lingl)
Date: Mon, 1 Jul 2002 22:31:00 +0200
Subject: [Tutor] OOP Newbie Q
References: <20020701172847.77395.qmail@web20510.mail.yahoo.com>
Message-ID: <003c01c2213e$366c2060$1615a8c0@mega>

----- Original Message ----- 
From: "Alan Colburn" <aicolburn@yahoo.com>
To: <tutor@python.org>
> ... How can you create a new
> object without having to manually enter the source
> code each time?
> 
> a=BankAccount()
> b=BankAccount()
> c=BankAccount()
>  
> This would get a bit tedious after awhile! ...
> ... code like this wouldn't work for creating a new
> BankAccount object:
> 
> acctName=raw_input("Account name? ")
> acctName=BankAccount()
> 
> Any thoughts? Thanks! -- Al C.
> 

If you have to store an unknown number of objects
of any kind, you should think of using a compound data type
to store them, as are, fo instance lists or - maybe
in your case this would serve better - dictionaries:

accounts = {}
while   < some condition > :
    acctName=raw_input("Account name? ")
    accounts[acctName] = BankAccount()
    ....

so you could retrieve any account via
its name this way:

actualAccount = accounts[acctName]
...

Gregor





From Kyle Babich" <kb@kb5.org  Mon Jul  1 22:08:21 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Mon, 1 Jul 2002 21:08:21 +0000
Subject: [Tutor] Translating to Python
Message-ID: <20020701210821.9023E6DB33@www.fastmail.fm>

Could someone show me how to translate this to python from perl?

#!/usr/bin/perl -wT
use strict;
use CGI qw/ :standard /;

print header ( 'text/html' );

my $c = param('c');
my $content = "c";
	if ($c eq "abc") {
		$content = qq{abc123};
	} elsif ($c eq "def") {
		$content = qq{def456};
	} else {
		print "error:  content failed\n";
	}

open(TEXT,"text.txt") or die ("error:  text.txt failed\n");
	my $text = <TEXT>;
close(TEXT) or die("error:  close text.txt failed\n");

print <<"EndOfHTML";

$content

<br>&nbsp;<br>&nbsp;<br>&nbsp;

$text

EndOfHTML

And/or could someone recomend a good python tutorial from the ground up
that includes opening external files and if/elseif statements?

Thank you in advance,
Kyle



From israel@lith.com  Mon Jul  1 22:11:30 2002
From: israel@lith.com (Israel Evans)
Date: Mon, 1 Jul 2002 14:11:30 -0700
Subject: [Tutor] Translating to Python
Message-ID: <AF020C5FC551DD43A4958A679EA16A15017B4245@abbott.lith.com>

Eyes.. Blurring...

Mind filled with $ %# c  ... unbearable stuff...

<passed out on the floor>



ps.  Sorry I can't help you, but I feel your pain.



~Israel~


-----Original Message-----
From: Kyle Babich [mailto:kb@kb5.org] 
Sent: 01 July 2002 2:08 PM
To: tutor
Subject: [Tutor] Translating to Python

Could someone show me how to translate this to python from perl?

#!/usr/bin/perl -wT
use strict;
use CGI qw/ :standard /;

print header ( 'text/html' );

my $c = param('c');
my $content = "c";
	if ($c eq "abc") {
		$content = qq{abc123};
	} elsif ($c eq "def") {
		$content = qq{def456};
	} else {
		print "error:  content failed\n";
	}

open(TEXT,"text.txt") or die ("error:  text.txt failed\n");
	my $text = <TEXT>;
close(TEXT) or die("error:  close text.txt failed\n");

print <<"EndOfHTML";

$content

<br>&nbsp;<br>&nbsp;<br>&nbsp;

$text

EndOfHTML

And/or could someone recomend a good python tutorial from the ground up
that includes opening external files and if/elseif statements?

Thank you in advance,
Kyle


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



From rob@uselesspython.com  Mon Jul  1 22:15:27 2002
From: rob@uselesspython.com (Rob)
Date: Mon, 01 Jul 2002 16:15:27 -0500
Subject: [Tutor] Translating to Python
References: <20020701210821.9023E6DB33@www.fastmail.fm>
Message-ID: <3D20C66F.40600@uselesspython.com>

http://www.python.org/doc/current/tut/tut.html

Kyle Babich wrote:
<snip />


> 
> And/or could someone recomend a good python tutorial from the ground up
> that includes opening external files and if/elseif statements?
> 


-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show





From rob@uselesspython.com  Mon Jul  1 22:17:09 2002
From: rob@uselesspython.com (Rob)
Date: Mon, 01 Jul 2002 16:17:09 -0500
Subject: [Tutor] Translating to Python
References: <20020701210821.9023E6DB33@www.fastmail.fm> <3D20C66F.40600@uselesspython.com>
Message-ID: <3D20C6D5.10908@uselesspython.com>

Oh, and, if you already know Perl....

http://diveintopython.org/

Rob
http://uselessspython.com

Rob wrote:

> http://www.python.org/doc/current/tut/tut.html
> 
> Kyle Babich wrote:
> <snip />
> 
> 
>>
>> And/or could someone recomend a good python tutorial from the ground up
>> that includes opening external files and if/elseif statements?
>>
> 
> 


-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show





From dyoo@hkn.eecs.berkeley.edu  Mon Jul  1 22:50:23 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 1 Jul 2002 14:50:23 -0700 (PDT)
Subject: [Tutor] Translating to Python   [perl --> python]
In-Reply-To: <20020701210821.9023E6DB33@www.fastmail.fm>
Message-ID: <Pine.LNX.4.44.0207011536140.28725-100000@hkn.eecs.berkeley.edu>


On Mon, 1 Jul 2002, Kyle Babich wrote:

> Could someone show me how to translate this to python from perl?

Hi Kyle,

Welcome!  Let's see what a translation might look like between Perl and
Python.



> #!/usr/bin/perl -wT
> use strict;

Python is always in "strict" mode in a sense --- anything bad that happens
will raise an Exception.  Python's magic line will probably look like:

#!/usr/bin/env python





> use CGI qw/ :standard /;

In Python, module importing is done through the 'import' keyword.  Python
does have a 'cgi' module, so we can do:

###
import cgi
###

with similar effects.

See:

    http://www.python.org/doc/lib/module-cgi.html

for more details on the 'cgi' module.



By the way, Python provides a really nice debugging module called 'cgitb'
that prints out a nice traceback if there are bugs in the module.  Rather
than get a rude 'Internal Server Error', we can have our Python script
display a nicely formatted error page by doing:

###
import cgitb
cgitb.enable()
###




> print header ( 'text/html' );

I don't know if the Python cgi module has a header() utility function, but
we can do this for a similar effect:

###
print "Content-type: text/html\n\n"
###




> my $c = param('c');
> my $content = "c";
> 	if ($c eq "abc") {
> 		$content = qq{abc123};
> 	} elsif ($c eq "def") {
> 		$content = qq{def456};
> 	} else {
> 		print "error:  content failed\n";
> 	}


Python's cgi module provides an object that we use to pull out parameters.
Here's what it might look like:

###
form = cgi.FieldStorage()
c = cgi['c'].value
content = 'c'
if c == 'abc':
    content = "abc123"
elif c == 'def':
    content = "def456"
else:
    print "error: content failed\n" ## shouldn't we raise an error here?
###





> open(TEXT,"text.txt") or die ("error:  text.txt failed\n");
> 	my $text = <TEXT>;
> close(TEXT) or die("error:  close text.txt failed\n");


File opening in Python implicitly raises an IOError if bad things happen,
so the "die" part is implied.

###
file = open("text.txt")
text = file.read()
file.close()
###



> print <<"EndOfHTML";
>
> $content
>
> <br>&nbsp;<br>&nbsp;<br>&nbsp;
>
> $text
>
> EndOfHTML

Python provides a string formatting operation that can span across several
lines:

###
print """

%(content)s


<br>&nbsp;<br>&nbsp;<br>&nbsp;

%(text)s

""" % vars()
###





Let's put everything together to see what the final product looks like.
I'll do a little rearrangement to make the program flow a little nicer:

###
# Translation of Kyle's Perl program into Python
import cgi
import cgitb
cgitb.enable()


form = cgi.FieldStorage()
c = cgi['c'].value
content = 'c'
if c == 'abc':
    content = "abc123"
elif c == 'def':
    content = "def456"
else:
    print "error: content failed\n"

file = open("text.txt")
text = file.read()
file.close()


print "Content-type: text/html\n\n"
print """

%(content)s


<br>&nbsp;<br>&nbsp;<br>&nbsp;

%(text)s

""" % vars()
###


This is still a little awkward as far as Python programs go --- I'd like
to break things down into separate functions to make the code's intent
clearer, and to avoid having global variables spill out everywhere.


Hope this helps!




From rob@uselesspython.com  Mon Jul  1 23:01:58 2002
From: rob@uselesspython.com (Rob)
Date: Mon, 01 Jul 2002 17:01:58 -0500
Subject: [Tutor] installing/starting vPython
References: <02af01c2206a$515ff2e0$0193fea9@vt1000>
Message-ID: <3D20D156.8090909@uselesspython.com>

It sounds like you might have a GL issue on your hands. What Operating 
System are you running?

Rob
http://uselesspython.com

val wrote:

> Hi The List,
>     i downloaded and installed vPython for Python22.
>     i'm trying to run demos from the Demos dir by double-
>     clicking on *.py files.  It works impressively fine 
>     on my job (same win2k, both Py21 and Py22 are             installed).
>     At home i have a standard message from vPython
>     and then just an empty window (or two or three
>     depending on the demo to be run).
> 
>     Any help/advice would be very appreciated.
> thanx,
> val
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show





From Kyle Babich" <kb@kb5.org  Mon Jul  1 23:10:02 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Mon, 1 Jul 2002 22:10:02 +0000
Subject: [Tutor] Translating to Python   [perl --> python]
Message-ID: <20020701221002.4C3546DACE@www.fastmail.fm>

Thank you, that's just what I was looking for.  I like it, err... one
problem, my server doesn't.     505

Results of python -c index.py

Traceback (innermost last):
  File "<string>", line 1, in ?
NameError: index


Exactly what index.py says:

#!/usr/bin/python

import cgi

import cgitb
cgitb.enable()

print "Content-type: text/html\n\n"
print

form = cgi.FieldStorage()
	c = cgi['c'].value
	content = 'c'
		if c == 'abc':
    		content = "abc123"
		elif c == 'def':
    		content = "def456"
		else:
		print "error: content failed\n"

file = open("text.txt")
	text = file.read()
file.close()

print """

%(content)s

<br>&nbsp;<br>&nbsp;<br>&nbsp;

%(text)s

""" % vars()

On Mon, 1 Jul 2002 14:50:23 -0700 (PDT), "Danny Yoo"
<dyoo@hkn.eecs.berkeley.edu> said:
> 
> 
> On Mon, 1 Jul 2002, Kyle Babich wrote:
> 
> > Could someone show me how to translate this to python from perl?
> 
> Hi Kyle,
> 
> Welcome!  Let's see what a translation might look like between Perl and
> Python.
> 
> 
> 
> > #!/usr/bin/perl -wT
> > use strict;
> 
> Python is always in "strict" mode in a sense --- anything bad that
> happens
> will raise an Exception.  Python's magic line will probably look like:
> 
> #!/usr/bin/env python
> 
> 
> 
> 
> 
> > use CGI qw/ :standard /;
> 
> In Python, module importing is done through the 'import' keyword. 
> Python
> does have a 'cgi' module, so we can do:
> 
> ###
> import cgi
> ###
> 
> with similar effects.
> 
> See:
> 
>     http://www.python.org/doc/lib/module-cgi.html
> 
> for more details on the 'cgi' module.
> 
> 
> 
> By the way, Python provides a really nice debugging module called
> 'cgitb'
> that prints out a nice traceback if there are bugs in the module. 
> Rather
> than get a rude 'Internal Server Error', we can have our Python script
> display a nicely formatted error page by doing:
> 
> ###
> import cgitb
> cgitb.enable()
> ###
> 
> 
> 
> 
> > print header ( 'text/html' );
> 
> I don't know if the Python cgi module has a header() utility function,
> but
> we can do this for a similar effect:
> 
> ###
> print "Content-type: text/html\n\n"
> ###
> 
> 
> 
> 
> > my $c = param('c');
> > my $content = "c";
> > 	if ($c eq "abc") {
> > 		$content = qq{abc123};
> > 	} elsif ($c eq "def") {
> > 		$content = qq{def456};
> > 	} else {
> > 		print "error:  content failed\n";
> > 	}
> 
> 
> Python's cgi module provides an object that we use to pull out
> parameters.
> Here's what it might look like:
> 
> ###
> form = cgi.FieldStorage()
> c = cgi['c'].value
> content = 'c'
> if c == 'abc':
>     content = "abc123"
> elif c == 'def':
>     content = "def456"
> else:
>     print "error: content failed\n" ## shouldn't we raise an error
>     here?
> ###
> 
> 
> 
> 
> 
> > open(TEXT,"text.txt") or die ("error:  text.txt failed\n");
> > 	my $text = <TEXT>;
> > close(TEXT) or die("error:  close text.txt failed\n");
> 
> 
> File opening in Python implicitly raises an IOError if bad things
> happen,
> so the "die" part is implied.
> 
> ###
> file = open("text.txt")
> text = file.read()
> file.close()
> ###
> 
> 
> 
> > print <<"EndOfHTML";
> >
> > $content
> >
> > <br>&nbsp;<br>&nbsp;<br>&nbsp;
> >
> > $text
> >
> > EndOfHTML
> 
> Python provides a string formatting operation that can span across
> several
> lines:
> 
> ###
> print """
> 
> %(content)s
> 
> 
> <br>&nbsp;<br>&nbsp;<br>&nbsp;
> 
> %(text)s
> 
> """ % vars()
> ###
> 
> 
> 
> 
> 
> Let's put everything together to see what the final product looks like.
> I'll do a little rearrangement to make the program flow a little nicer:
> 
> ###
> # Translation of Kyle's Perl program into Python
> import cgi
> import cgitb
> cgitb.enable()
> 
> 
> form = cgi.FieldStorage()
> c = cgi['c'].value
> content = 'c'
> if c == 'abc':
>     content = "abc123"
> elif c == 'def':
>     content = "def456"
> else:
>     print "error: content failed\n"
> 
> file = open("text.txt")
> text = file.read()
> file.close()
> 
> 
> print "Content-type: text/html\n\n"
> print """
> 
> %(content)s
> 
> 
> <br>&nbsp;<br>&nbsp;<br>&nbsp;
> 
> %(text)s
> 
> """ % vars()
> ###
> 
> 
> This is still a little awkward as far as Python programs go --- I'd
> like
> to break things down into separate functions to make the code's intent
> clearer, and to avoid having global variables spill out everywhere.
> 
> 
> Hope this helps!
> 
> 
> 
> 



From dman@dman.ddts.net  Mon Jul  1 23:58:52 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Mon, 1 Jul 2002 17:58:52 -0500
Subject: [Tutor] Re: Translating to Python   [perl --> python]
In-Reply-To: <20020701221002.4C3546DACE@www.fastmail.fm>
References: <20020701221002.4C3546DACE@www.fastmail.fm>
Message-ID: <20020701225851.GA15141@dman.ddts.net>

--X1bOJ3K7DJ5YkBrT
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jul 01, 2002 at 10:10:02PM +0000, Kyle Babich wrote:
| Thank you, that's just what I was looking for.  I like it, err...
| one problem, my server doesn't.  505

I found 3 problems with Danny's code (must not have been tested :-)),
and 2 problems with Kyle's code.

| Results of python -c index.py
|=20
| Traceback (innermost last):
|   File "<string>", line 1, in ?
| NameError: index

First, "index.py" is a valid python statement only when
    1)  A variable named 'index' exists
and
    2)  that object has a member named 'py'

What you meant to write was
    $ python index.py

Still, that wouldn't help you to debug a CGI script unless you also
first created the rest of the environment that apache would create for
the script.
=20
| Exactly what index.py says:

| form =3D cgi.FieldStorage()
| 	c =3D cgi['c'].value
  ^
| 	content =3D 'c'
  ^
| 		if c =3D=3D 'abc':
  ^     ^
|     		content =3D "abc123"
  ^^^^^ ^

That indentation is not valid syntax in python.  That's probbly what
is causing your 505 error.  A good idea is to look at the web server's
error log since it will (at least for apache) contain the error
message.

Be very consistent in your indentataion or else python will beat you
with a cluestick :-).

Rule #1 (this applies to any language, python just enforces it) :
    Indent blocks of statements at the same indentation level.
    Indent nested blocks by 1 additional indentation level.

If you don't indent consistently, then the code is nearly impossible
to read.  While C, Perl, etc, will let you get away with it (assuming
the code is correct in the first place and you haven't merely fooled
yourself), Python won't let you get away with it -- it will be even
more fooled than you are.

Rule #2 (this also applies to everything but Makefiles, IMO) :
    Never use tabs.
    Always keep your tabstop set at 8.

Any decent editor can be configured to insert/remove the proper number of
spaces when you press the buttons on your keyboard labeled "tab" and
"backspace".  Thus the tab character (ASCII 0x09) never needs to be
stored in the file itself.  Also note that whenever python sees a tab
character, it treats it as 8 spaces.  If you muck with the size your
editor displays a tab as, you'll get very confusing syntax errors from
python because it doesn't see the same thing your eyes see.

For vim, I recommend these settings :


" make tabs visible
set lcs=3Dtab:>-
set list

augroup Python
    au!
    au FileType python set sts=3D4 sw=3D4 et tw=3D80 fo=3Dcroq2 hls

    " override C preprocessor indenting
    au FileType python inoremap # X<C-H>#

    au FileType python set foldmethod=3Dindent
    " do I want everything collapsed when I open the file?
    au FileType python set nofoldenable

augroup END


Now to correct the bugs in Danny's code :


#!/usr/bin/env python

import cgi
import cgitb
cgitb.enable()


# Bug #1:  print the headers first.  Otherwise it is possible to print
# that "error: content failed" message before the headers are printed.
print "Content-type: text/html\n\n"


form =3D cgi.FieldStorage()
# Bug #3:  handle the situation where the script was not passed a
#          parameter 'c'.  Unlike perl/sh, in python accessing undefined
#          variables is an error, not the empty string.
try :
    # Bug #2: s/cgi/form/  Danny meant to index the form object, not
    #         the cgi module.
    c =3D form['c'].value
except KeyError :
    # What to do if the parameter doesn't exist.  I suppose
    # considering it to be the empty string is what is desired in this
    # case.
    c =3D ""
content =3D 'c'
if c =3D=3D 'abc':
    content =3D "abc123"
elif c =3D=3D 'def':
    content =3D "def456"
else:
    print "error: content failed\n"

file =3D open("text.txt")
text =3D file.read()
file.close()

print """

%(content)s


<br>&nbsp;<br>&nbsp;<br>&nbsp;

%(text)s

""" % vars()


HTH,
-D

--=20

Like a gold ring in a pig's snout
is a beautiful woman who shows no discretion.
        Proverbs 11:22
=20
http://dman.ddts.net/~dman/


--X1bOJ3K7DJ5YkBrT
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0g3qsACgkQO8l8XBKTpRTU9gCgxQimIQNcvqv9L/rXQZU4YiXg
J0AAoL69T0cJ59ksv3DyV+c6IrWtzPPq
=sRkc
-----END PGP SIGNATURE-----

--X1bOJ3K7DJ5YkBrT--



From ak@silmarill.org  Tue Jul  2 01:35:33 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 1 Jul 2002 20:35:33 -0400
Subject: [Tutor] game help
In-Reply-To: <002f01c2205d$80368820$264bf8d8@davidearly>
References: <002f01c2205d$80368820$264bf8d8@davidearly>
Message-ID: <20020702003533.GA15464@ak.silmarill.org>

On Sun, Jun 30, 2002 at 12:42:26PM -0500, David & Sheri Early wrote:
> hello my name is chris and am trying to use python to start creating a game but everywhere i look for resources i come up at a dead end. help!
> 
> ~Chris~

did you look at pygame.org?


-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From arosado@softhome.net  Tue Jul  2 01:37:46 2002
From: arosado@softhome.net (Andres Rosado)
Date: Mon, 01 Jul 2002 20:37:46 -0400
Subject: [Tutor] help on makin a prog
Message-ID: <5.1.0.14.0.20020701203743.00bad970@mail.softhome.net>

At 12:00 PM 6/30/2002 -0400, you wrote:
>Hey im really really new to this stuff and i would like some help so could
>any1 try teach me? i know a few things raw_input("Hello, world") and
>print"hello world so cud u teach me how to make a proper program?

There are several tutorials that can get you started. Python comes with one 
tutorial. I can't tell you if it will help you, since I wasn't know to 
programming when I started in Python.

Most of what you need to learn is to think in terms of the computer.


-----------------------------------
Andres Rosado
Email: andresr@despammed.com
ICQ: 66750646
Homepage: http://andres980.tripod.com/

If God wanted us to be brave, why did he give us legs?
                 -- Marvin Kitman




From bwinton@latte.ca  Tue Jul  2 00:30:25 2002
From: bwinton@latte.ca (Blake Winton)
Date: Mon, 1 Jul 2002 19:30:25 -0400
Subject: [Tutor] Re: Translating to Python   [perl --> python]
In-Reply-To: <20020701225851.GA15141@dman.ddts.net>
References: <20020701221002.4C3546DACE@www.fastmail.fm> <20020701225851.GA15141@dman.ddts.net>
Message-ID: <20020701193025.A24900@latte.ca>

* Derrick 'dman' Hudson <dman@dman.ddts.net> [020701 18:39]:
> try :
>     # Bug #2: s/cgi/form/  Danny meant to index the form object, not
>     #         the cgi module.
>     c = form['c'].value
> except KeyError :
>     # What to do if the parameter doesn't exist.  I suppose
>     # considering it to be the empty string is what is desired in this
>     # case.
>     c = ""
> content = 'c'

I think that might be more useful if it was 
content = c

That way, if the content isn't there, you get whatever
the user typed in, instead of the letter 'c'.  ;)

> if c == 'abc':
>     content = "abc123"
> elif c == 'def':
>     content = "def456"
> else:
>     print "error: content failed\n"

Later,
Blake.
-- 
  7:30pm  up 1 day, 23:52,  4 users,  load average: 0.00, 0.00, 0.00




From Kyle Babich" <kb@kb5.org  Tue Jul  2 00:48:30 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Mon, 1 Jul 2002 23:48:30 +0000
Subject: [Tutor] Re: Translating to Python   [perl --> python]
Message-ID: <20020701234830.8EEDA6F7B1@www.fastmail.fm>

How could I do this without cgitb?

Thank you

On Mon, 1 Jul 2002 17:58:52 -0500, "Derrick 'dman' Hudson"
<dman@dman.ddts.net> said:
> On Mon, Jul 01, 2002 at 10:10:02PM +0000, Kyle Babich wrote:
> | Thank you, that's just what I was looking for.  I like it, err...
> | one problem, my server doesn't.  505
> 
> I found 3 problems with Danny's code (must not have been tested :-)),
> and 2 problems with Kyle's code.
> 
> | Results of python -c index.py
> | 
> | Traceback (innermost last):
> |   File "<string>", line 1, in ?
> | NameError: index
> 
> First, "index.py" is a valid python statement only when
>     1)  A variable named 'index' exists
> and
>     2)  that object has a member named 'py'
> 
> What you meant to write was
>     $ python index.py
> 
> Still, that wouldn't help you to debug a CGI script unless you also
> first created the rest of the environment that apache would create for
> the script.
>  
> | Exactly what index.py says:
> 
> | form = cgi.FieldStorage()
> |       c = cgi['c'].value
>   ^
> |       content = 'c'
>   ^
> |               if c == 'abc':
>   ^     ^
> |               content = "abc123"
>   ^^^^^ ^
> 
> That indentation is not valid syntax in python.  That's probbly what
> is causing your 505 error.  A good idea is to look at the web server's
> error log since it will (at least for apache) contain the error
> message.
> 
> Be very consistent in your indentataion or else python will beat you
> with a cluestick :-).
> 
> Rule #1 (this applies to any language, python just enforces it) :
>     Indent blocks of statements at the same indentation level.
>     Indent nested blocks by 1 additional indentation level.
> 
> If you don't indent consistently, then the code is nearly impossible
> to read.  While C, Perl, etc, will let you get away with it (assuming
> the code is correct in the first place and you haven't merely fooled
> yourself), Python won't let you get away with it -- it will be even
> more fooled than you are.
> 
> Rule #2 (this also applies to everything but Makefiles, IMO) :
>     Never use tabs.
>     Always keep your tabstop set at 8.
> 
> Any decent editor can be configured to insert/remove the proper number
> of
> spaces when you press the buttons on your keyboard labeled "tab" and
> "backspace".  Thus the tab character (ASCII 0x09) never needs to be
> stored in the file itself.  Also note that whenever python sees a tab
> character, it treats it as 8 spaces.  If you muck with the size your
> editor displays a tab as, you'll get very confusing syntax errors from
> python because it doesn't see the same thing your eyes see.
> 
> For vim, I recommend these settings :
> 
> 
> " make tabs visible
> set lcs=tab:>-
> set list
> 
> augroup Python
>     au!
>     au FileType python set sts=4 sw=4 et tw=80 fo=croq2 hls
> 
>     " override C preprocessor indenting
>     au FileType python inoremap # X<C-H>#
> 
>     au FileType python set foldmethod=indent
>     " do I want everything collapsed when I open the file?
>     au FileType python set nofoldenable
> 
> augroup END
> 
> 
> Now to correct the bugs in Danny's code :
> 
> 
> #!/usr/bin/env python
> 
> import cgi
> import cgitb
> cgitb.enable()
> 
> 
> # Bug #1:  print the headers first.  Otherwise it is possible to print
> # that "error: content failed" message before the headers are printed.
> print "Content-type: text/html\n\n"
> 
> 
> form = cgi.FieldStorage()
> # Bug #3:  handle the situation where the script was not passed a
> #          parameter 'c'.  Unlike perl/sh, in python accessing
> undefined
> #          variables is an error, not the empty string.
> try :
>     # Bug #2: s/cgi/form/  Danny meant to index the form object, not
>     #         the cgi module.
>     c = form['c'].value
> except KeyError :
>     # What to do if the parameter doesn't exist.  I suppose
>     # considering it to be the empty string is what is desired in this
>     # case.
>     c = ""
> content = 'c'
> if c == 'abc':
>     content = "abc123"
> elif c == 'def':
>     content = "def456"
> else:
>     print "error: content failed\n"
> 
> file = open("text.txt")
> text = file.read()
> file.close()
> 
> print """
> 
> %(content)s
> 
> 
> <br>&nbsp;<br>&nbsp;<br>&nbsp;
> 
> %(text)s
> 
> """ % vars()
> 
> 
> HTH,
> -D
> 
> -- 
> 
> Like a gold ring in a pig's snout
> is a beautiful woman who shows no discretion.
>         Proverbs 11:22
>  
> http://dman.ddts.net/~dman/
> 



From slime@vsnl.net  Mon Jul  1 17:32:14 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Mon, 1 Jul 2002 22:02:14 +0530
Subject: [Tutor] Matrix class problems
In-Reply-To: <fc.004c4b6b009eae14004c4b6b009eae14.9eae80@blakeschool.org>
References: <fc.004c4b6b009eae14004c4b6b009eae14.9eae80@blakeschool.org>
Message-ID: <20020701163213.GA2131@localhost.localdomain>

Hi,

    Firstly, Thanks to everyone for clearing my question on what repr()
does. since the matrix class, in my case, actually represents a list of
lists, I have just done this :

"""
    def __repr__ (self) :
        return repr(self.matrix)
"""

on mon, 01 jul 2002 christopher smith spewed into the ether:
[-- snippity --]
> try defining the __rmul__ method which is called whenever an 

    Thanks ! I discovered that *just* after I sent my mail yesterday.
I also discovered a whole bunch of other operators, some of which I
never knew existed ( __inverse__() for one :-)

[-- snippity --]
> >ps. for those of you who study maths, i have been racking my brains as
> >to how to get the determinant of a matrix, and have been unsuccessful.
> >
> >how do i find the minor matrix ? aaaarggghhh !!
> 
> when i was on that rack my kind math teacher reminded me 
> that by reducing the matrix to an upper diagonal form through the 
> swapping, multiplying, and adding rows together the determinant is 
> found as the product of the diagonal.

    Hmm ... this is something I realise I need to make finding the rank
of the matrix easier as well. Will have to look into it.

> You can find such algorithms in Gauss elimination routines.

    OK, I will look for algorithms.

    Meanwhile, for those who might be interested, I have put up my
initial stab at this module here :

    http://www.symonds.net/~prahladv/files/matrix.py

    There is a whole lot on the TODO list of the class yet ...

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

Before marriage the three little words are "I love you," after marriage
they are "Let's eat out."



From dyoo@hkn.eecs.berkeley.edu  Tue Jul  2 09:16:11 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 2 Jul 2002 01:16:11 -0700 (PDT)
Subject: [Tutor] Re: Translating to Python   [perl --> python]
In-Reply-To: <20020701234830.8EEDA6F7B1@www.fastmail.fm>
Message-ID: <Pine.LNX.4.44.0207020105001.9772-100000@hkn.eecs.berkeley.edu>


On Mon, 1 Jul 2002, Kyle Babich wrote:

> How could I do this without cgitb?

Hi Kyle,

Which part, exactly, would you like to do without the 'cgitb' traceback
module?  cgitb modifies the programming environment slightly so that
raised exceptions give nicely formatted error messages back to the web
browser.


Try commenting the cgitb lines first, and deliberately introduce a syntax
error in the script --- you'll notice that the web server doesn't output
too much useful information back to the user (although it will be in the
error log).  On Apache, a bug in a CGI script brings up the infuriatingly
uninformative "Internal Server Error" page.


Afterwards, uncomment the cgitb-related lines and try again, and you'll
see a difference.  It's not mandatory, but it is pretty useful.  I usually
keep 'cgitb' on because it's such a nice debugging tool, and looks nicer
than having to do a:

    tail -f /var/log/apache/error.log

which would be an alternative way of watching script problems.


If you have more questions, please feel free to ask!  By the way, it
sounds like you're coming from a Perl background.  How much Perl do you
know already?  We can tailor our answers to take advantage of your
experiences in other languages, if that would be helpful for you.


Good luck!




From alan.gauld@bt.com  Tue Jul  2 10:57:27 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 2 Jul 2002 10:57:27 +0100
Subject: [Tutor] OOP Newbie Q
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6D9@mbtlipnt02.btlabs.bt.co.uk>

> An example would probably make my question clearer. In
> honor of Alan Gauld's nice tutorial, 

In return for the nice comments I'd better reply ;-)


> <object name>=BankAccount()
> 
> account holder. Presumably a bank would have hundreds
> of BankAccount objects in its program.

Yes so we need some kind of 'database' that allows us to find a 
given bank account by its oweners name(or more likely their bank 
account number - since one person can have many accounts and 
many persons can have the same name...)

Finding something in a collection given a unique key....hmmm, 
sounds like a dictionary!

accountList = {}  # new dictionary
while 1:  # loop forever
   id = getNextID()  # a function to generate new account numbers
   name = raw_input('Name: ') 
   if name == '' : break  # get out of the loop when finished
   bal = raw_input("Opening Balance? ")
   # and so on for all account attributes
   accountList[id] = BankAccount(Name,....) 

# Now lets access the accounts

for id in accountList.keys():
    print accountList[id].theName,
    print accountList[id].theBalance

# and find a particular one

id = raw_input("Which account? ")
print accountList[id].theName,
print accountList[id].theBalance

> My question is about how I'd set up a user interface
> to create a new account. 

Does that help?
I'll probably add the above to the OOP page next time I do 
an update of the site since it seems to be a common 
question that beginners raise.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@bt.com  Tue Jul  2 11:50:51 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 2 Jul 2002 11:50:51 +0100
Subject: [Tutor] [OT] TECO and Emacs (Was: pair programming.)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6DA@mbtlipnt02.btlabs.bt.co.uk>

> > > Richard M. Stallman did that, merging two existing TECO macro
> > > packages.  Gosling wrote the first implementation of Emacs in C.

Actually I definitely got one bit wrong. 
Gosling did do a C version slightly before Stallman's although 
I believe it wasn't much more than a crude interpreter for his 
TECO macros.  But at least it meant you could run EMACS without 
TECO being there... It also had a horrible version of Lisp as 
a macro language...

> > Gosling wrote his "Editing MACroS" package in TECO macro language. 

I don't think there's any dispute over this bit, other than 
whether they count as a real emacs - since you needed TECO 
installed to run them!

> > Stallman used it at MIT and wrote the first C/Lisp emacs vesion. 

This is the bit I got wrong, see above.

> Have you got any web pages or other references supporting your
> version?  

The Unipress documentation has an appendix giving their version 
of events. Having checked their web page they don't seem to 
support emacs any more and have removed all the online docs :-(
(Shame they didn't think to release the source as open!)
In fact they seem to only sell one single product now, shame 
because they used to do a range of interesting software tools...

I also have a copy of an old HP emacs manual (1986) which summarises 
the Unipress version of things. (I think HP/Ux licensed Unipress 
emacs for a while, but I'm not sure - I never used HP/Ux back then...)

> the other hand, I found several supporting mine:
> http://www.jwz.org/doc/emacs-timeline.html
> http://www.abc.se/~jp/articles/computer/editor/emacshis.txt
> http://www.lysator.liu.se/history/garb/txt/87-1-emacs.txt
> http://www.emacswiki.org/cgi-bin/wiki.pl?CategoryHistory

The problem is these are all from the GNU/Opensource pespective
wherein Gosling has been demonised(*) because he sold out to a 
commercial company(Unipress). It's actually hard to get a Gosling 
sympathetic perspective anywhere on the web!

One source I do still have is my very first Unix tutorial:
Unix For Users, published 1984. It says under 'other editors':
-----------
"emacs

emacs is a very advanced screen editor, due to James Gosling, 
it is considerably more powerful than vi, offering a split 
screen facility to permit editing of more than one file 
simultaneously. You may find it available ogn systems other 
than unix."
------------

Hardly definitive I know but significantly in a 1984 context 
credit was ascribed exclusively to Gosling and Stallman doesn't 
even warrant a mention!

Equally the official GNU camp have a very different view. A search 
on Google groups will show that debates over the origin of emacs 
and the relative roles of Gosling vv Stallman have been raging 
almost since emacs began! :-)

History is a variable not a constant! :-)

> But as I was -4 years old in 1976, I obviously don't have any
> first-hand information.  I might well be wrong.

I was using computers by then but didn't hit emacs until 1988.
(I hit teco in 1986 - ouch!)

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld

(*) 
Example of Stallman's view of Gosling is his comment at a conference:
"Then he stabbed everyone in the back by putting copyrights on it, making 
people promise not to redistribute it and then selling it to a
software-house. 
My later dealings with him personally showed that he was every bit as 
cowardly and despicable as you would expect from that history." 
No bias there then...



From alan.gauld@bt.com  Tue Jul  2 11:58:40 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 2 Jul 2002 11:58:40 +0100
Subject: [Tutor] Translating to Python
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6DB@mbtlipnt02.btlabs.bt.co.uk>

> Could someone show me how to translate this to python from perl?

Only if you translate the perl into English first! :-)

> print header ( 'text/html' );
> etc....

This looks like pretty much html generation so far as I can see.
Python has html libraries to help you do that.

> open(TEXT,"text.txt") or die ("error:  text.txt failed\n");

f = open("text.txt","r")

> 	my $text = <TEXT>;

text = f.read()

> close(TEXT) or die("error:  close text.txt failed\n");

f.close()

> 
> print <<"EndOfHTML";

print """

> $content
%s

blah blah

> $text
%s

> EndOfHTML
""" % (content, text)

> And/or could someone recomend a good python tutorial from the 
> ground up that includes opening external files and if/elseif statements?

The official one will be best if you know Perl.
Its included in the standard docs.

For a very quick look at files and branching try the relevant pages 
in my tutor

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld




From Kyle Babich" <kb@kb5.org  Tue Jul  2 12:26:10 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Tue, 2 Jul 2002 11:26:10 +0000
Subject: [Tutor] Re: Translating to Python   [perl --> python]
Message-ID: <20020702112610.C34A76DA1C@www.fastmail.fm>

I would like to do the entire thing without cgitb because I don't have
the module and I don't want to try to convincing my host to install it.
 Is it possible to do it without cgitb?

On Tue, 2 Jul 2002 01:16:11 -0700 (PDT), "Danny Yoo"
<dyoo@hkn.eecs.berkeley.edu> said:
> 
> 
> On Mon, 1 Jul 2002, Kyle Babich wrote:
> 
> > How could I do this without cgitb?
> 
> Hi Kyle,
> 
> Which part, exactly, would you like to do without the 'cgitb' traceback
> module?  cgitb modifies the programming environment slightly so that
> raised exceptions give nicely formatted error messages back to the web
> browser.
> 
> 
> Try commenting the cgitb lines first, and deliberately introduce a
> syntax
> error in the script --- you'll notice that the web server doesn't
> output
> too much useful information back to the user (although it will be in
> the
> error log).  On Apache, a bug in a CGI script brings up the
> infuriatingly
> uninformative "Internal Server Error" page.
> 
> 
> Afterwards, uncomment the cgitb-related lines and try again, and you'll
> see a difference.  It's not mandatory, but it is pretty useful.  I
> usually
> keep 'cgitb' on because it's such a nice debugging tool, and looks
> nicer
> than having to do a:
> 
>     tail -f /var/log/apache/error.log
> 
> which would be an alternative way of watching script problems.
> 
> 
> If you have more questions, please feel free to ask!  By the way, it
> sounds like you're coming from a Perl background.  How much Perl do you
> know already?  We can tailor our answers to take advantage of your
> experiences in other languages, if that would be helpful for you.
> 
> 
> Good luck!
> 
> 
> 
> 



From pythontutor@venix.com  Tue Jul  2 14:06:06 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 02 Jul 2002 09:06:06 -0400
Subject: [Tutor] Re: Translating to Python   [perl --> python]
References: <20020702112610.C34A76DA1C@www.fastmail.fm>
Message-ID: <3D21A53E.6060906@venix.com>

(I presume Danny is asleep by this time.)
Simply delete the two lines that contain cgitb references, or make
them comments:
#import cgitb
#cgitb.enable()

cgitb ONLY comes into play if your script fails and raises an exception.
You can omit cgitb without affecting your normal processing.

Kyle Babich wrote:

> I would like to do the entire thing without cgitb because I don't have
> the module and I don't want to try to convincing my host to install it.
>  Is it possible to do it without cgitb?
> 
> On Tue, 2 Jul 2002 01:16:11 -0700 (PDT), "Danny Yoo"
> <dyoo@hkn.eecs.berkeley.edu> said:
> 
>>
>>On Mon, 1 Jul 2002, Kyle Babich wrote:
>>
>>
>>>How could I do this without cgitb?
>>>
>>Hi Kyle,
>>
>>Which part, exactly, would you like to do without the 'cgitb' traceback
>>module?  cgitb modifies the programming environment slightly so that
>>raised exceptions give nicely formatted error messages back to the web
>>browser.
>>
>>
>>Try commenting the cgitb lines first, and deliberately introduce a
>>syntax
>>error in the script --- you'll notice that the web server doesn't
>>output
>>too much useful information back to the user (although it will be in
>>the
>>error log).  On Apache, a bug in a CGI script brings up the
>>infuriatingly
>>uninformative "Internal Server Error" page.
>>
>>
>>Afterwards, uncomment the cgitb-related lines and try again, and you'll
>>see a difference.  It's not mandatory, but it is pretty useful.  I
>>usually
>>keep 'cgitb' on because it's such a nice debugging tool, and looks
>>nicer
>>than having to do a:
>>
>>    tail -f /var/log/apache/error.log
>>
>>which would be an alternative way of watching script problems.
>>
>>
>>If you have more questions, please feel free to ask!  By the way, it
>>sounds like you're coming from a Perl background.  How much Perl do you
>>know already?  We can tailor our answers to take advantage of your
>>experiences in other languages, if that would be helpful for you.
>>
>>
>>Good luck!
>>
>>
>>
>>
>>
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From Kyle Babich" <kb@kb5.org  Tue Jul  2 14:59:40 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Tue, 2 Jul 2002 13:59:40 +0000
Subject: [Tutor] Re: Translating to Python   [perl --> python]
Message-ID: <20020702135940.6F53A6D9C4@www.fastmail.fm>

Ok, well then something is still wrong because I'm still getting syntax
errors that I can't figure out.  Is there a python tutorial that is
more like cgi101.com (only python)?  (Ie. including source codes, live
working examples, and different sections for different commands)

Btw, here is the code again:

#!/usr/bin/env python

import cgi

print "Content-type: text/html\n\n"

form = cgi.FieldStorage()
c = form['c'].value
except KeyError :
c = ""
content = c
if c == 'abc':
content = "abc123"
elif c == 'def':
content = "def456"
else:
print "error: content failed\n"

file = open("text.txt")
text = file.read()
file.close()

print """

%(content)s


<br>&nbsp;<br>&nbsp;<br>&nbsp;

%(text)s

""" % vars()


It says there is an error near except KeyError: but I've never used
python before so I don't know what to change.

Thanks,
Kyle

On Tue, 02 Jul 2002 09:06:06 -0400, "Lloyd Kvam"
<pythontutor@venix.com> said:
> (I presume Danny is asleep by this time.)
> Simply delete the two lines that contain cgitb references, or make
> them comments:
> #import cgitb
> #cgitb.enable()
> 
> cgitb ONLY comes into play if your script fails and raises an
> exception.
> You can omit cgitb without affecting your normal processing.
> 
> Kyle Babich wrote:
> 
> > I would like to do the entire thing without cgitb because I don't have
> > the module and I don't want to try to convincing my host to install it.
> >  Is it possible to do it without cgitb?
> > 
> > On Tue, 2 Jul 2002 01:16:11 -0700 (PDT), "Danny Yoo"
> > <dyoo@hkn.eecs.berkeley.edu> said:
> > 
> >>
> >>On Mon, 1 Jul 2002, Kyle Babich wrote:
> >>
> >>
> >>>How could I do this without cgitb?
> >>>
> >>Hi Kyle,
> >>
> >>Which part, exactly, would you like to do without the 'cgitb' traceback
> >>module?  cgitb modifies the programming environment slightly so that
> >>raised exceptions give nicely formatted error messages back to the web
> >>browser.
> >>
> >>
> >>Try commenting the cgitb lines first, and deliberately introduce a
> >>syntax
> >>error in the script --- you'll notice that the web server doesn't
> >>output
> >>too much useful information back to the user (although it will be in
> >>the
> >>error log).  On Apache, a bug in a CGI script brings up the
> >>infuriatingly
> >>uninformative "Internal Server Error" page.
> >>
> >>
> >>Afterwards, uncomment the cgitb-related lines and try again, and you'll
> >>see a difference.  It's not mandatory, but it is pretty useful.  I
> >>usually
> >>keep 'cgitb' on because it's such a nice debugging tool, and looks
> >>nicer
> >>than having to do a:
> >>
> >>    tail -f /var/log/apache/error.log
> >>
> >>which would be an alternative way of watching script problems.
> >>
> >>
> >>If you have more questions, please feel free to ask!  By the way, it
> >>sounds like you're coming from a Perl background.  How much Perl do you
> >>know already?  We can tailor our answers to take advantage of your
> >>experiences in other languages, if that would be helpful for you.
> >>
> >>
> >>Good luck!
> >>
> >>
> >>
> >>
> >>
> > 
> > 
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> > 
> 
> 
> -- 
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
> 
> voice: 
> 603-443-6155
> fax: 
> 801-459-9582
> 
> 
> 
> 
> 



From dman@dman.ddts.net  Tue Jul  2 15:30:22 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 2 Jul 2002 09:30:22 -0500
Subject: [Tutor] Re: Re: Translating to Python   [perl --> python]
In-Reply-To: <20020702135940.6F53A6D9C4@www.fastmail.fm>
References: <20020702135940.6F53A6D9C4@www.fastmail.fm>
Message-ID: <20020702143022.GA30506@dman.ddts.net>

--WIyZ46R2i8wDzkSu
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 02, 2002 at 01:59:40PM +0000, Kyle Babich wrote:
| Ok, well then something is still wrong because I'm still getting syntax
| errors that I can't figure out.  Is there a python tutorial that is
| more like cgi101.com (only python)?  (Ie. including source codes, live
| working examples, and different sections for different commands)

http://python.org/doc/current/tut/tut.html

It covers the python language.  Working with CGI is trivial once you
know the language -- just use the same environment variables as always
(found in the 'os.environ' dictionary) and use the cgi.FieldStorage
class to parse form submissions.
=20
| Btw, here is the code again:
|=20
| #!/usr/bin/env python
|=20
| import cgi
|=20
| print "Content-type: text/html\n\n"
|=20
| form =3D cgi.FieldStorage()
  try:
  ^^^^
      c =3D form['c'].value
  ^^^^
| except KeyError :
      c =3D ""
  ^^^^
| content =3D c
| if c =3D=3D 'abc':
      content =3D "abc123"
  ^^^^
| elif c =3D=3D 'def':
      content =3D "def456"
  ^^^^
| else:
      print "error: content failed\n"
  ^^^^

| It says there is an error near except KeyError:

The 'except' keyword can only be used after a 'try:'.  Just like in
perl you can't put "else" all over the place, only after an "if".
Also, you need to indent the blocks of compound statements.  If, in
perl, it would have had curly braces around it, indent it.

| but I've never used python before so I don't know what to change.

Read Guido's tutorial.  It is very easy to read if you already know
the basics of programming (which you do if you've used perl before).

HTH,
-D

--=20

A kindhearted woman gains respect,
but ruthless men gain only wealth.
        Proverbs 11:16
=20
http://dman.ddts.net/~dman/


--WIyZ46R2i8wDzkSu
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0huP4ACgkQO8l8XBKTpRS+vgCgj8XX6uSXGdgtsTty31LSDY2I
S2kAoLEq1uZyHLjv2PQWaWSGvmikTd6k
=GBN1
-----END PGP SIGNATURE-----

--WIyZ46R2i8wDzkSu--



From pythontutor@venix.com  Tue Jul  2 15:34:44 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 02 Jul 2002 10:34:44 -0400
Subject: [Tutor] Re: Translating to Python   [perl --> python]
References: <20020702135940.6F53A6D9C4@www.fastmail.fm>
Message-ID: <3D21BA04.1010700@venix.com>

try:
     c = form['c'].value
except KeyError:
     c = ""

The except statement must be paired with a try.  Also, I hope that
the lack of indentation is an artifact of your email program.
Python uses indentation  rather than braces or other character
markers to indicate the extent of "code blocks". So for instance:

if <something is true>:
	<block of code for
	this being true is indented>
elif <some other thing>:
	<also indented >
else:
	<indented block for neither thing true>
<back to main flow with no indent>

Kyle Babich wrote:

> Ok, well then something is still wrong because I'm still getting syntax
> errors that I can't figure out.  Is there a python tutorial that is
> more like cgi101.com (only python)?  (Ie. including source codes, live
> working examples, and different sections for different commands)
> 
> Btw, here is the code again:
> 
> #!/usr/bin/env python
> 
> import cgi
> 
> print "Content-type: text/html\n\n"
> 
> form = cgi.FieldStorage()
> c = form['c'].value
> except KeyError :
> c = ""
> content = c
> if c == 'abc':
> content = "abc123"
> elif c == 'def':
> content = "def456"
> else:
> print "error: content failed\n"
> 
> file = open("text.txt")
> text = file.read()
> file.close()
> 
> print """
> 
> %(content)s
> 
> 
> <br>&nbsp;<br>&nbsp;<br>&nbsp;
> 
> %(text)s
> 
> """ % vars()
> 
> 
> It says there is an error near except KeyError: but I've never used
> python before so I don't know what to change.
> 
> Thanks,
> Kyle
> 
> On Tue, 02 Jul 2002 09:06:06 -0400, "Lloyd Kvam"
> <pythontutor@venix.com> said:
> 
>>(I presume Danny is asleep by this time.)
>>Simply delete the two lines that contain cgitb references, or make
>>them comments:
>>#import cgitb
>>#cgitb.enable()
>>
>>cgitb ONLY comes into play if your script fails and raises an
>>exception.
>>You can omit cgitb without affecting your normal processing.
>>
>>Kyle Babich wrote:
>>
>>
>>>I would like to do the entire thing without cgitb because I don't have
>>>the module and I don't want to try to convincing my host to install it.
>>> Is it possible to do it without cgitb?
>>>
>>>On Tue, 2 Jul 2002 01:16:11 -0700 (PDT), "Danny Yoo"
>>><dyoo@hkn.eecs.berkeley.edu> said:
>>>
>>>
>>>>On Mon, 1 Jul 2002, Kyle Babich wrote:
>>>>
>>>>
>>>>
>>>>>How could I do this without cgitb?
>>>>>
>>>>>
>>>>Hi Kyle,
>>>>
>>>>Which part, exactly, would you like to do without the 'cgitb' traceback
>>>>module?  cgitb modifies the programming environment slightly so that
>>>>raised exceptions give nicely formatted error messages back to the web
>>>>browser.
>>>>
>>>>
>>>>Try commenting the cgitb lines first, and deliberately introduce a
>>>>syntax
>>>>error in the script --- you'll notice that the web server doesn't
>>>>output
>>>>too much useful information back to the user (although it will be in
>>>>the
>>>>error log).  On Apache, a bug in a CGI script brings up the
>>>>infuriatingly
>>>>uninformative "Internal Server Error" page.
>>>>
>>>>
>>>>Afterwards, uncomment the cgitb-related lines and try again, and you'll
>>>>see a difference.  It's not mandatory, but it is pretty useful.  I
>>>>usually
>>>>keep 'cgitb' on because it's such a nice debugging tool, and looks
>>>>nicer
>>>>than having to do a:
>>>>
>>>>   tail -f /var/log/apache/error.log
>>>>
>>>>which would be an alternative way of watching script problems.
>>>>
>>>>
>>>>If you have more questions, please feel free to ask!  By the way, it
>>>>sounds like you're coming from a Perl background.  How much Perl do you
>>>>know already?  We can tailor our answers to take advantage of your
>>>>experiences in other languages, if that would be helpful for you.
>>>>
>>>>
>>>>Good luck!
>>>>
>>>>
>>>>
>>>>
>>>>
>>>>
>>>
>>>_______________________________________________
>>>Tutor maillist  -  Tutor@python.org
>>>http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>>
>>
>>-- 
>>Lloyd Kvam
>>Venix Corp.
>>1 Court Street, Suite 378
>>Lebanon, NH 03766-1358
>>
>>voice: 
>>603-443-6155
>>fax: 
>>801-459-9582
>>
>>
>>
>>
>>
>>
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From alan.gauld@bt.com  Tue Jul  2 15:30:32 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 2 Jul 2002 15:30:32 +0100
Subject: [Tutor] Re: Translating to Python   [perl --> python]
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6E7@mbtlipnt02.btlabs.bt.co.uk>

> import cgi
> 
> print "Content-type: text/html\n\n"
> 

try:    ####### need 'try' to get 'except' to work... ####
 	form = cgi.FieldStorage()
 	c = form['c'].value
except KeyError :
 	c = ""

Notice the indentation above, it is critical.

> content = c
> if c == 'abc':
> content = "abc123"

again you have no indentation, Python needs the 
indentation its not just a matter of style.

> elif c == 'def':
> content = "def456"
> else:
> print "error: content failed\n"
> 
> file = open("text.txt")
> text = file.read()
> file.close()
> 
> print """
> 
> %(content)s
> 
> 
> <br>&nbsp;<br>&nbsp;<br>&nbsp;
> 
> %(text)s
> 
> """ % vars()
> 
> 
> It says there is an error near except KeyError: but I've never used
> python before so I don't know what to change.

Thats the lack of try first and the lack of indentation second


Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From Kyle Babich" <kb@kb5.org  Tue Jul  2 17:12:17 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Tue, 2 Jul 2002 16:12:17 +0000
Subject: [Tutor] Re: Re: Translating to Python   [perl --> python]
Message-ID: <20020702161218.4C4716DB1A@www.fastmail.fm>

It works!  :)  Thank you.

My next question is how do I open a file for appending vs.
overwritting?  I don't see this in any tutorials.  (or maybe I'm just
missing it)

On Tue, 2 Jul 2002 09:30:22 -0500, "Derrick 'dman' Hudson"
<dman@dman.ddts.net> said:
> On Tue, Jul 02, 2002 at 01:59:40PM +0000, Kyle Babich wrote:
> | Ok, well then something is still wrong because I'm still getting
> syntax
> | errors that I can't figure out.  Is there a python tutorial that is
> | more like cgi101.com (only python)?  (Ie. including source codes,
> live
> | working examples, and different sections for different commands)
> 
> http://python.org/doc/current/tut/tut.html
> 
> It covers the python language.  Working with CGI is trivial once you
> know the language -- just use the same environment variables as always
> (found in the 'os.environ' dictionary) and use the cgi.FieldStorage
> class to parse form submissions.
>  
> | Btw, here is the code again:
> | 
> | #!/usr/bin/env python
> | 
> | import cgi
> | 
> | print "Content-type: text/html\n\n"
> | 
> | form = cgi.FieldStorage()
>   try:
>   ^^^^
>       c = form['c'].value
>   ^^^^
> | except KeyError :
>       c = ""
>   ^^^^
> | content = c
> | if c == 'abc':
>       content = "abc123"
>   ^^^^
> | elif c == 'def':
>       content = "def456"
>   ^^^^
> | else:
>       print "error: content failed\n"
>   ^^^^
> 
> | It says there is an error near except KeyError:
> 
> The 'except' keyword can only be used after a 'try:'.  Just like in
> perl you can't put "else" all over the place, only after an "if".
> Also, you need to indent the blocks of compound statements.  If, in
> perl, it would have had curly braces around it, indent it.
> 
> | but I've never used python before so I don't know what to change.
> 
> Read Guido's tutorial.  It is very easy to read if you already know
> the basics of programming (which you do if you've used perl before).
> 
> HTH,
> -D
> 
> -- 
> 
> A kindhearted woman gains respect,
> but ruthless men gain only wealth.
>         Proverbs 11:16
>  
> http://dman.ddts.net/~dman/
> 



From dyoo@hkn.eecs.berkeley.edu  Tue Jul  2 17:35:23 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 2 Jul 2002 09:35:23 -0700 (PDT)
Subject: [Tutor] Re: Translating to Python   [cgitb for Python 2.1]
In-Reply-To: <20020702112610.C34A76DA1C@www.fastmail.fm>
Message-ID: <Pine.LNX.4.44.0207020929120.16569-100000@hkn.eecs.berkeley.edu>


On Tue, 2 Jul 2002, Kyle Babich wrote:

> I would like to do the entire thing without cgitb because I don't have
> the module and I don't want to try to convincing my host to install it.

By the way, although 'cgitb' is a standard part of Python 2.2, it's also
available for Python 2.1:

    http://web.lfw.org/python/


Talk to you later!




From dyoo@hkn.eecs.berkeley.edu  Tue Jul  2 17:27:44 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 2 Jul 2002 09:27:44 -0700 (PDT)
Subject: [Tutor] Re: Re: Translating to Python   [perl --> python]
In-Reply-To: <20020702161218.4C4716DB1A@www.fastmail.fm>
Message-ID: <Pine.LNX.4.44.0207020921250.16569-100000@hkn.eecs.berkeley.edu>


On Tue, 2 Jul 2002, Kyle Babich wrote:

> It works!  :)  Thank you.

Very cool!


> My next question is how do I open a file for appending vs. overwritting?
> I don't see this in any tutorials.  (or maybe I'm just missing it)

For this, you'll want to tell open() to read your file in "append" mode.
So something like:

###
>>> f = open('helloworld.txt', 'w')
>>> f.write("hello!")
>>> f.close
<built-in method close of file object at 0x8151640>
>>> f.close()
>>> f = open('helloworld.txt', 'a')
>>> f.write(' world!')
>>> f.close()
>>> f = open('helloworld.txt', 'r')
>>> content = f.read()
>>> print content
hello! world!
###



By the way, notice what happens when I forget to use parentheses in the
f.close:

###
>>> f.close
<built-in method close of file object at 0x8151640>
###

That's because, even if a function doesn't take any arguments, it doesn't
"fire off" until parentheses are used.  What this statement is doing,
instead, is giving us the function itself as an object.  The closest
analogy to Perl would be taking a reference to a subroutine object.


For more information about open(), you can take a look at:

    http://www.python.org/doc/lib/built-in-funcs.html#built-in-funcs


Best of wishes!




From Kyle Babich" <kb@kb5.org  Tue Jul  2 19:00:07 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Tue, 2 Jul 2002 18:00:07 +0000
Subject: [Tutor] Env Vars
Message-ID: <20020702180007.CD6C66D9EB@www.fastmail.fm>

How do environment variables work in python?  I couldn't seem to find
documentation for this either.

Thanks,
Kyle



From pythontutor@venix.com  Tue Jul  2 19:27:50 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 02 Jul 2002 14:27:50 -0400
Subject: [Tutor] setting up a timer
Message-ID: <3D21F0A6.7060507@venix.com>

I have some logic for starting and connecting to a MySQL database that I
believe could get stuck because of network problems or remote server
problems.  I'd like to have a timer to simply cancel the process if it is
not successful in a reasonable time frame.  My search didn't turn up any
examples, so I coded the following (my unix/C roots are showing).

Then I discovered that signal.alarm is NOT available in Windows.  Mark
Hammond's book (Python Programming on Win32) was no help.  Please point
me in the right direction.

def timeout( signo, frame):
	raise RuntimeError( "Timed out trying to connect to database server")

def startup( login_name, passwd, svc_host, datadir, dbname):
	signal.signal( signal.SIGALRM, timeout)
	signal.alarm( 20)	# allow twenty seconds to succeed
	while 1:
		if did_startup_successfully():
			break
	signal.alarm(0)		# cancel alarm		

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From jimmy_130@lycos.com  Tue Jul  2 19:42:43 2002
From: jimmy_130@lycos.com (James M Lang)
Date: Tue, 02 Jul 2002 14:42:43 -0400
Subject: [Tutor] Math symbols
Message-ID: <MEDCLFEOGPLFCAAA@mailcity.com>

My first experiances ( is that how you spell it?) with programming were with my TI-83+ graphing calculator. Now that I lost it, :( , I'm trying to solve a problem with Python.I'm attempting to have python use loops to guess and check.
 Here's the problem
Find the numbers which the letters represent
        SEND
       +MORE
--------------
        MONEY
Anyway, to get to the point, I'm used to the calculator's greater than or equal to or less than or equal sign. Of course, I realized that there isn't such a sign on the keyboard. So how do you use such a symbol in Python?


____________________________________________________________
Win a first-class trip to New Orleans and vacation Elvis Style!.
Enter NOW!
http://r.lycos.com/r/sagel_mail/http://www.elvis.lycos.com/sweepstakes/



From pythontutor@venix.com  Tue Jul  2 19:43:37 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 02 Jul 2002 14:43:37 -0400
Subject: [Tutor] Env Vars
References: <20020702180007.CD6C66D9EB@www.fastmail.fm>
Message-ID: <3D21F459.4040000@venix.com>

os.environ is a dictionary containing your environment names and values.

Also the cgi.test function will provide a great deal of information if
you are still working on cgi scripts.

Kyle Babich wrote:

> How do environment variables work in python?  I couldn't seem to find
> documentation for this either.
> 
> Thanks,
> Kyle
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From ponderor@lycos.com  Tue Jul  2 20:10:31 2002
From: ponderor@lycos.com (Dean Goodmanson)
Date: Tue, 02 Jul 2002 15:10:31 -0400
Subject: [Tutor] Regular Expressions  question about AND
Message-ID: <EGIHINNBLHNFCAAA@mailcity.com>

Greetings!

I'm using regular expressions to _validate_ a string.

I got the basic expression down when the Eureka light came on and I realized I needed to Search for All Valid posibilities .  

Alternation to the rescue!

Now, when a new feature was requested, I'm struggling to find the "AND" companion (just about said complement!;-)) to the Alternation's OR functionality.

My primary references include the first edition of _Mastering Regular Expressions_ and http://py-howto.sourceforge.net/regex/node13.html .

Thanks in advance,

Dean


____________________________________________________________
Win a first-class trip to New Orleans and vacation Elvis Style!.
Enter NOW!
http://r.lycos.com/r/sagel_mail/http://www.elvis.lycos.com/sweepstakes/



From ponderor@lycos.com  Tue Jul  2 20:14:10 2002
From: ponderor@lycos.com (Dean Goodmanson)
Date: Tue, 02 Jul 2002 15:14:10 -0400
Subject: [Tutor] Regular Expressions  question about AND - missing detail.
Message-ID: <CMFOHPPDOKNFCAAA@mailcity.com>

Now, when a new feature was requested, I'm struggling to find the "AND" companion (just about said complement!;-)) to the Alternation's OR functionality.

==
I'm not looking specificaly for "AND" functionality, but want to re-create the logic of NOT AND:

This AND NOT that , such as: Any Non-whitespace that does NOT include a decimal: potentially \S&&\D  , where && represents "and"


____________________________________________________________
Win a first-class trip to New Orleans and vacation Elvis Style!.
Enter NOW!
http://r.lycos.com/r/sagel_mail/http://www.elvis.lycos.com/sweepstakes/



From glingl@aon.at  Tue Jul  2 20:29:34 2002
From: glingl@aon.at (Gregor Lingl)
Date: Tue, 2 Jul 2002 21:29:34 +0200
Subject: [Tutor] Math symbols
References: <MEDCLFEOGPLFCAAA@mailcity.com>
Message-ID: <000c01c221fe$cc3fac90$1615a8c0@mega>

----- Original Message -----
From: "James M Lang" <jimmy_130@lycos.com>
To: <tutor@python.org>

> Anyway, to get to the point, I'm used to the calculator's greater than or
equal to or less than or equal sign. Of course, I realized that there isn't
such a sign on the keyboard. So how do you use such a symbol in Python?
>

We write >=  or <= respectively.
So using the interactive Python interpreter we observe:

>>> 3 <= 4
1              # this means true in Python
>>> 4 <= 4
1
>>> 5 <= 4
0              # an this means false
>>> 5 >= 4
1
>>> if 5 >= 4:
        print "This is ok!"
else:
        print "Wrong!"


This is ok!
>>>

And so on! Have fun!

Gregor




From rob@uselesspython.com  Tue Jul  2 21:44:31 2002
From: rob@uselesspython.com (Rob)
Date: Tue, 02 Jul 2002 15:44:31 -0500
Subject: [Tutor] small program in Python and in C++
Message-ID: <3D2210AF.4070702@uselesspython.com>

This is a multi-part message in MIME format.
--------------060709020104040202020000
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit

Someone here found a formula in the newspaper to tell if you are obese, 
but she couldn't follow it (even worse math skills than my own, it 
seems), so I wrote her a Python program to run the calculation. I wound 
up writing a C++ equivalent for someone else a few minutes later (and he 
promises me he'll send me a PHP version tonight to return the favor).

I thought I'd pass it all along to the Tutor list in case it makes a 
good example for anyone (or if anyone cared to point out other ways to 
do it, etc.). If you know a little C++ and are looking into Python, or 
vice versa, you might like it on some level.

Rob
http://uselesspython.com
-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show

--------------060709020104040202020000
Content-Type: text/plain;
 name="obesity.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="obesity.py"

# fetch height and weight from user
height = float(raw_input("\nWhat is your height in inches? "))
weight = float(raw_input("\nWhat is your weight in pounds? "))

# calculate body mass index
bodyMassIndex = 703 * ( weight / ( height * height ) )

# print obesity judgement
print "\nYour Body Mass Index is " + str(bodyMassIndex)
if bodyMassIndex >= 30:
    print "\nYou are obese.\n"
else:
    print "\nYou are not obese.\n"

--------------060709020104040202020000
Content-Type: text/plain;
 name="obesity.cpp"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="obesity.cpp"

#include <iostream>
using namespace std;

int main()
{
    // fetch data from the user
    cout << endl << "What is your height in inches? ";
    float height;
    cin >> height;
    cout << endl << "What is your weight in pounds? ";
    float weight;
    cin >> weight;
    
    // calculate body mass index
    float bodyMassIndex;
    bodyMassIndex = 703 * ( weight / ( height * height ) );
    
    // display obesity judgement
    cout << "\nYour Body Mass Index is " << bodyMassIndex << endl;
    if (bodyMassIndex >= 30)
        cout << "\nYou are obese." << endl;
    else
        cout << "\nYou are not obese." << endl;
        
    return 0;
}

--------------060709020104040202020000--





From Kyle Babich" <kb@kb5.org  Tue Jul  2 21:51:17 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Tue, 2 Jul 2002 20:51:17 +0000
Subject: [Tutor] Env Vars
Message-ID: <20020702205117.7DA796DA6F@www.fastmail.fm>

How do I use it, find out what variables it includes?
Also, how do I get raw_input to work in a browser?

On Tue, 02 Jul 2002 14:43:37 -0400, "Lloyd Kvam"
<pythontutor@venix.com> said:
> os.environ is a dictionary containing your environment names and
> values.
> 
> Also the cgi.test function will provide a great deal of information if
> you are still working on cgi scripts.
> 
> Kyle Babich wrote:
> 
> > How do environment variables work in python?  I couldn't seem to find
> > documentation for this either.
> > 
> > Thanks,
> > Kyle
> > 
> > 
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> > 
> 
> 
> -- 
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
> 
> voice: 
> 603-443-6155
> fax: 
> 801-459-9582
> 
> 
> 
> 
> 



From dyoo@hkn.eecs.berkeley.edu  Tue Jul  2 22:03:18 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 2 Jul 2002 14:03:18 -0700 (PDT)
Subject: [Tutor] setting up a timer
In-Reply-To: <3D21F0A6.7060507@venix.com>
Message-ID: <Pine.LNX.4.44.0207021352250.18738-100000@hkn.eecs.berkeley.edu>


On Tue, 2 Jul 2002, Lloyd Kvam wrote:

> I have some logic for starting and connecting to a MySQL database that I
> believe could get stuck because of network problems or remote server
> problems.  I'd like to have a timer to simply cancel the process if it
> is not successful in a reasonable time frame.  My search didn't turn up
> any examples, so I coded the following (my unix/C roots are showing).
>
> Then I discovered that signal.alarm is NOT available in Windows.  Mark
> Hammond's book (Python Programming on Win32) was no help.
>
> Please point me in the right direction.

Hi Lloyd!

There's a "Timer" class in the threading module that might be useful: it
uses threads underneath, so it should be usable with Windows:

    http://python.org/doc/current/lib/timer-objects.html


Hope this helps!




From dyoo@hkn.eecs.berkeley.edu  Tue Jul  2 22:09:53 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 2 Jul 2002 14:09:53 -0700 (PDT)
Subject: [Tutor] Env Vars
In-Reply-To: <20020702205117.7DA796DA6F@www.fastmail.fm>
Message-ID: <Pine.LNX.4.44.0207021403410.18738-100000@hkn.eecs.berkeley.edu>


On Tue, 2 Jul 2002, Kyle Babich wrote:

> How do I use it, find out what variables it includes?

Ah!  In Python, a dictionary-like object will respond to a keys() method
call by giving back a list of the variables it contains.  For example:

###
>>> os.environ.keys()
['PERL_BADLANG', 'LS_COLORS', 'MAIL', 'COLORTERM', 'PWD', 'GDM_LANG',
'HOSTNAME', 'PERL5LIB', 'LD_PRELOAD', 'LD_LIBRARY_PATH', '_', 'BASH_ENV',
'GDMSESSION', 'CLASSPATH', 'SSH_AUTH_SOCK', 'PYTHONPATH', 'CVSEDITOR',
'PATH', 'USERNAME', 'CVSROOT', 'JAVA_HOME', 'XMODIFIERS', 'OSTYPE',
'WINDOWID', 'WNHOME', 'HISTSIZE', 'QTDIR', 'SHLVL', 'SESSION_MANAGER',
'XAUTHORITY', 'SHELL', 'TERM', 'KDEDIR', 'LANG', 'SSH_AGENT_PID',
'DISPLAY', 'HOME', 'INPUTRC', 'USER', 'LOGNAME', 'CVS_RSH', 'LESSOPEN',
'HOSTTYPE', 'MACHTYPE', 'GNOME_SESSION_NAME', 'SSH_ASKPASS']
###


For more information on dictionaries, see:

    http://www.python.org/doc/lib/typesmapping.html

and for os.environ(), see:

    http://www.python.org/doc/lib/os-procinfo.html




> Also, how do I get raw_input to work in a browser?

This probably won't work: CGI's are inherantly based in the HTML form
model, where all the input is sent, batched, through the QUERY_STRING
environmental variable.

Hmmm... what are you trying to read back from the user, by the way?  Does
it have to be interactive?


Talk to you later!




From pythontutor@venix.com  Tue Jul  2 22:10:36 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 02 Jul 2002 17:10:36 -0400
Subject: [Tutor] setting up a timer
References: <Pine.LNX.4.44.0207021352250.18738-100000@hkn.eecs.berkeley.edu>
Message-ID: <3D2216CC.2070005@venix.com>

Thanks, Danny.

Danny Yoo wrote:

> 
> On Tue, 2 Jul 2002, Lloyd Kvam wrote:
> 
> 
>>I have some logic for starting and connecting to a MySQL database that I
>>believe could get stuck because of network problems or remote server
>>problems.  I'd like to have a timer to simply cancel the process if it
>>is not successful in a reasonable time frame.  My search didn't turn up
>>any examples, so I coded the following (my unix/C roots are showing).
>>
>>Then I discovered that signal.alarm is NOT available in Windows.  Mark
>>Hammond's book (Python Programming on Win32) was no help.
>>
>>Please point me in the right direction.
>>
> 
> Hi Lloyd!
> 
> There's a "Timer" class in the threading module that might be useful: it
> uses threads underneath, so it should be usable with Windows:
> 
>     http://python.org/doc/current/lib/timer-objects.html
> 
> 
> Hope this helps!
> 
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From dyoo@hkn.eecs.berkeley.edu  Tue Jul  2 22:24:11 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 2 Jul 2002 14:24:11 -0700 (PDT)
Subject: [Tutor] Regular Expressions  question about AND - missing detail.
In-Reply-To: <CMFOHPPDOKNFCAAA@mailcity.com>
Message-ID: <Pine.LNX.4.44.0207021414300.18738-100000@hkn.eecs.berkeley.edu>


On Tue, 2 Jul 2002, Dean Goodmanson wrote:

> Now, when a new feature was requested, I'm struggling to find the "AND"
> companion (just about said complement!;-)) to the Alternation's OR
> functionality.
>
> ==
> I'm not looking specificaly for "AND" functionality, but want to
> re-create the logic of NOT AND:
>
>
> This AND NOT that , such as: Any Non-whitespace that does NOT include a
> decimal: potentially \S&&\D , where && represents "and"


Hmmm... if we're trying to find a character that is both not whitespace
and not a decimal, we can play with the logic a little:

    (not whitespace) and (not decimal) <===> not (whitespace or decimal)

This is a systematic transformation between AND and OR, or vice versa.
*grin* I think the logic rule is called De Morgan's Law.  You can probably
use a negative assertion, in combination with alternation, to get the
regular expression you want.

But would a negative character class have the effect that you're looking
for?  That might be simpler to check:

###
>>> pattern = re.compile(r'[^\s\.]')
>>> pattern.search('f')
<SRE_Match object at 0x80cbaa0>
>>> pattern.search('.')
>>> pattern.search(' ')
>>> pattern.search(']')
<SRE_Match object at 0x8133228>
###




Hope this helps!




From john@pertalion.org  Tue Jul  2 22:51:22 2002
From: john@pertalion.org (John Pertalion)
Date: Tue, 2 Jul 2002 17:51:22 -0400
Subject: [Tutor] setting up a timer
In-Reply-To: <3D21F0A6.7060507@venix.com>
Message-ID: <DHENJFCDEPKIKGEFBLAHIEJBCMAA.john@pertalion.org>

Hello,

I've used timeoutsocket.py module when connecting to a MySQL database over a
questionable network (the Internet).  It lets you define a timeout in
seconds for ALL socket connections.  It throws a timeoutsocket.Timeout
exception when the connection isn't made within the timeout.  And has worked
great for me with connections using MySQLdb and smtplib.  Available at
http://www.timo-tasi.org/python/timeoutsocket.py

John Pertalion

> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Lloyd Kvam
> Sent: Tuesday, July 02, 2002 2:28 PM
> To: Tutor Python
> Subject: [Tutor] setting up a timer
>
>
> I have some logic for starting and connecting to a MySQL database that I
> believe could get stuck because of network problems or remote server
> problems.  I'd like to have a timer to simply cancel the process if it is
> not successful in a reasonable time frame.  My search didn't turn up any
> examples, so I coded the following (my unix/C roots are showing).
>
> Then I discovered that signal.alarm is NOT available in Windows.  Mark
> Hammond's book (Python Programming on Win32) was no help.  Please point
> me in the right direction.
>
> def timeout( signo, frame):
> 	raise RuntimeError( "Timed out trying to connect to
> database server")
>
> def startup( login_name, passwd, svc_host, datadir, dbname):
> 	signal.signal( signal.SIGALRM, timeout)
> 	signal.alarm( 20)	# allow twenty seconds to succeed
> 	while 1:
> 		if did_startup_successfully():
> 			break
> 	signal.alarm(0)		# cancel alarm
>
> --
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
>
> voice:
> 603-443-6155
> fax:
> 801-459-9582
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>





From dyoo@hkn.eecs.berkeley.edu  Tue Jul  2 23:04:49 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 2 Jul 2002 15:04:49 -0700 (PDT)
Subject: [Tutor] small program in Python and in C++
In-Reply-To: <3D2210AF.4070702@uselesspython.com>
Message-ID: <Pine.LNX.4.44.0207021452090.23522-100000@hkn.eecs.berkeley.edu>


On Tue, 2 Jul 2002, Rob wrote:

> I thought I'd pass it all along to the Tutor list in case it makes a
> good example for anyone (or if anyone cared to point out other ways to
> do it, etc.). If you know a little C++ and are looking into Python, or
> vice versa, you might like it on some level.
>
>
> # calculate body mass index
> bodyMassIndex = 703 * ( weight / ( height * height ) )

It might be good to make this a function --- even though it's so simple,
having it as a function makes it easy to reuse this calculation if we ever
need it later.  As an additional bonus, if we write it as a function, we
can play with it very easily within the interactive interpreter:


###
>>> def bodyMassIndex(weight, height):
...     return 703 * ( weight / ( height * height ) )
...
>>> bodyMassIndex(175, 6.5)
2911.834319526627
>>> bodyMassIndex(175, 6)
2812
###


Oh!  It also reveals that we need to be careful about the types that we
use to do the calculation when division comes into play.


C++'s variable typing forces weight and height to be floats, but we don't
restrict the same in Python. If "from __future__ import true_division"
isn't on, we should probably force floating point division:

###
>>> def bodyMassIndex(weight, height):
...     return 703 * ( weight / float( height * height ) )
...
>>> bodyMassIndex(175, 6)
3417.3611111111109
###


Hope this helps!




From rob@uselesspython.com  Tue Jul  2 23:27:00 2002
From: rob@uselesspython.com (Rob)
Date: Tue, 02 Jul 2002 17:27:00 -0500
Subject: [Tutor] small program in Python and in C++
References: <Pine.LNX.4.44.0207021452090.23522-100000@hkn.eecs.berkeley.edu>
Message-ID: <3D2228B4.1010703@uselesspython.com>

This is a multi-part message in MIME format.
--------------030709000100070406090702
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit

Quite right. Attached is a C++ source file with the formula wrapped in a 
function.

Another friend contributed this equivalent (but not with the function) 
version in Perl:


#!/usr/bin/perl

print "What is your height in inches? ";
$inches=<STDIN>;
print "What is your weight in pounds? ";
$pounds=<STDIN>;

$bmi= 703 * ($pounds/($inches*$inches));

print "Your body mass index is $bmi\n";

if ($bmi>=30) { print "You are obese!\n"; }
else { print "You are not obese!\n"; }


Happy Hacking,
Rob
http://uselesspython.com

Danny Yoo wrote:

> 
> On Tue, 2 Jul 2002, Rob wrote:
> 
> 
>>I thought I'd pass it all along to the Tutor list in case it makes a
>>good example for anyone (or if anyone cared to point out other ways to
>>do it, etc.). If you know a little C++ and are looking into Python, or
>>vice versa, you might like it on some level.
>>
>>
>># calculate body mass index
>>bodyMassIndex = 703 * ( weight / ( height * height ) )
>>
> 
> It might be good to make this a function --- even though it's so simple,
> having it as a function makes it easy to reuse this calculation if we ever
> need it later.  As an additional bonus, if we write it as a function, we
> can play with it very easily within the interactive interpreter:
> 
> 
> ###
> 
>>>>def bodyMassIndex(weight, height):
>>>>
> ...     return 703 * ( weight / ( height * height ) )
> ...
> 
>>>>bodyMassIndex(175, 6.5)
>>>>
> 2911.834319526627
> 
>>>>bodyMassIndex(175, 6)
>>>>
> 2812
> ###
> 
> 
> Oh!  It also reveals that we need to be careful about the types that we
> use to do the calculation when division comes into play.
> 
> 
> C++'s variable typing forces weight and height to be floats, but we don't
> restrict the same in Python. If "from __future__ import true_division"
> isn't on, we should probably force floating point division:
> 
> ###
> 
>>>>def bodyMassIndex(weight, height):
>>>>
> ...     return 703 * ( weight / float( height * height ) )
> ...
> 
>>>>bodyMassIndex(175, 6)
>>>>
> 3417.3611111111109
> ###
> 
> 
> Hope this helps!
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show

--------------030709000100070406090702
Content-Type: text/plain;
 name="obesityFunc.cpp"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="obesityFunc.cpp"

#include <iostream>
using namespace std;

// function prototype for getBMI()
// A function prototype appearing before the function is called
//     in a program tell the program how to talk to the function.
float getBMI(float, float);

int main()
{
    // fetch data from the user
    cout << endl << "What is your height in inches? ";
    float height;
    cin >> height;
    cout << endl << "What is your weight in pounds? ";
    float weight;
    cin >> weight;
    
    // calculate body mass index
    float bodyMassIndex;
    bodyMassIndex = getBMI(height, weight);
    
    // display obesity judgement
    cout << "\nYour Body Mass Index is " << bodyMassIndex << endl;
    if (bodyMassIndex >= 30)
        cout << "\nYou are obese." << endl;
    else
        cout << "\nYou are not obese." << endl;
        
    return 0;
}

//---------------------------------------------------------------
// In this function, "height" could just as easily read "inches",
//     and "weight" could just as easily read "pounds"
//     without having to change anything outside the function.
//     Just a handy fact for those who are new to C++.
float getBMI(float height, float weight)
{
    return 703 * ( weight / ( height * height ) );
}

--------------030709000100070406090702--





From dman@dman.ddts.net  Wed Jul  3 00:14:10 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 2 Jul 2002 18:14:10 -0500
Subject: [Tutor] Re: Env Vars
In-Reply-To: <20020702180007.CD6C66D9EB@www.fastmail.fm>
References: <20020702180007.CD6C66D9EB@www.fastmail.fm>
Message-ID: <20020702231410.GA4084@dman.ddts.net>

--J2SCkAp4GZ/dPZZf
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 02, 2002 at 06:00:07PM +0000, Kyle Babich wrote:
| How do environment variables work in python?  I couldn't seem to find
| documentation for this either.

You won't find that sort of thing in the tutorial.  The tutorial is
designed to introduce you to the core _language_ functionality.
Unlike perl but rather like C, python's core language is quite
minimal.  All the really fancy features are implemented either in the
standard library or in additional libraries that can be installed.  To
find out what is in the standard library, read the Library Reference
(also in the "Documentation" section of python.org, I don't have the
url in hand right now).  Do note that the library reference is just
that -- a library reference.  It is not a tutorial and won't cover
the python language, just the library.

In the library reference you'll find info on the 'os' module, which is
where operating system stuff (like the environment) is contained.
You'll also find the built-in functions and the operations supported
by the built-in types (eg dictionaries) documented.

HTH,
-D

--=20

Your beauty should not come from outward adornment, such as braided hair
and the wearing of gold jewelry and fine clothes.  Instead, it should be
that of your inner self, the unfading beauty of a gentle and quiet
spirit, which is of GREAT WORTH in God's sight.  For this is the way the
holy women of the past used to make themselves beautiful.
        I Peter 3:3-5
=20
http://dman.ddts.net/~dman/


--J2SCkAp4GZ/dPZZf
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0iM8IACgkQO8l8XBKTpRTffACgk/e3hmj/8jenSQFBY5+oAR/X
wv0AmwVv2qcl/vvk2UTw7iUP98e3PWma
=7BEj
-----END PGP SIGNATURE-----

--J2SCkAp4GZ/dPZZf--



From Kyle Babich" <kb@kb5.org  Wed Jul  3 00:32:22 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Tue, 2 Jul 2002 23:32:22 +0000
Subject: [Tutor] Env Vars
Message-ID: <20020702233222.6F2996DA1A@www.fastmail.fm>

Now I'm able to get it in the shell by importing os and then print
(os.environ['OSTYPE']) but I when I try to open it in the browser I
just get a blank page.

Also, so far my biggest problem with learning python has been the
text/html header.  What is the standard way of printing the text/html
header in python?

Thank you,
Kyle

On Tue, 2 Jul 2002 20:51:17 +0000, "Kyle Babich" <kb@kb5.org> said:
> How do I use it, find out what variables it includes?
> Also, how do I get raw_input to work in a browser?
> 
> On Tue, 02 Jul 2002 14:43:37 -0400, "Lloyd Kvam"
> <pythontutor@venix.com> said:
> > os.environ is a dictionary containing your environment names and
> > values.
> > 
> > Also the cgi.test function will provide a great deal of information if
> > you are still working on cgi scripts.
> > 
> > Kyle Babich wrote:
> > 
> > > How do environment variables work in python?  I couldn't seem to find
> > > documentation for this either.
> > > 
> > > Thanks,
> > > Kyle
> > > 
> > > 
> > > _______________________________________________
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > > 
> > > 
> > 
> > 
> > -- 
> > Lloyd Kvam
> > Venix Corp.
> > 1 Court Street, Suite 378
> > Lebanon, NH 03766-1358
> > 
> > voice: 
> > 603-443-6155
> > fax: 
> > 801-459-9582
> > 
> > 
> > 
> > 
> > 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 



From pythontutor@venix.com  Wed Jul  3 00:47:02 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 02 Jul 2002 19:47:02 -0400
Subject: [Tutor] setting up a timer
References: <DHENJFCDEPKIKGEFBLAHIEJBCMAA.john@pertalion.org>
Message-ID: <3D223B76.7040805@venix.com>

John, I haven't tried your suggestion yet.  My code includes checking if
the sql server is running with the correct configuration and restarting
it when necessary.  So I thought covering it all with one timer would be
simpler.

I implemented a timer to catch a connection/startup failure. I tested using
a while 1: loop to simulate a connection/startup failure.  The timer did
get triggered and it raised an exception.  However, raising an
exception doesn't terminate the process.  Is there a way to kill a thread?
Or is there some documentation about using exceptions with threads?

John Pertalion wrote:

> Hello,
> 
> I've used timeoutsocket.py module when connecting to a MySQL database over a
> questionable network (the Internet).  It lets you define a timeout in
> seconds for ALL socket connections.  It throws a timeoutsocket.Timeout
> exception when the connection isn't made within the timeout.  And has worked
> great for me with connections using MySQLdb and smtplib.  Available at
> http://www.timo-tasi.org/python/timeoutsocket.py
> 
> John Pertalion
> 
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From pythontutor@venix.com  Wed Jul  3 00:56:35 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 02 Jul 2002 19:56:35 -0400
Subject: [Tutor] Env Vars
References: <20020702233222.6F2996DA1A@www.fastmail.fm>
Message-ID: <3D223DB3.2060208@venix.com>

I've been using HTMLgen where there are complications in the generated
html.  To see the environment that your cgi script sees, simply run
the cgi test function.  Here's one way to do it:

#cgitest.py
import cgi
cgi.test()

Install this into yor cgi-bin directory and use your browser to
reference it, something like:
	webserver.com/cgi-bin/cgitest.py?var1=ABC&var2=DEF

You will get back a useful dump of the environment and the variables
supplied to the script.

Kyle Babich wrote:

> Now I'm able to get it in the shell by importing os and then print
> (os.environ['OSTYPE']) but I when I try to open it in the browser I
> just get a blank page.
> 
> Also, so far my biggest problem with learning python has been the
> text/html header.  What is the standard way of printing the text/html
> header in python?
> 
> Thank you,
> Kyle
> 
> On Tue, 2 Jul 2002 20:51:17 +0000, "Kyle Babich" <kb@kb5.org> said:
> 
>>How do I use it, find out what variables it includes?
>>Also, how do I get raw_input to work in a browser?
>>
>>On Tue, 02 Jul 2002 14:43:37 -0400, "Lloyd Kvam"
>><pythontutor@venix.com> said:
>>
>>>os.environ is a dictionary containing your environment names and
>>>values.
>>>
>>>Also the cgi.test function will provide a great deal of information if
>>>you are still working on cgi scripts.
>>>
>>>Kyle Babich wrote:
>>>
>>>
>>>>How do environment variables work in python?  I couldn't seem to find
>>>>documentation for this either.
>>>>
>>>>Thanks,
>>>>Kyle
>>>>
>>>>
>>>>_______________________________________________
>>>>Tutor maillist  -  Tutor@python.org
>>>>http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>>
>>>>
>>>
>>>-- 
>>>Lloyd Kvam
>>>Venix Corp.
>>>1 Court Street, Suite 378
>>>Lebanon, NH 03766-1358
>>>
>>>voice: 
>>>603-443-6155
>>>fax: 
>>>801-459-9582
>>>
>>>
>>>
>>>
>>>
>>>
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>
>>
>>
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From Kyle Babich" <kb@kb5.org  Wed Jul  3 02:14:58 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Wed, 3 Jul 2002 01:14:58 +0000
Subject: [Tutor] Env Vars
Message-ID: <20020703011458.164326D9BC@www.fastmail.fm>

I still am getting nothing, I'm probably doing it wrong.  Isn't there a
simple way of doing this?  I import os, then what to I type so I can
view it in the browser?  Can I get an example?  Thanks.

On Tue, 02 Jul 2002 19:56:35 -0400, "Lloyd Kvam"
<pythontutor@venix.com> said:
> I've been using HTMLgen where there are complications in the generated
> html.  To see the environment that your cgi script sees, simply run
> the cgi test function.  Here's one way to do it:
> 
> #cgitest.py
> import cgi
> cgi.test()
> 
> Install this into yor cgi-bin directory and use your browser to
> reference it, something like:
> 	webserver.com/cgi-bin/cgitest.py?var1=ABC&var2=DEF
> 
> You will get back a useful dump of the environment and the variables
> supplied to the script.
> 
> Kyle Babich wrote:
> 
> > Now I'm able to get it in the shell by importing os and then print
> > (os.environ['OSTYPE']) but I when I try to open it in the browser I
> > just get a blank page.
> > 
> > Also, so far my biggest problem with learning python has been the
> > text/html header.  What is the standard way of printing the text/html
> > header in python?
> > 
> > Thank you,
> > Kyle
> > 
> > On Tue, 2 Jul 2002 20:51:17 +0000, "Kyle Babich" <kb@kb5.org> said:
> > 
> >>How do I use it, find out what variables it includes?
> >>Also, how do I get raw_input to work in a browser?
> >>
> >>On Tue, 02 Jul 2002 14:43:37 -0400, "Lloyd Kvam"
> >><pythontutor@venix.com> said:
> >>
> >>>os.environ is a dictionary containing your environment names and
> >>>values.
> >>>
> >>>Also the cgi.test function will provide a great deal of information if
> >>>you are still working on cgi scripts.
> >>>
> >>>Kyle Babich wrote:
> >>>
> >>>
> >>>>How do environment variables work in python?  I couldn't seem to find
> >>>>documentation for this either.
> >>>>
> >>>>Thanks,
> >>>>Kyle
> >>>>
> >>>>
> >>>>_______________________________________________
> >>>>Tutor maillist  -  Tutor@python.org
> >>>>http://mail.python.org/mailman/listinfo/tutor
> >>>>
> >>>>
> >>>>
> >>>
> >>>-- 
> >>>Lloyd Kvam
> >>>Venix Corp.
> >>>1 Court Street, Suite 378
> >>>Lebanon, NH 03766-1358
> >>>
> >>>voice: 
> >>>603-443-6155
> >>>fax: 
> >>>801-459-9582
> >>>
> >>>
> >>>
> >>>
> >>>
> >>>
> >>
> >>_______________________________________________
> >>Tutor maillist  -  Tutor@python.org
> >>http://mail.python.org/mailman/listinfo/tutor
> >>
> >>
> >>
> >>
> >>
> > 
> > 
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> > 
> 
> 
> -- 
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
> 
> voice: 
> 603-443-6155
> fax: 
> 801-459-9582
> 
> 
> 
> 
> 



From val@vtek.com  Wed Jul  3 02:50:49 2002
From: val@vtek.com (val)
Date: Tue, 2 Jul 2002 21:50:49 -0400
Subject: [Tutor] installing/starting vPython
References: <02af01c2206a$515ff2e0$0193fea9@vt1000> <3D20D156.8090909@uselesspython.com>
Message-ID: <003801c22234$10598060$0193fea9@vt1000>

Rob,
    Thanx for your quick response.
    I've checked the OpenGL installation
    (BTW, this is a win2k, OpenGL under Python22).
    I couldn't run a single demo from the openGL demos dir.
    The messages were 'couldn't read memory...' and
    looks like the Tk has been involved.  In one
    case was a total crash... with auto reboot.

    Any pointers/instructions where to look?
thanx,
val


----- Original Message -----
From: "Rob" <rob@uselesspython.com>
To: <tutor@python.org>
Sent: Monday, July 01, 2002 6:01 PM
Subject: Re: [Tutor] installing/starting vPython


> It sounds like you might have a GL issue on your hands. What Operating
> System are you running?
>
> Rob
> http://uselesspython.com
>
> val wrote:
>
> > Hi The List,
> >     i downloaded and installed vPython for Python22.
> >     i'm trying to run demos from the Demos dir by double-
> >     clicking on *.py files.  It works impressively fine
> >     on my job (same win2k, both Py21 and Py22 are
installed).
> >     At home i have a standard message from vPython
> >     and then just an empty window (or two or three
> >     depending on the demo to be run).
> >
> >     Any help/advice would be very appreciated.
> > thanx,
> > val
> >
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
>
> --
> "Giving the Linus Torvalds Award to the Free Software Foundation is a
> bit like giving the Han Solo Award to the Rebel Alliance."
> --Richard Stallman at the 1999 LinuxWorld show
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From rob@uselesspython.com  Wed Jul  3 03:28:21 2002
From: rob@uselesspython.com (Rob)
Date: Tue, 02 Jul 2002 21:28:21 -0500
Subject: [Tutor] installing/starting vPython
References: <02af01c2206a$515ff2e0$0193fea9@vt1000> <3D20D156.8090909@uselesspython.com> <003801c22234$10598060$0193fea9@vt1000>
Message-ID: <3D226145.9080603@uselesspython.com>

If you do suspect your problem may be GL-related, you can go to Display 
Settings -> Troubleshooting tab and lower "Hardware acceleration" to 
None. Then click OK or Apply.

After this, try your VPython demos again and see if you have better 
luck. If they run with hardware acceleration off, but not with it on, 
this may confirm GL problems. In that case, I refer you to the VPython 
FAQ, which suggests a fix. http://vpython.org/FAQ.html

I actually have this problem on my laptop, but haven't taken the time to 
fix it because I can't afford the downtime just now.

hopefully helpful,
Rob
http://uselesspython.com

val wrote:

> Rob,
>     Thanx for your quick response.
>     I've checked the OpenGL installation
>     (BTW, this is a win2k, OpenGL under Python22).
>     I couldn't run a single demo from the openGL demos dir.
>     The messages were 'couldn't read memory...' and
>     looks like the Tk has been involved.  In one
>     case was a total crash... with auto reboot.
> 
>     Any pointers/instructions where to look?
> thanx,
> val
> 
> 
> ----- Original Message -----
> From: "Rob" <rob@uselesspython.com>
> To: <tutor@python.org>
> Sent: Monday, July 01, 2002 6:01 PM
> Subject: Re: [Tutor] installing/starting vPython
> 
> 
> 
>>It sounds like you might have a GL issue on your hands. What Operating
>>System are you running?
>>
>>Rob
>>http://uselesspython.com
>>
>>val wrote:
>>
>>
>>>Hi The List,
>>>    i downloaded and installed vPython for Python22.
>>>    i'm trying to run demos from the Demos dir by double-
>>>    clicking on *.py files.  It works impressively fine
>>>    on my job (same win2k, both Py21 and Py22 are
>>>
> installed).
> 
>>>    At home i have a standard message from vPython
>>>    and then just an empty window (or two or three
>>>    depending on the demo to be run).
>>>
>>>    Any help/advice would be very appreciated.
>>>thanx,
>>>val
>>>
>>>
>>>
>>>_______________________________________________
>>>Tutor maillist  -  Tutor@python.org
>>>http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>>
>>
>>--
>>"Giving the Linus Torvalds Award to the Free Software Foundation is a
>>bit like giving the Han Solo Award to the Rebel Alliance."
>>--Richard Stallman at the 1999 LinuxWorld show
>>
>>
>>
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>>
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show





From gncuster@firehead.org  Wed Jul  3 06:12:18 2002
From: gncuster@firehead.org (Nate Custer)
Date: 03 Jul 2002 00:12:18 -0500
Subject: [Tutor] Many files or one big file?
Message-ID: <1025673138.32458.308.camel@localhost.houston.rr.com>

Hey all,

I am helping to write a tn5250 client in python. Right now we are coding
the back end library. The team leader, who is new to python asked me
this:

> This brings me to a question though.  Should the lib be all
> implemented in one file as  you have it or in different files as I 
> have been doing it.  Here is where you come in because I do not have 
> the slightest idea of the benefits in python for doing one or the 
> other.

I tend towards placing smaller related classes in the same file. But I
do not have expierance writing a project of this size. What do you guys
think the right way to do it is?

thanks,

Nate Custer
-- 
Gentlemen, [the equation  e^(i*pi) + 1 = 0 ] is surely true, it is
absolutely paradoxical; we cannot understand it, and we don't know what
it means. But we have proved it, and therefore we know it must be truth.

-Benjamin Peirce
 




From ak@silmarill.org  Wed Jul  3 06:31:58 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Wed, 3 Jul 2002 01:31:58 -0400
Subject: [Tutor] Many files or one big file?
In-Reply-To: <1025673138.32458.308.camel@localhost.houston.rr.com>
References: <1025673138.32458.308.camel@localhost.houston.rr.com>
Message-ID: <20020703053158.GA29087@ak.silmarill.org>

On Wed, Jul 03, 2002 at 12:12:18AM -0500, Nate Custer wrote:
> Hey all,
> 
> I am helping to write a tn5250 client in python. Right now we are coding
> the back end library. The team leader, who is new to python asked me
> this:
> 
> > This brings me to a question though.  Should the lib be all
> > implemented in one file as  you have it or in different files as I 
> > have been doing it.  Here is where you come in because I do not have 
> > the slightest idea of the benefits in python for doing one or the 
> > other.
> 
> I tend towards placing smaller related classes in the same file. But I
> do not have expierance writing a project of this size. What do you guys
> think the right way to do it is?
>
I'd say many smaller files, because the code tends to grow beyond your
estimates and then you end up with a 2.5k lines file that you have to
tear apart, like I did :-).

> 
> thanks,
> 
> Nate Custer
> -- 
> Gentlemen, [the equation  e^(i*pi) + 1 = 0 ] is surely true, it is
> absolutely paradoxical; we cannot understand it, and we don't know what
> it means. But we have proved it, and therefore we know it must be truth.
> 
> -Benjamin Peirce
>  
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From rob@uselesspython.com  Wed Jul  3 11:35:21 2002
From: rob@uselesspython.com (Rob)
Date: Wed, 03 Jul 2002 05:35:21 -0500
Subject: [Tutor] small program in Python and in C++
References: <3D2210AF.4070702@uselesspython.com>
Message-ID: <3D22D369.2090304@uselesspython.com>

This is a multi-part message in MIME format.
--------------090004050406070600090609
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit

Looks like my hombre did indeed create a PHP version of the obesity 
calculator. It's attached here.

Rob
http://uselesspython.com
-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show

--------------090004050406070600090609
Content-Type: text/plain;
 name="obesity.txt"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="obesity.txt"

<html>
<head>
<title>
Body Mass Index -- Are you obese???
</title>
</head>
<body>

<?php

# Let's get right down to it...

if($action == "Calculate!") {
  $bodyMassTarget=30;
  $height=($inches + ($feet * 12));
  $bodyMassIndex = 703 * ($mass / ($height * $height));
  echo "The target body mass index is ".$bodyMassTarget.". Your body mass index is ".$bodyMassIndex.". <br /><br />";
  if($bodyMassIndex >= $bodyMassTarget) {
    $obesity="I'm sorry. You are obese.";
  } else {
    $obesity="Congratulations! You are not obese!";
  }
  echo $obesity;
} else {

?>

<form action="./obesity.php" method="post">
<b>Height:&nbsp;</b><input type="text" size="1" maxlength="1" name="feet">FT&nbsp;<input type="text" size="1" maxlength="2" name="inches">IN<br />
<b>Weight:&nbsp;</b><input type="text" size="2" maxlength="3" name="mass">LB's<br />
<input type="submit" name="action" value="Calculate!">
</form>
<?php

}

?>

</body>
</html>
--------------090004050406070600090609--





From kemu@linuxmail.org  Wed Jul  3 14:07:19 2002
From: kemu@linuxmail.org (Jonas Geiregat)
Date: Wed, 03 Jul 2002 21:07:19 +0800
Subject: [Tutor] Python best gui api
Message-ID: <20020703130719.24354.qmail@linuxmail.org>

What is the best gui api for python ?
tkinter pygtk ... ??
-- 
Get your free email from www.linuxmail.org 


Powered by Outblaze



From jeff@ccvcorp.com  Wed Jul  3 16:59:16 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed, 03 Jul 2002 08:59:16 -0700
Subject: [Tutor] Python best gui api
References: <20020703130719.24354.qmail@linuxmail.org>
Message-ID: <3D231F53.D090337E@ccvcorp.com>


Jonas Geiregat wrote:

> What is the best gui api for python ? tkinter pygtk ... ??

I've been using wxPython and am quite happy with it.  From what I can
see, Tkinter is a bit easier to pick up the basics of, but it's more
difficult to do complex things with Tkinter than with wxPython -- it's
a lot less flexible.  I don't know much about pyGTK itself...  I've
also heard lots of good things about PyQT, but haven't explored it
myself yet.

Jeff Shannon
Technician/Programmer
Credit International






From jeff@ccvcorp.com  Wed Jul  3 17:10:26 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed, 03 Jul 2002 09:10:26 -0700
Subject: [Tutor] Many files or one big file?
References: <1025673138.32458.308.camel@localhost.houston.rr.com>
Message-ID: <3D2321F2.D52A64FE@ccvcorp.com>


Nate Custer wrote:

> > This brings me to a question though.  Should the lib be all
> > implemented in one file as  you have it or in different files as I
> > have been doing it.  Here is where you come in because I do not have
> > the slightest idea of the benefits in python for doing one or the
> > other.
>
> I tend towards placing smaller related classes in the same file. But I
> do not have expierance writing a project of this size. What do you guys
> think the right way to do it is?

Well, a lot of this depends on just what size we're talking about here.  My
tendency is that, in any project large enough to involve more than a couple
of significant classes, I try to break each major subcomponent into its own
separate file, and have as much of the support for that subcomponent in that
file.  In a certain sense, I'm breaking my library into logical sublibraries
of related functionality.  To my mind, having numerous smaller files makes
it easier to isolate components (an important goal of OOP), track changes
and their effects, and allow for modular re-use of various parts.

Of course, if you break things apart *too* far, then you end up with a
chaotic mess -- there's a balance to be found, and the exact location of
that balance point varies from project to project.

Jeff Shannon
Technician/Programmer
Credit International





From phthenry@earthlink.net  Wed Jul  3 17:01:56 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Wed, 3 Jul 2002 12:01:56 -0400
Subject: [Tutor] help using this code
Message-ID: <20020703120156.E30029@localhost.localdomain>

Below is a block of code that uses the mxTextTools to tag an rtf
file. I would like to use this code to convert rtf to xml and
believe I need to just change a few lines, but I am not sure
what. Could someone help me?

If anyone could point me to some good documentation on how to use
mxTextTools, I would appreciate it. The documentation that comes
with this tool assumes that you know a lot already.

Thanks!

Paul

***********************
#!/usr/local/bin/python

""" RTF - tag a RTF string (Version 0.2)
    
    This version does recursion using the TableInList cmd.
    
    Copyright (c) 2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
    Copyright (c) 2000-2001, eGenix.com Software GmbH; mailto:info@egenix.com
    See the documentation for further information on copyrights,
    or contact the author. All Rights Reserved.
"""

import sys,string

# engine + constants
from mx.TextTools import *

# list of tables (hack to be able to do recursion)
tables = []
# indices
rtf_index = 0

numeral = (# sign ?
           (None,Is,'-',+1),
           (None,AllIn,number)
          )

# XXX: doesn't know how to handle \bin et al. with embedded {}

ctrlword = (# name
            ('name',AllIn,a2z),
            # delimiter
            (None,Is,' ',+1,MatchOk),
            (None,IsIn,number+'-',MatchOk),
             (None,Skip,-1),
             ('param',Table,numeral,+0,MatchOk),
             (None,Is,' ',+1,MatchOk),
              (None,Skip,-1)
           )

hex = set(number+'abcdefABCDEF')
notalpha = set(alpha,0)

ctrlsymbol = (# hexquote
              (None,Is,"'",+3),
               (None,IsInSet,hex),
               (None,IsInSet,hex),
              # other
              (None,IsInSet,notalpha,+1,MatchOk)
             )

rtf = (# control ?
       (None,Is,'\\',+3),
        # word
        ('word',Table,ctrlword,+1,-1),
        # symbol
        ('symbol',Table,ctrlsymbol,+1,-2),
       # closing group
       (None,Is,'}',+2),
        (None,Skip,-1,0,MatchOk),
       # nested group
       (None,Is,'{',+4),
        # recurse
        ('group',TableInList,(tables,rtf_index)),
        (None,Is,'}'),
        (None,Jump,To,-8),
       # document text
       ('text', AllNotIn, '\\{}',+1,-9),
       # EOF
       ('eof',EOF,Here)
      )

# add tables to list
tables.append(rtf)

# note:
# TableInList,(tables,rtf_index)) means: use table tables[rtf_index]

if __name__ == '__main__':

    t = TextTools._timer()

    # read file
    f = open(sys.argv[1])
    text = f.read()

    # tag text
    t.start()
    result, taglist, nextindex = tag(text,rtf)
    t = t.stop()[0]

    print result, nextindex, t,'sec ... hit return to see the tags'
    raw_input()
    print
    print_tags(text,taglist)




-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From ATrautman@perryjudds.com  Wed Jul  3 17:37:25 2002
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Wed, 3 Jul 2002 11:37:25 -0500
Subject: [Tutor] rtf
Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A31F@CORP_EXCHANGE>

hi,

Just a quick question because I haven't found anyone or library that does
it. Does anyone know of a library or project that creates rtf formatting for
you? I need to create printable report in the windows world with some
formatted and shaded table otherwise I would use HTML. I do already have a
HTML copy of the page working.

Thanks for you help

Alan





From kafuiyvonne@hotmail.com  Wed Jul  3 17:55:57 2002
From: kafuiyvonne@hotmail.com (YVONNE KAFUI)
Date: Wed, 03 Jul 2002 16:55:57 +0000
Subject: [Tutor] Python best gui api
Message-ID: <F159u9PH3IhA1qfT7eE00005541@hotmail.com>



>From: "Jeff Shannon" <jeff@ccvcorp.com>
>To: Jonas Geiregat <kemu@linuxmail.org>
>CC: tutor@python.org
>Subject: Re: [Tutor] Python best gui api
>Date: Wed, 03 Jul 2002 08:59:16 -0700
>
>
>
>Jonas Geiregat wrote:
>
> > What is the best gui api for python ? tkinter pygtk ... ??
>
>I've been using wxPython and am quite happy with it.  From what I can
>see, Tkinter is a bit easier to pick up the basics of, but it's more
>difficult to do complex things with Tkinter than with wxPython -- it's
>a lot less flexible.  I don't know much about pyGTK itself...  I've
>also heard lots of good things about PyQT, but haven't explored it
>myself yet.
>
>Jeff Shannon
>Technician/Programmer
>Credit International
>
>
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor




_________________________________________________________________
Send and receive Hotmail on your mobile device: http://mobile.msn.com




From alan.gauld@bt.com  Wed Jul  3 17:56:23 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Jul 2002 17:56:23 +0100
Subject: [Tutor] setting up a timer
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6F8@mbtlipnt02.btlabs.bt.co.uk>

> Then I discovered that signal.alarm is NOT available in Windows.  Mark
> Hammond's book (Python Programming on Win32) was no help.  

I usually just create a Windows timer and catch the timer event.
That gets slightly messy in a plain python program because you 
don't normally have a windows event loop!

Curious to see other suggestoions.

Alan G.



From alan.gauld@bt.com  Wed Jul  3 18:07:02 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Jul 2002 18:07:02 +0100
Subject: [Tutor] small program in Python and in C++
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6F9@mbtlipnt02.btlabs.bt.co.uk>

> up writing a C++ equivalent for someone else a few minutes 
> 
> ...or if anyone cared to point out other ways

Not so much other ways but I notice you define your variables 
in C++ just before using them.

That's a recipe for disaster! If you write more than a few 
hundered lines of code finding your definitions will be murder. 
Imagine discovering that a certain int has to be made a long. 
Now find where within several hundred lines you declared it. 
Ok you can use search functions but it's much easier to just 
go to the top of the function!

Its much more maintainable to group declarations at the 
top of the containing scope(function/file etc). The only 
reasonable exception to this are single letter variablers 
used as loop counters etc.

Others might disagree but I think most regular C++'ers 
will back this up.

Alan G.



From alan.gauld@bt.com  Wed Jul  3 18:15:49 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Jul 2002 18:15:49 +0100
Subject: [Tutor] Many files or one big file?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6FA@mbtlipnt02.btlabs.bt.co.uk>

> > This brings me to a question though.  Should the lib be all
> > implemented in one file as  you have it or in different files 

> I tend towards placing smaller related classes in the same file. 

The useful unit of reuse in Python is the file therefore collect 
all you need into a file and keep it together. eg. you should 
never need to import say 3 separate files to access one feature.

equally we don't want to import  a single huge file to access 
a single feature so organize on the basis of what might 
conceivably be reusable in the future, either by you or somebody 
else.

Alan g.



From alan.gauld@bt.com  Wed Jul  3 18:19:04 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Jul 2002 18:19:04 +0100
Subject: [Tutor] Python best gui api
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6FB@mbtlipnt02.btlabs.bt.co.uk>

------_=_NextPart_001_01C222B5.BB3DF520
Content-type: text/plain; charset="ISO-8859-1"

 >  What is the best gui api for python ?  
 
Best is such an emotive term. It depends as ever, 
on what you need to do.
 
The widest compatibility is probably Tkinter. The highest 
functionality on any given platform will likely be something else.
 
What platform(s) do you need to be portable across?
What special features do you need?
 
What other emnvironments must you interact with(Gnome, KDE etc?)
 
 
All of these will affect the answer to your question of 
which is bet for you.
 
Alan G. 

------_=_NextPart_001_01C222B5.BB3DF520
Content-type: text/html; charset="ISO-8859-1"

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">


<META content="MSHTML 5.50.4807.2300" name=GENERATOR></HEAD>
<BODY>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;&gt; &nbsp;</FONT></SPAN>What is the best gui api for python 
?&nbsp;<SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2>Best is such an emotive term. It depends as ever, </FONT></SPAN></DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2>on what you need to do.</FONT></SPAN></DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2>The widest compatibility is probably Tkinter. The highest 
</FONT></SPAN></DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2>functionality on any given platform will likely be something 
else.</FONT></SPAN></DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2>What platform(s) do you need to be portable across?</FONT></SPAN></DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2>What special features do you need?</FONT></SPAN></DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2>What other emnvironments must you interact with(Gnome, KDE 
etc?)</FONT></SPAN></DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2>All of these will affect the answer to your question of 
</FONT></SPAN></DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2>which is bet for you.</FONT></SPAN></DIV>
<DIV><SPAN class=260242117-03072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=260242117-03072002></SPAN><FONT face="Courier New"><FONT 
color=#0000ff><FONT size=2>A<SPAN class=260242117-03072002>lan 
G.&nbsp;</SPAN></FONT></FONT></FONT></DIV></BODY></HTML>

------_=_NextPart_001_01C222B5.BB3DF520--



From israel@lith.com  Wed Jul  3 18:37:31 2002
From: israel@lith.com (Israel Evans)
Date: Wed, 3 Jul 2002 10:37:31 -0700
Subject: [Tutor] Python best gui api
Message-ID: <AF020C5FC551DD43A4958A679EA16A15017B4253@abbott.lith.com>

This message is in MIME format. Since your mail reader does not understand
this format, some or all of this message may not be legible.

------_=_NextPart_001_01C222B8.4F5BE0FC
Content-Type: text/plain

Just chiming in...
 
 
For my particular tastes, I have these guidelines for my choice.
 
1.	I would like to write the GUI in as pythonic a manner as possible.
2.	The GUI should allow a look as close as possible to the OS.
3.	Free.  ( I'm a cheap bastard and only a hobbyist. )
 
I would love to be able to just write python code and not have an
intermediate toolkit.  If only it were that easy.  I'd also be interested in
using Python in MacOS X's Project Builder and Interface Builder to make
cocoa apps!  WSYWIG tools for a python GUI would be swell.
 
I'm not terribly worried about cross platform, but it would be nice if we
all just got along and understood each other better.
 
 
 
~Israel~
 
-----Original Message-----
From: alan.gauld@bt.com [mailto:alan.gauld@bt.com] 
Sent: 03 July 2002 10:19 AM
To: kemu@linuxmail.org; tutor@python.org
Subject: RE: [Tutor] Python best gui api
 
 >  What is the best gui api for python ?  
 
Best is such an emotive term. It depends as ever, 
on what you need to do.
 
The widest compatibility is probably Tkinter. The highest 
functionality on any given platform will likely be something else.
 
What platform(s) do you need to be portable across?
What special features do you need?
 
What other emnvironments must you interact with(Gnome, KDE etc?)
 
 
All of these will affect the answer to your question of 
which is bet for you.
 
Alan G. 

------_=_NextPart_001_01C222B8.4F5BE0FC
Content-Type: text/html
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns:o=3D"urn:schemas-microsoft-com:office:office" =
xmlns:w=3D"urn:schemas-microsoft-com:office:word" =
xmlns:st1=3D"urn:schemas-microsoft-com:office:smarttags" =
xmlns=3D"http://www.w3.org/TR/REC-html40">

<head>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3Dus-ascii">


<meta name=3DProgId content=3DWord.Document>
<meta name=3DGenerator content=3D"Microsoft Word 10">
<meta name=3DOriginator content=3D"Microsoft Word 10">
<link rel=3DFile-List href=3D"cid:filelist.xml@01C2227D.922B8FE0">
<o:SmartTagType =
namespaceuri=3D"urn:schemas-microsoft-com:office:smarttags"
 name=3D"time"/>
<o:SmartTagType =
namespaceuri=3D"urn:schemas-microsoft-com:office:smarttags"
 name=3D"date"/>
<o:SmartTagType =
namespaceuri=3D"urn:schemas-microsoft-com:office:smarttags"
 name=3D"country-region"/>
<o:SmartTagType =
namespaceuri=3D"urn:schemas-microsoft-com:office:smarttags"
 name=3D"place"/>
<!--[if gte mso 9]><xml>
 <o:OfficeDocumentSettings>
  <o:DoNotRelyOnCSS/>
 </o:OfficeDocumentSettings>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <w:WordDocument>
  <w:SpellingState>Clean</w:SpellingState>
  <w:GrammarState>Clean</w:GrammarState>
  <w:DocumentKind>DocumentEmail</w:DocumentKind>
  <w:EnvelopeVis/>
  <w:Compatibility>
   <w:UseFELayout/>
  </w:Compatibility>
  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
 </w:WordDocument>
</xml><![endif]--><!--[if !mso]>
<style>
st1\:*{behavior:url(#default#ieooui) }
</style>
<![endif]-->
<style>
<!--
 /* Font Definitions */
 @font-face
	{font-family:PMingLiU;
	panose-1:2 2 3 0 0 0 0 0 0 0;
	mso-font-alt:\65B0\7D30\660E\9AD4;
	mso-font-charset:136;
	mso-generic-font-family:roman;
	mso-font-pitch:variable;
	mso-font-signature:3 137232384 22 0 1048577 0;}
@font-face
	{font-family:Tahoma;
	panose-1:2 11 6 4 3 5 4 4 2 4;
	mso-font-charset:0;
	mso-generic-font-family:swiss;
	mso-font-pitch:variable;
	mso-font-signature:553679495 -2147483648 8 0 66047 0;}
@font-face
	{font-family:"\@PMingLiU";
	panose-1:2 2 3 0 0 0 0 0 0 0;
	mso-font-charset:136;
	mso-generic-font-family:roman;
	mso-font-pitch:variable;
	mso-font-signature:3 137232384 22 0 1048577 0;}
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{mso-style-parent:"";
	margin:0in;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman";
	mso-fareast-font-family:PMingLiU;}
a:link, span.MsoHyperlink
	{color:blue;
	text-decoration:underline;
	text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
	{color:purple;
	text-decoration:underline;
	text-underline:single;}
p.MsoAutoSig, li.MsoAutoSig, div.MsoAutoSig
	{margin:0in;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman";
	mso-fareast-font-family:"Times New Roman";
	mso-fareast-language:EN-US;}
span.EmailStyle17
	{mso-style-type:personal-reply;
	mso-style-noshow:yes;
	mso-ansi-font-size:10.0pt;
	mso-bidi-font-size:10.0pt;
	font-family:Arial;
	mso-ascii-font-family:Arial;
	mso-hansi-font-family:Arial;
	mso-bidi-font-family:Arial;
	color:navy;}
span.SpellE
	{mso-style-name:"";
	mso-spl-e:yes;}
span.GramE
	{mso-style-name:"";
	mso-gram-e:yes;}
@page Section1
	{size:8.5in 11.0in;
	margin:1.0in 1.25in 1.0in 1.25in;
	mso-header-margin:.5in;
	mso-footer-margin:.5in;
	mso-paper-source:0;}
div.Section1
	{page:Section1;}
 /* List Definitions */
 @list l0
	{mso-list-id:1585143224;
	mso-list-type:hybrid;
	mso-list-template-ids:-77438038 67698703 67698713 67698715 67698703 =
67698713 67698715 67698703 67698713 67698715;}
@list l0:level1
	{mso-level-tab-stop:.5in;
	mso-level-number-position:left;
	text-indent:-.25in;}
ol
	{margin-bottom:0in;}
ul
	{margin-bottom:0in;}
-->
</style>
<!--[if gte mso 10]>
<style>
 /* Style Definitions */=20
 table.MsoNormalTable
	{mso-style-name:"Table Normal";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-parent:"";
	mso-padding-alt:0in 5.4pt 0in 5.4pt;
	mso-para-margin:0in;
	mso-para-margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:10.0pt;
	font-family:"Times New Roman";}
</style>
<![endif]-->
</head>

<body lang=3DEN-US link=3Dblue vlink=3Dpurple =
style=3D'tab-interval:.5in'>

<div class=3DSection1>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>Just chiming =
in...<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'><o:p>&nbsp;</o:p></span></font></p>=


<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'><o:p>&nbsp;</o:p></span></font></p>=


<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>For my particular tastes, I have =
these
guidelines for my choice.<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'><o:p>&nbsp;</o:p></span></font></p>=


<ol style=3D'mso-margin-top-alt:0in' start=3D1 type=3D1>
 <li class=3DMsoNormal style=3D'color:navy;mso-list:l0 level1 =
lfo1;tab-stops:list .5in'><font
     size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:10.0pt;font-family:
     Arial'>I would like to write the GUI in as <span =
class=3DSpellE>pythonic</span>
     a manner as possible.<o:p></o:p></span></font></li>
 <li class=3DMsoNormal style=3D'color:navy;mso-list:l0 level1 =
lfo1;tab-stops:list .5in'><font
     size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:10.0pt;font-family:
     Arial'>The GUI should allow a look as close as possible to the =
OS.<o:p></o:p></span></font></li>
 <li class=3DMsoNormal style=3D'color:navy;mso-list:l0 level1 =
lfo1;tab-stops:list .5in'><font
     size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:10.0pt;font-family:
     Arial'>Free.<span style=3D'mso-spacerun:yes'>&nbsp; </span><span
     class=3DGramE>( I'm</span> a cheap bastard and only a hobbyist. =
)<o:p></o:p></span></font></li>
</ol>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'><o:p>&nbsp;</o:p></span></font></p>=


<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>I would love to be able to just =
write python
code and not have an intermediate toolkit.<span =
style=3D'mso-spacerun:yes'>&nbsp;
</span>If only it were that easy.<span =
style=3D'mso-spacerun:yes'>&nbsp; </span>I'd
also be interested in using Python in <span class=3DSpellE>MacOS</span> =
X's
Project Builder and Interface Builder to make cocoa apps! <span
style=3D'mso-spacerun:yes'>&nbsp;</span>WSYWIG tools for a python GUI =
would be <span
class=3DGramE>swell</span>.<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'><o:p>&nbsp;</o:p></span></font></p>=


<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>I'm not terribly worried about =
cross
platform, but it would be nice if we all just got along and understood =
each
other better.<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'><o:p>&nbsp;</o:p></span></font></p>=


<div>

<p class=3DMsoAutoSig><font size=3D3 color=3Dnavy face=3D"Times New =
Roman"><span
style=3D'font-size:12.0pt;color:navy;mso-no-proof:yes'><o:p>&nbsp;</o:p>=
</span></font></p>

<p class=3DMsoAutoSig><font size=3D3 color=3Dnavy face=3D"Times New =
Roman"><span
style=3D'font-size:12.0pt;color:navy;mso-no-proof:yes'><o:p>&nbsp;</o:p>=
</span></font></p>

<p class=3DMsoAutoSig><font size=3D2 color=3Dnavy face=3D"Courier =
New"><span
style=3D'font-size:10.0pt;font-family:"Courier =
New";color:navy;mso-no-proof:yes'>~</span></font><st1:country-region><st=
1:place><font
  size=3D2 color=3Dnavy face=3D"Courier New"><span =
style=3D'font-size:10.0pt;
  font-family:"Courier =
New";color:navy;mso-no-proof:yes'>Israel</span></font></st1:place></st1:=
country-region><font
size=3D2 color=3Dnavy face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:
"Courier =
New";color:navy;mso-no-proof:yes'>~<o:p></o:p></span></font></p>

</div>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'><o:p>&nbsp;</o:p></span></font></p>=


<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
face=3DTahoma><span
style=3D'font-size:10.0pt;font-family:Tahoma'>-----Original =
Message-----<br>
<b><span style=3D'font-weight:bold'>From:</span></b> alan.gauld@bt.com
[mailto:alan.gauld@bt.com] <br>
<b><span style=3D'font-weight:bold'>Sent:</span></b> =
</span></font><st1:date
Month=3D"7" Day=3D"3" Year=3D"2002"><font size=3D2 face=3DTahoma><span =
style=3D'font-size:
 10.0pt;font-family:Tahoma'>03 July 2002</span></font></st1:date><font =
size=3D2
face=3DTahoma><span style=3D'font-size:10.0pt;font-family:Tahoma'> =
</span></font><st1:time
Hour=3D"10" Minute=3D"19"><font size=3D2 face=3DTahoma><span =
style=3D'font-size:10.0pt;
 font-family:Tahoma'>10:19 AM</span></font></st1:time><font size=3D2 =
face=3DTahoma><span
style=3D'font-size:10.0pt;font-family:Tahoma'><br>
<b><span style=3D'font-weight:bold'>To:</span></b> kemu@linuxmail.org;
tutor@python.org<br>
<b><span style=3D'font-weight:bold'>Subject:</span></b> RE: [Tutor] =
Python best
gui api</span></font></p>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Times New Roman"><span
style=3D'font-size:12.0pt'><o:p>&nbsp;</o:p></span></font></p>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
color=3Dblue
face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
color:blue'>&nbsp;&gt; &nbsp;</span></font>What is the best gui api for =
python
?&nbsp;<font size=3D2 color=3Dblue face=3D"Courier New"><span =
style=3D'font-size:10.0pt;
font-family:"Courier =
New";color:blue'>&nbsp;</span></font><o:p></o:p></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Times New Roman"><span
style=3D'font-size:12.0pt'>&nbsp;<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
color=3Dblue
face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
color:blue'>Best is such an emotive term. It depends as ever, =
</span></font><o:p></o:p></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
color=3Dblue
face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
color:blue'>on what you need to do.</span></font><o:p></o:p></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Times New Roman"><span
style=3D'font-size:12.0pt'>&nbsp;<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
color=3Dblue
face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
color:blue'>The widest compatibility is probably Tkinter. The highest =
</span></font><o:p></o:p></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
color=3Dblue
face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
color:blue'>functionality on any given platform will likely be =
something else.</span></font><o:p></o:p></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Times New Roman"><span
style=3D'font-size:12.0pt'>&nbsp;<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
color=3Dblue
face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
color:blue'>What platform(s) do you need to be portable =
across?</span></font><o:p></o:p></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
color=3Dblue
face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
color:blue'>What special features do you =
need?</span></font><o:p></o:p></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Times New Roman"><span
style=3D'font-size:12.0pt'>&nbsp;<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
color=3Dblue
face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
color:blue'>What other emnvironments must you interact with(Gnome, KDE =
etc?)</span></font><o:p></o:p></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Times New Roman"><span
style=3D'font-size:12.0pt'>&nbsp;<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Times New Roman"><span
style=3D'font-size:12.0pt'>&nbsp;<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
color=3Dblue
face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
color:blue'>All of these will affect the answer to your question of =
</span></font><o:p></o:p></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
color=3Dblue
face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
color:blue'>which is bet for you.</span></font><o:p></o:p></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Times New Roman"><span
style=3D'font-size:12.0pt'>&nbsp;<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
color=3Dblue
face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
color:blue'>Alan G.&nbsp;</span></font><o:p></o:p></p>

</div>

</div>

</body>

</html>

------_=_NextPart_001_01C222B8.4F5BE0FC--



From kb@kb5.org  Wed Jul  3 18:44:43 2002
From: kb@kb5.org (Kyle Babich)
Date: Wed, 3 Jul 2002 13:44:43 -0400
Subject: [Tutor] Env Vars
References: <20020703011458.164326D9BC@www.fastmail.fm> <3D22F7E9.4020200@venix.com> <001801c222a3$9a493da0$2b73d03f@oemcomputer> <3D231EC2.2080302@venix.com>
Message-ID: <003401c222b9$5736d2a0$0d74d03f@oemcomputer>

My problem is this, I type #!/usr/bin/env python
then what exactly do I put after that if I wanted to print, for example, the
os type into the browser?

----- Original Message -----
From: "Lloyd Kvam" <lkvam@venix.com>
To: "Kyle Babich" <kb@kb5.org>
Sent: Wednesday, July 03, 2002 11:56 AM
Subject: Re: [Tutor] Env Vars


> OK.  I have not kept that system properly patched so I don't like to
> leave it exposed for too long.
>
> Let me (and the Tutor list) know if we can help.
>
> Kyle Babich wrote:
>
> > Thank you, you can take it down.
>
>
>
>




From val@vtek.com  Wed Jul  3 14:31:33 2002
From: val@vtek.com (val)
Date: Wed, 3 Jul 2002 09:31:33 -0400
Subject: [Tutor] installing/starting vPython
References: <02af01c2206a$515ff2e0$0193fea9@vt1000> <3D20D156.8090909@uselesspython.com> <003801c22234$10598060$0193fea9@vt1000> <3D226145.9080603@uselesspython.com>
Message-ID: <009801c22295$f436d1a0$0193fea9@vt1000>

Rob,

    Thank you so much, it works...
    I followed your pointers and changed
    hardware acceleration to None.
    It has helped.  Great!

appreciate very much,
val
    
----- Original Message ----- 
From: "Rob" <rob@uselesspython.com>
To: <tutor@python.org>
Sent: Tuesday, July 02, 2002 10:28 PM
Subject: Re: [Tutor] installing/starting vPython


> If you do suspect your problem may be GL-related, you can go to Display 
> Settings -> Troubleshooting tab and lower "Hardware acceleration" to 
> None. Then click OK or Apply.
> 
> After this, try your VPython demos again and see if you have better 
> luck. If they run with hardware acceleration off, but not with it on, 
> this may confirm GL problems. In that case, I refer you to the VPython 
> FAQ, which suggests a fix. http://vpython.org/FAQ.html
> 
> I actually have this problem on my laptop, but haven't taken the time to 
> fix it because I can't afford the downtime just now.
> 
> hopefully helpful,
> Rob
> http://uselesspython.com
> 
> val wrote:
> 
> > Rob,
> >     Thanx for your quick response.
> >     I've checked the OpenGL installation
> >     (BTW, this is a win2k, OpenGL under Python22).
> >     I couldn't run a single demo from the openGL demos dir.
> >     The messages were 'couldn't read memory...' and
> >     looks like the Tk has been involved.  In one
> >     case was a total crash... with auto reboot.
> > 
> >     Any pointers/instructions where to look?
> > thanx,
> > val
> > 
> > 
> > ----- Original Message -----
> > From: "Rob" <rob@uselesspython.com>
> > To: <tutor@python.org>
> > Sent: Monday, July 01, 2002 6:01 PM
> > Subject: Re: [Tutor] installing/starting vPython
> > 
> > 
> > 
> >>It sounds like you might have a GL issue on your hands. What Operating
> >>System are you running?
> >>
> >>Rob
> >>http://uselesspython.com
> >>
> >>val wrote:
> >>
> >>
> >>>Hi The List,
> >>>    i downloaded and installed vPython for Python22.
> >>>    i'm trying to run demos from the Demos dir by double-
> >>>    clicking on *.py files.  It works impressively fine
> >>>    on my job (same win2k, both Py21 and Py22 are
> >>>
> > installed).
> > 
> >>>    At home i have a standard message from vPython
> >>>    and then just an empty window (or two or three
> >>>    depending on the demo to be run).
> >>>
> >>>    Any help/advice would be very appreciated.
> >>>thanx,
> >>>val
> >>>
> >>>
> >>>
> >>>_______________________________________________
> >>>Tutor maillist  -  Tutor@python.org
> >>>http://mail.python.org/mailman/listinfo/tutor
> >>>
> >>>
> >>>
> >>
> >>--
> >>"Giving the Linus Torvalds Award to the Free Software Foundation is a
> >>bit like giving the Han Solo Award to the Rebel Alliance."
> >>--Richard Stallman at the 1999 LinuxWorld show
> >>
> >>
> >>
> >>
> >>_______________________________________________
> >>Tutor maillist  -  Tutor@python.org
> >>http://mail.python.org/mailman/listinfo/tutor
> >>
> >>
> > 
> > 
> > 
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> > 
> 
> 
> -- 
> "Giving the Linus Torvalds Award to the Free Software Foundation is a 
> bit like giving the Han Solo Award to the Rebel Alliance."
> --Richard Stallman at the 1999 LinuxWorld show
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




From rob@uselesspython.com  Wed Jul  3 19:20:14 2002
From: rob@uselesspython.com (Rob)
Date: Wed, 03 Jul 2002 13:20:14 -0500
Subject: [Tutor] small program in Python and in C++
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6F9@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3D23405E.7010009@uselesspython.com>

Philosophically, I'm inclined to agree. Defining them all in a clump "up 
top" is the way we did it in Pascal back in '92, as I recall (although I 
could be wrong, it having been a decade back).

I've mainly gotten into doing it this way because my C++ professor and 
the books we use have a decided preference for doing it this way.

Rob
http://uselesspython.com

alan.gauld@bt.com wrote:

>>up writing a C++ equivalent for someone else a few minutes 
>>
>>...or if anyone cared to point out other ways
>>
> 
> Not so much other ways but I notice you define your variables 
> in C++ just before using them.
> 
> That's a recipe for disaster! If you write more than a few 
> hundered lines of code finding your definitions will be murder. 
> Imagine discovering that a certain int has to be made a long. 
> Now find where within several hundred lines you declared it. 
> Ok you can use search functions but it's much easier to just 
> go to the top of the function!
> 
> Its much more maintainable to group declarations at the 
> top of the containing scope(function/file etc). The only 
> reasonable exception to this are single letter variablers 
> used as loop counters etc.
> 
> Others might disagree but I think most regular C++'ers 
> will back this up.
> 
> Alan G.
> 
> 


-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show





From rob@uselesspython.com  Wed Jul  3 19:27:09 2002
From: rob@uselesspython.com (Rob)
Date: Wed, 03 Jul 2002 13:27:09 -0500
Subject: [Tutor] Python best gui api
References: <20020703130719.24354.qmail@linuxmail.org>
Message-ID: <3D2341FD.3060501@uselesspython.com>

Jonas Geiregat wrote:

> What is the best gui api for python ? tkinter pygtk ... ?? 

Others have already pointed out the difficulties of defining "best" in 
such a situation. I'll add that if you describe what you would like for 
a GUI API to do for you and under what circumstances, you might get some 
very useful responses from this group.

I'll add to the batch that Java Swing is also quite good, and is 
accessible if you use Jython (which is still very much python in my 
experience).

And there's something to be said for good ol' HTML, too.

If you have zero experience with GUI programming, Tkinter is great to 
cut your teeth on.

If you think you might wind up using wxWindows at some point, then 
wxPython may prove handy to tinker with.

It really depends a lot on what you like and what your circumstances 
call for.

Rob
http://uselesspython.com
-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show





From pythontutor@venix.com  Wed Jul  3 20:29:54 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed, 03 Jul 2002 15:29:54 -0400
Subject: [Tutor] Env Vars
References: <20020703011458.164326D9BC@www.fastmail.fm> <3D22F7E9.4020200@venix.com> <001801c222a3$9a493da0$2b73d03f@oemcomputer> <3D231EC2.2080302@venix.com> <003401c222b9$5736d2a0$0d74d03f@oemcomputer>
Message-ID: <3D2350B2.8050309@venix.com>

Here's a short piece of code that should work!  Fix the
top line to match your system.

#!/usr/local/bin/python
import cgi
import os

http_req = cgi.FieldStorage()
print "Content-type: text/html"
print
try:
	import HTMLgen
	doc = HTMLgen.SimpleDocument()
	ostext = HTMLgen.Text( "The server is running %s" % os.name)
	doc.append(ostext)
	doc.write()
except ImportError:
	print "The server is running %s" % os.name


Kyle Babich wrote:

> My problem is this, I type #!/usr/bin/env python
> then what exactly do I put after that if I wanted to print, for example, the
> os type into the browser?
> 
> ----- Original Message -----
> From: "Lloyd Kvam" <lkvam@venix.com>
> To: "Kyle Babich" <kb@kb5.org>
> Sent: Wednesday, July 03, 2002 11:56 AM
> Subject: Re: [Tutor] Env Vars
> 
> 
> 
>>OK.  I have not kept that system properly patched so I don't like to
>>leave it exposed for too long.
>>
>>Let me (and the Tutor list) know if we can help.
>>
>>Kyle Babich wrote:
>>
>>
>>>Thank you, you can take it down.
>>>
>>
>>
>>
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From kb@kb5.org  Wed Jul  3 21:01:33 2002
From: kb@kb5.org (Kyle Babich)
Date: Wed, 3 Jul 2002 16:01:33 -0400
Subject: [Tutor] Env Vars
References: <20020703011458.164326D9BC@www.fastmail.fm> <3D22F7E9.4020200@venix.com> <001801c222a3$9a493da0$2b73d03f@oemcomputer> <3D231EC2.2080302@venix.com> <003401c222b9$5736d2a0$0d74d03f@oemcomputer> <3D2350B2.8050309@venix.com>
Message-ID: <000601c222cc$788bdd20$0d74d03f@oemcomputer>

I copied and pasted exactly what you put and replaced the path to python.
It says there is a syntax error at import HTMLgen.

Also, is all of that really necessary just to print one environment
variable?
Can you please explain what that is all doing?

Thanks,
Kyle

----- Original Message -----
From: "Lloyd Kvam" <pythontutor@venix.com>
To: "Kyle Babich" <kb@kb5.org>
Cc: <tutor@python.org>
Sent: Wednesday, July 03, 2002 3:29 PM
Subject: Re: [Tutor] Env Vars


> Here's a short piece of code that should work!  Fix the
> top line to match your system.
>
> #!/usr/local/bin/python
> import cgi
> import os
>
> http_req = cgi.FieldStorage()
> print "Content-type: text/html"
> print
> try:
> import HTMLgen
> doc = HTMLgen.SimpleDocument()
> ostext = HTMLgen.Text( "The server is running %s" % os.name)
> doc.append(ostext)
> doc.write()
> except ImportError:
> print "The server is running %s" % os.name
>
>
> Kyle Babich wrote:
>
> > My problem is this, I type #!/usr/bin/env python
> > then what exactly do I put after that if I wanted to print, for example,
the
> > os type into the browser?
> >
> > ----- Original Message -----
> > From: "Lloyd Kvam" <lkvam@venix.com>
> > To: "Kyle Babich" <kb@kb5.org>
> > Sent: Wednesday, July 03, 2002 11:56 AM
> > Subject: Re: [Tutor] Env Vars
> >
> >
> >
> >>OK.  I have not kept that system properly patched so I don't like to
> >>leave it exposed for too long.
> >>
> >>Let me (and the Tutor list) know if we can help.
> >>
> >>Kyle Babich wrote:
> >>
> >>
> >>>Thank you, you can take it down.
> >>>
> >>
> >>
> >>
> >
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
>
> --
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
>
> voice:
> 603-443-6155
> fax:
> 801-459-9582
>
>
>




From dman@dman.ddts.net  Wed Jul  3 22:19:29 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Wed, 3 Jul 2002 16:19:29 -0500
Subject: [Tutor] Re: Env Vars
In-Reply-To: <20020702233222.6F2996DA1A@www.fastmail.fm>
References: <20020702233222.6F2996DA1A@www.fastmail.fm>
Message-ID: <20020703211929.GA18632@dman.ddts.net>

--y0ulUmNC+osPPQO6
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 02, 2002 at 11:32:22PM +0000, Kyle Babich wrote:
| Now I'm able to get it in the shell by importing os and then print
| (os.environ['OSTYPE']) but I when I try to open it in the browser I
| just get a blank page.

In your browser, try the "View Source" function so you can see exactly
what your script gave back to the browser.  Otherwise the browser's
rendering might hide something.
=20
| Also, so far my biggest problem with learning python has been the
| text/html header.  What is the standard way of printing the text/html
| header in python?

Use the 'print' statment!

print "Content-Type: text/html\n\n"



On Wed, Jul 03, 2002 at 01:14:58AM +0000, Kyle Babich wrote:
| I still am getting nothing,

If you get "nothing" then either you aren't printing anything, or
everything you are printing is being rendered by the browser in such
as way as to make it appear invisible.

| I'm probably doing it wrong.

Mmm hmm.

| Isn't there a simple way of doing this?

Yes.

First you read Guido's tutorial so that you know something about
python (just like you once did with perl, except that wasn't Guido's
tutorial).

Then you start writing the script just like you would have in perl,
except that you follow python's syntax rules instead.

| I import os, then what to I type so I can view it in the
| browser?  Can I get an example?  Thanks.

print.  Always print.  Use the print statement liberally.  For example :


#!/usr/bin/env python

# First print the HTTP headers.  Terminate them with a blank line!
print "Content-Type text/plain\n\n"

# now do and print whatever you feel like

import os
print os
print dir( os )
print os.environ
print repr( os.environ )
keys =3D os.environ.keys()
keys.sort()
for k in keys :
    print "%-15s :  %s" % ( k , os.environ[k] )



On Wed, Jul 03, 2002 at 04:01:33PM -0400, Kyle Babich wrote:
| I copied and pasted exactly what you put and replaced the path to python.
| It says there is a syntax error at import HTMLgen.

Did you read the code at all?  I don't mean to sound rude, but it
doesn't sound like you have actually read anything people have been
telling you?  I ask because :

The (relevant) code

try:
import HTMLgen

The error is your indentation.  Python's indentation has been
explained to you (on this list) at least 3 times already, and it is
covered in Guido's tutorial.  I'll leave it to you to figure out what
the correct indentation for those two lines are, and to find the rest
of the indentation problems in your file. =20

Also note that Lloyd indented correctly.  You did not copy his code
verbatim or else you would have it indented correctly as well.

| Also, is all of that really necessary just to print one environment
| variable?

No.  However, it is a framework which (can, I guess) make it much
easier for you to generate more complex pages.  It just seems like
overkill when all you want is a single simple value returned.

| Can you please explain what that is all doing?

No, I don't want to read the docs right now.  However I'll go so far
as to give you URLs so you can RTFM for yourself.

http://starship.python.net/crew/friedrich/HTMLgen/html/main.html
http://python.org/doc/current/lib/module-os.html
http://python.org/doc/current/lib/module-cgi.html

(Apparently HTMLGen isn't a standard module, so you'll have to
download it if you want to use it.  Installing a python module is as
simple as simply copying the .py files to the local disk (in the right
location, of course))


As a group, we enjoy teaching people and helping people learn python.
However, we do just that -- *help* people, not do all the work for
them.  You'll have to put forth some effort yourself and read some
documents and manuals and pay attention to the explanations people
give.  You really shouldn't be asking _this_ syntax error question
again (and again) when it has already been explained several times.
Remember that everyone on this list is just a volunteer.  I, for one,
find it annoying to answer the same question (to the same askee)
multiple times.

-D

--=20

What good is it for a man to gain the whole world, yet forfeit his
soul?  Or what can a man give in exchange for his soul?
        Mark 8:36-37
=20
http://dman.ddts.net/~dman/


--y0ulUmNC+osPPQO6
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0jamAACgkQO8l8XBKTpRRvAQCdHQlcPLPwdTRE5aJtY6JY2mBl
8roAoIoEoVwLA9fieIqsCysKa40wWv9I
=9MXV
-----END PGP SIGNATURE-----

--y0ulUmNC+osPPQO6--



From dyoo@hkn.eecs.berkeley.edu  Wed Jul  3 22:17:14 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 3 Jul 2002 14:17:14 -0700 (PDT)
Subject: [Tutor] Env Vars
In-Reply-To: <000601c222cc$788bdd20$0d74d03f@oemcomputer>
Message-ID: <Pine.LNX.4.44.0207031348420.16202-100000@hkn.eecs.berkeley.edu>


On Wed, 3 Jul 2002, Kyle Babich wrote:

> I copied and pasted exactly what you put and replaced the path to python.
> It says there is a syntax error at import HTMLgen.

Hi Kyle,


Ah!  That's probably a typo in the code: the block between the 'try:' and
the 'except:' needs to be indented.



> Also, is all of that really necessary just to print one environment
> variable?

If we just want to print the environmental variable, we can do this:

###
import os
print "Content-type: text/plain\n\n"
print "The server is running", os.name
###

and for simple stuff, this should be perfectly sufficient.




Lloyd was showing a "simple" example of using the HTMLgen module.
There's a admittedly some overhead in actually using the module itself,
but that overhead comes with an advantage: HTMLgen is taking care of
tricky details that CGI programmers can overlook if they're not careful.


Let's take a look at the brunt of the HTMLgen stuff:

> > ostext = HTMLgen.Text( "The server is running %s" % os.name)

The first line is constructing a chunk of text.  This may seem simple
enough to be silly:  why do we even need to process it with HTMLgen?

But then, HTMLgen is taking care of some details.  Specifically, it's
automatically HTML-quoting special characters like apostrophies and
less-than signs for us:

http://starship.python.net/crew/friedrich/HTMLgen/html/HTMLgen-Text.html

HTML doesn't allow certain characters in documents because, otherwise,
they could be mistaking for HTML tags!  So although it might be overkill
for something simple like printing out 'os.name', it becomes much more
useful when we use it in more involving scripts, where we get our data for
all sorts of places.



> > doc.append(ostext)
> > doc.write()

Note that HTMLgen does not automatically print stuff to screen, which also
may seem somewhat Useless: We insert it into the document 'doc', but we
have to call doc.write() to get it to actually print out to the user. Why
not just print 'ostext' out using a simple 'print' statement like this?

###
print ostext
###

and be done with it?


One reason for delaying the printing is because it's often efficient to
"buffer" our output and send it off in one go, instead of in little
chunks.  Buffering is a good thing for a few other reasons, and you'll
learn about them as you program more CGI's.

(One reason is that delaying output allows us to forwards and redirects
more easily, without worrying about what has been sent to the user's
browser window already.)



Also, HTMLgen is not just for CGI's: it can used in automatically
generating HTML documents to disk.  doc.write() can take in an optional
'filename' parameter:

http://starship.python.net/crew/friedrich/HTMLgen/html/index.html

so that the output is not to screen, but to a file.


Please feel free to ask more questions.  Hope this helps!




From dman@dman.ddts.net  Wed Jul  3 22:29:13 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Wed, 3 Jul 2002 16:29:13 -0500
Subject: [Tutor] Re: setting up a timer
In-Reply-To: <3D223B76.7040805@venix.com>
References: <DHENJFCDEPKIKGEFBLAHIEJBCMAA.john@pertalion.org> <3D223B76.7040805@venix.com>
Message-ID: <20020703212913.GB18632@dman.ddts.net>

--H1spWtNR+x+ondvy
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 02, 2002 at 07:47:02PM -0400, Lloyd Kvam wrote:

First, it's too bad you can't use the standard, tried-and-true
signal.alarm().  It would do exactly what you need.

| Is there a way to kill a thread?

Not if it is blocked.  The only way to "kill" a thread is to terminate
it's run() function from the inside.

| Or is there some documentation about using exceptions with threads?

If the exception occurs within the running thread, then the run()
method should be able to catch it and terminate gracefully.  (if it
doesn't catch it then I think the thread will just die less
gracefully)

Each thread's run() method is like a separate main() (in a C program).


Hmm, maybe something like this could work :


import threading

def foo() :
    raise Exception

try :
    timer =3D threading.Timer( 10 , foo )
    timer.start()
    mysql.connect()  # whatever
    timer.cancel() # we don't really want the exception anymore
except Exception :
    print "timeout!"


I just sorta tested it, and it seems that the Timer runs in a separate
thread, so it has no effect on this thread.

If the mysql connection is blocking and has no built-in timeout, I'm
not sure if you can actually do anything about it.  It's much easier
to turn an async call into a sync one than the other way around
(unless you have signal.alarm()!).
=20
HTH,
-D

--=20

In the way of righteousness there is life;
along that path is immortality.
        Proverbs 12:28
=20
http://dman.ddts.net/~dman/


--H1spWtNR+x+ondvy
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0jbKkACgkQO8l8XBKTpRQrcACfbTfctQ+OjwjcO5lPKKb9++1C
KLAAnjbBW6EFUiOB//tF1ZHCXIJhqRbl
=375B
-----END PGP SIGNATURE-----

--H1spWtNR+x+ondvy--



From wolf_binary@hotmail.com  Wed Jul  3 22:24:36 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Wed, 3 Jul 2002 16:24:36 -0500
Subject: [Tutor] system programmers
Message-ID: <DAV6163sKdhs8v4gBlk0000413c@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_0005_01C222AE.1F4896E0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hi all,

I would like to know if anyone here is a system's programmer.  If there =
is would he/she e-mail me.  I have a few questions about drivers, os =
construction, etc.

Thanks,
Cameron Stoner

------=_NextPart_000_0005_01C222AE.1F4896E0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2713.1100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hi all,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I would like to know if anyone here is =
a system's=20
programmer.&nbsp; If there is would he/she e-mail me.&nbsp; I have a few =

questions about drivers, os construction, etc.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Cameron =
Stoner</FONT></DIV></BODY></HTML>

------=_NextPart_000_0005_01C222AE.1F4896E0--



From dman@dman.ddts.net  Wed Jul  3 22:43:04 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Wed, 3 Jul 2002 16:43:04 -0500
Subject: [Tutor] Re: Python best gui api
In-Reply-To: <20020703130719.24354.qmail@linuxmail.org>
References: <20020703130719.24354.qmail@linuxmail.org>
Message-ID: <20020703214304.GD18632@dman.ddts.net>

--fXStkuK2IQBfcDe+
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, Jul 03, 2002 at 09:07:19PM +0800, Jonas Geiregat wrote:
|    What is the best gui api for python ? tkinter pygtk ... ??=20

I like PyGTK a lot (especially when combined with glade and libglade)
both from a programmer's perspective and from a user's perspective.

wxPython also looks rather decent, but lacks the flexibility that
libglade provides for GTK.

-D

--=20

A)bort, R)etry, B)ang it with a large hammer
=20
http://dman.ddts.net/~dman/


--fXStkuK2IQBfcDe+
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0jb+gACgkQO8l8XBKTpRQk4QCeIgtFIey4GDvA6NQDb6yB8zVb
2L8AoL4/qz7Gc7RSqefgw2G0+nvkL/Hy
=mTFY
-----END PGP SIGNATURE-----

--fXStkuK2IQBfcDe+--



From dman@dman.ddts.net  Wed Jul  3 22:45:02 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Wed, 3 Jul 2002 16:45:02 -0500
Subject: [Tutor] Re: rtf
In-Reply-To: <75EDF89FDE81D511840D00A0C9AD25DD0261A31F@CORP_EXCHANGE>
References: <75EDF89FDE81D511840D00A0C9AD25DD0261A31F@CORP_EXCHANGE>
Message-ID: <20020703214502.GE18632@dman.ddts.net>

--Oiv9uiLrevHtW1RS
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, Jul 03, 2002 at 11:37:25AM -0500, Alan Trautman wrote:
| hi,
|=20
| Just a quick question because I haven't found anyone or library that does
| it. Does anyone know of a library or project that creates rtf formatting =
for
| you? I need to create printable report in the windows world with some
| formatted and shaded table otherwise I would use HTML. I do already have a
| HTML copy of the page working.

HTML can do table formatting and background shading.

Otherwise I recommend using reportlab and generating a PDF file.  Note
that anything more complex than HTML will take quite a bit more coding
(you'll have to do the "rendering" first, rather than spew out some
text and let the browser deal with it).  RTF isn't an open standard
anyways, so you'll find it hard to work with it in a
reliable/complete/robust manner.

-D

--=20

After you install Microsoft Windows XP, you have the option to create
user accounts.  If you create user accounts, by default, they will have
an account type of administrator with no password.
                                                            -- bugtraq
=20
http://dman.ddts.net/~dman/


--Oiv9uiLrevHtW1RS
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0jcF4ACgkQO8l8XBKTpRTUvgCgmc49zsCL/zLV/AUaTIbKWPZ4
0cUAnj/q7+a5DzmMNlpoPJBwung3ZD3f
=CGQw
-----END PGP SIGNATURE-----

--Oiv9uiLrevHtW1RS--



From dman@dman.ddts.net  Wed Jul  3 22:41:25 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Wed, 3 Jul 2002 16:41:25 -0500
Subject: [Tutor] Re: small program in Python and in C++
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6F9@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6F9@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020703214125.GC18632@dman.ddts.net>

--/Uq4LBwYP4y1W6pO
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, Jul 03, 2002 at 06:07:02PM +0100, alan.gauld@bt.com wrote:
| > up writing a C++ equivalent for someone else a few minutes=20
| >=20
| > ...or if anyone cared to point out other ways
|=20
| Not so much other ways but I notice you define your variables=20
| in C++ just before using them.
|=20
| That's a recipe for disaster! If you write more than a few=20
| hundered lines of code finding your definitions will be murder.=20

A function that large (usually) needs to be refactored anyways.

| Imagine discovering that a certain int has to be made a long.=20
| Now find where within several hundred lines you declared it.=20
| Ok you can use search functions but it's much easier to just=20
| go to the top of the function!

With a good editor (eg vim, where your hands stay on the keyboard) it
is quite trivial to search for variable names.  I do it all the time,
even though I've mostly been working with python lately.

| Its much more maintainable to group declarations at the=20
| top of the containing scope(function/file etc).

I find it confusing, actually, to see a whole mess of types/names at
the top of a function when I have no idea what each one really means
yet.  I think it is easier to follow a function if you only have to
remember the relevant variables for that section of it.  Limiting the
scope of a variable limits the length of time for which you must
remember what it means.

I really like python's ability to 'del' a no-longer-needed local if
your function is too long.

Of course, if you are writing a 3-5 line function (or so, something
short) it is clearer to put the declarations at the top so they don't
clutter the flow of the rest of the logic.

Oh, also I think it is good to initialize the variable immediately.
Initializing it to a senseless value like NULL isn't really helpful,
but often that is the only value you have available at the top of the
function, whereas if you declare the variable later you can construct
it properly then.  This is also even more significant in C++ than in
Java or Python when working with classes.  Either you'll end up
wasting some resources by first constructing a default instance of the
class, and then later constructing the one you wanted and copying it
to the existing one (if you use stack-automatic memory management) or
you'll have to mess with pointers and new/delete and ensure you never
end up with NULL when you shouldn't, etc.

| The only reasonable exception to this are single letter variablers
| used as loop counters etc.

Loop counters should be declared in the opening of the loop, IMO.
=20
| Others might disagree but I think most regular C++'ers=20
| will back this up.

It probably depends on whether the "regular" C++'ers started with C or
not.

C required all locals to be declared at the start of a block.  I think
that's due to the early implementations, but I'm just hypothesizing
here.

Java has the same rules as C++, and all the code I've written and read
seems to follow the "don't declare it until you actually need it"
style.


Of course, much of this is just a matter of style with little
technical merit either way, so do as you please :-).

-D

--=20

If we claim we have not sinned, we make Him out to be a liar and His
Word has no place in our lives.
        I John 1:10
=20
http://dman.ddts.net/~dman/


--/Uq4LBwYP4y1W6pO
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0jb4UACgkQO8l8XBKTpRTiNwCguvqN2OzNCeZ/2sc6jxKHY3Px
/NoAn1swmkmhx6yncWw0IwUfRDgQxZM0
=zgqe
-----END PGP SIGNATURE-----

--/Uq4LBwYP4y1W6pO--



From pythontutor@venix.com  Wed Jul  3 22:49:36 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed, 03 Jul 2002 17:49:36 -0400
Subject: [Tutor] Env Vars
References: <Pine.LNX.4.44.0207031348420.16202-100000@hkn.eecs.berkeley.edu>
Message-ID: <3D237170.6010909@venix.com>

Thanks for stepping in Danny, I got sidetracked by work :)

Kyle, I think your email client discards the indentation.  I
actually tested this code example.

Danny Yoo wrote:

> 
> On Wed, 3 Jul 2002, Kyle Babich wrote:
> 
> 
>>I copied and pasted exactly what you put and replaced the path to python.
>>It says there is a syntax error at import HTMLgen.
>>
> 
> Hi Kyle,
> 
> 
> Ah!  That's probably a typo in the code: the block between the 'try:' and
> the 'except:' needs to be indented.
> 
> 
> 
> 
>>Also, is all of that really necessary just to print one environment
>>variable?
>>
> 
> If we just want to print the environmental variable, we can do this:
> 
> ###
> import os
> print "Content-type: text/plain\n\n"
> print "The server is running", os.name
> ###
> 
> and for simple stuff, this should be perfectly sufficient.
> 
> 
> 
> 
> Lloyd was showing a "simple" example of using the HTMLgen module.
> There's a admittedly some overhead in actually using the module itself,
> but that overhead comes with an advantage: HTMLgen is taking care of
> tricky details that CGI programmers can overlook if they're not careful.
> 
> 
> Let's take a look at the brunt of the HTMLgen stuff:
> 
> 
>>>ostext = HTMLgen.Text( "The server is running %s" % os.name)
>>>
> 
> The first line is constructing a chunk of text.  This may seem simple
> enough to be silly:  why do we even need to process it with HTMLgen?
> 
> But then, HTMLgen is taking care of some details.  Specifically, it's
> automatically HTML-quoting special characters like apostrophies and
> less-than signs for us:
> 
> http://starship.python.net/crew/friedrich/HTMLgen/html/HTMLgen-Text.html
> 
> HTML doesn't allow certain characters in documents because, otherwise,
> they could be mistaking for HTML tags!  So although it might be overkill
> for something simple like printing out 'os.name', it becomes much more
> useful when we use it in more involving scripts, where we get our data for
> all sorts of places.
> 
> 
> 
> 
>>>doc.append(ostext)
>>>doc.write()
>>>
> 
> Note that HTMLgen does not automatically print stuff to screen, which also
> may seem somewhat Useless: We insert it into the document 'doc', but we
> have to call doc.write() to get it to actually print out to the user. Why
> not just print 'ostext' out using a simple 'print' statement like this?
> 
> ###
> print ostext
> ###
> 
> and be done with it?
> 
> 
> One reason for delaying the printing is because it's often efficient to
> "buffer" our output and send it off in one go, instead of in little
> chunks.  Buffering is a good thing for a few other reasons, and you'll
> learn about them as you program more CGI's.
> 
> (One reason is that delaying output allows us to forwards and redirects
> more easily, without worrying about what has been sent to the user's
> browser window already.)
> 
> 
> 
> Also, HTMLgen is not just for CGI's: it can used in automatically
> generating HTML documents to disk.  doc.write() can take in an optional
> 'filename' parameter:
> 
> http://starship.python.net/crew/friedrich/HTMLgen/html/index.html
> 
> so that the output is not to screen, but to a file.
> 
> 
> Please feel free to ask more questions.  Hope this helps!
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From lkvam@venix.com  Wed Jul  3 22:45:10 2002
From: lkvam@venix.com (Lloyd Kvam)
Date: Wed, 03 Jul 2002 17:45:10 -0400
Subject: [Tutor] Re: setting up a timer
References: <DHENJFCDEPKIKGEFBLAHIEJBCMAA.john@pertalion.org> <3D223B76.7040805@venix.com> <20020703212913.GB18632@dman.ddts.net>
Message-ID: <3D237066.1000209@venix.com>

Thanks for the analysis.  I have given up on a watchdog timer.

The timer need was coming from also starting the remote
MySQL server when necessary.  I have lowered the requirements, so
that it will only start a local server.


Derrick 'dman' Hudson wrote:

> On Tue, Jul 02, 2002 at 07:47:02PM -0400, Lloyd Kvam wrote:
> 
> First, it's too bad you can't use the standard, tried-and-true
> signal.alarm().  It would do exactly what you need.
> 
> | Is there a way to kill a thread?
> 
> Not if it is blocked.  The only way to "kill" a thread is to terminate
> it's run() function from the inside.
> 
> | Or is there some documentation about using exceptions with threads?
> 
> If the exception occurs within the running thread, then the run()
> method should be able to catch it and terminate gracefully.  (if it
> doesn't catch it then I think the thread will just die less
> gracefully)
> 
> Each thread's run() method is like a separate main() (in a C program).
> 
> 
> Hmm, maybe something like this could work :
> 
> 
> import threading
> 
> def foo() :
>     raise Exception
> 
> try :
>     timer = threading.Timer( 10 , foo )
>     timer.start()
>     mysql.connect()  # whatever
>     timer.cancel() # we don't really want the exception anymore
> except Exception :
>     print "timeout!"
> 
> 
> I just sorta tested it, and it seems that the Timer runs in a separate
> thread, so it has no effect on this thread.
> 
> If the mysql connection is blocking and has no built-in timeout, I'm
> not sure if you can actually do anything about it.  It's much easier
> to turn an async call into a sync one than the other way around
> (unless you have signal.alarm()!).
>  
> HTH,
> -D
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From gncuster@firehead.org  Wed Jul  3 23:29:52 2002
From: gncuster@firehead.org (Nate Custer)
Date: 03 Jul 2002 17:29:52 -0500
Subject: [Tutor] Many files or one big file?
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6FA@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6FA@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <1025735392.32458.362.camel@localhost.houston.rr.com>

On Wed, 2002-07-03 at 12:15, alan.gauld@bt.com wrote:
> 
> The useful unit of reuse in Python is the file therefore collect 
> all you need into a file and keep it together. eg. you should 
> never need to import say 3 separate files to access one feature.
> 
> equally we don't want to import  a single huge file to access 
> a single feature so organize on the basis of what might 
> conceivably be reusable in the future, either by you or somebody 
> else.
> 
> Alan g.
Thanks that seems to be a great way to define the balance we are looking
at. To answer questions of size. So far there are 5 or 6 major classes.
In the end there will probaly be more. The 5250 is a funky machine. It
is used to connect to the AS\400. So it is a propritary, true
Mini-Computer (though now you can hardware as beefy as most mainframes)
with a long history. It is screen based, which is closer in
implementation to a web based app then to any PC/Unix console I have
seen.

Nate Custer
-- 
Gentlemen, [the equation  e^(i*pi) + 1 = 0 ] is surely true, it is
absolutely paradoxical; we cannot understand it, and we don't know what
it means. But we have proved it, and therefore we know it must be truth.

-Benjamin Peirce
 




From kb@kb5.org  Thu Jul  4 02:47:07 2002
From: kb@kb5.org (Kyle Babich)
Date: Wed, 3 Jul 2002 21:47:07 -0400
Subject: [Tutor] Re: Env Vars
References: <20020702233222.6F2996DA1A@www.fastmail.fm> <20020703211929.GA18632@dman.ddts.net>
Message-ID: <003a01c222fe$415f5700$26eaf4d1@oemcomputer>

Yes, I have been reading.  OE must be screwing up indentations because I
even tried copying any pasting and it didn't work.  Indentations I've almost
figured out, my only problem is when to do I do 4 and when do I do a tab
which this tutorial told me:  http://blacksun.box.sk/tutorials/python.htm

Anyway, after you mentioned indentations I got it on my first try.

Thank you,
Kyle

----- Original Message -----
From: "Derrick 'dman' Hudson" <dman@dman.ddts.net>
To: "tutor" <tutor@python.org>
Sent: Wednesday, July 03, 2002 5:19 PM
Subject: [Tutor] Re: Env Vars






From dman@dman.ddts.net  Thu Jul  4 03:23:18 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Wed, 3 Jul 2002 21:23:18 -0500
Subject: [Tutor] Re: Re: Env Vars
In-Reply-To: <003a01c222fe$415f5700$26eaf4d1@oemcomputer>
References: <20020702233222.6F2996DA1A@www.fastmail.fm> <20020703211929.GA18632@dman.ddts.net> <003a01c222fe$415f5700$26eaf4d1@oemcomputer>
Message-ID: <20020704022318.GA23522@dman.ddts.net>

--vkogqOf2sHV7VnPd
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, Jul 03, 2002 at 09:47:07PM -0400, Kyle Babich wrote:
| Yes, I have been reading.

Ok, good :-).

| OE must be screwing up

Why doesn't that surprise me in the least?=20

| indentations because I
| even tried copying any pasting and it didn't work.

FWIW, Lloyd did have tab characters in the code he posted.  My vim
settings (which I use as a pager in mutt) shows them quite clearly.

| Indentations I've almost figured out, my only problem is when to do
| I do 4 and when do I do a tab which this tutorial told me:
| http://blacksun.box.sk/tutorials/python.htm

I skimmed that tutorial (rather I did a search for 'tab' in it) and
only saw one brief comment.

A better discussion of spaces and tabs in python comes from Guido :

http://python.org/doc/essays/styleguide.html


The key to indentation in python is consistency (and remembering that
a tab is an 8-space indent).  For example, with vim you can use this
snippet of a .vimrc to set up your indentation handling :

    augroup Python
        au!
        au FileType python set sts=3D4 sw=3D4 et tw=3D78 fo=3Dcroq2 hls

        " override C preprocessor indenting
        au FileType python inoremap # X<C-H>#
    augroup END

(use :help in vim to see what those options mean, I like the short
names for my own usage)

I (and apparently Guido) like a 4-space indentation level and always
uses spaces (not tabs).  Python just needs the indentation to be
consistent, however deep you want to make it.  Whether you use a space
or a tab is irrelevant to the interpreter, except for the one point
that a tab is considered an 8-space indentation level.  (some editors
allow you to change the width it displays for a tab, and to have it
mix tabs and spaces, and that will bite you hard)

| Anyway, after you mentioned indentations I got it on my first try.

Good!

Keep working on it!  :-)

HAND,
-D

PS.  the .sig is randomly chosen from a list (python script)

--=20

[Perl] combines all the worst aspects of C and Lisp: a billion different
    sublanguages in one monolithic executable.
It combines the power of C with the readability of PostScript.
        -- Jamie Zawinski
=20
http://dman.ddts.net/~dman/


--vkogqOf2sHV7VnPd
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0jsZYACgkQO8l8XBKTpRTPYwCeIAtCTUNZXhiP79zrMeoJuBvI
5f8AnAnxt3+lSL3EjEnnM+0Gvg3eDIAq
=HlE0
-----END PGP SIGNATURE-----

--vkogqOf2sHV7VnPd--



From alan.gauld@bt.com  Thu Jul  4 10:21:56 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 4 Jul 2002 10:21:56 +0100
Subject: [Tutor] Many files or one big file?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6FF@mbtlipnt02.btlabs.bt.co.uk>

> In the end there will probaly be more. The 5250 is a funky machine. 

It sure is. I once wrote a C++ 3270 'emulator' (actually an API 
for doing robotics on a mainframe) and they work in a similar way 
to the 5250.

> with a long history. It is screen based, which is closer in
> implementation to a web based app then to any PC/Unix console I have
> seen.

Yes, thats something I've noticed to. In fact I reckon an AS/400 
should make a fantastic CGI web server since the hardware 
architecture is nearly ideal for the job - far better than the 
more usual *nix machines. However I've not seen many AS/400 sites 
and never had the chance to try!

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld




From asis@graffiti.net  Thu Jul  4 06:07:38 2002
From: asis@graffiti.net (Ashish)
Date: Thu, 04 Jul 2002 10:52:38 +0545
Subject: [Tutor] Re: small program in Python and in C++
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C6F9@mbtlipnt02.btlabs.bt.co.uk> <20020703214125.GC18632@dman.ddts.net>
Message-ID: <3D23D81A.4090306@graffiti.net>

I agree that it is easier to declare variables at the time you need 
them. You know what you are using it for. If your functions are so long 
then may be you need to refactor.

Unless it is a class or instance variable, most local variables have a 
scope of few lines anyway. Also I prefer not to reuse my local 
variables. Like c to store the character at one point and some lines 
down when I don't need c to reuse it to store column number. I don't 
think it as great programming and saving memory. I just think it is a 
potential debugging nightmare.

Another advantage of declaring the variable just before using them is 
that it is easier to ensure they are properly initialised.

The only time I declared variables ahead was when I did C and I haven't 
done plain C for 2 years now.

Ashish




From ajs@ix.netcom.com  Thu Jul  4 16:05:27 2002
From: ajs@ix.netcom.com (Arthur Siegel)
Date: Thu, 4 Jul 2002 11:05:27 -0400
Subject: [Tutor] slots and inheritance
Message-ID: <000701c2236c$9c7ef000$0334fea9@carol>

Playing with new style classes.
I am particularly interested in the slots feature, since
it is quite common for me to typo when sending a keyword
argument when initializing a class instance. It never seemed quite
right to me that the typo would silently pass, and I
might not even notice that the argument I thought I sent was
having no impact.

(Yeah, I know with me whining about change all the time.  
Well I certainly have no intention of not making my best
effort to take advantage of  new features. I guess we all have
our own list of which are the "good" ones.) 

So --

>>> class A(object):
               __slots__=("x","y","z")
>>> a=A()
>>> a.x=1
>>> print a.x
1
>>> a.w=4
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in ?
    a.w=4
AttributeError: 'A' object has no attribute 'w'

All as advertised.

Now:

>>> class B(A):
                     pass

>>> b=B()
>>> b.w=4
>>> print b.w
4

So apparently slots are not inherited. 
Which surprised me.

I am thinking:

class B(A):
    __slots__ = A.__slots__

is the way to go and say

class B(A):
   __slots__ = A.__slots__ + ("u","v")

let's say if I want to add attributes to B not 
legal for A.

Is this by the book? (Were there a book)

Art





From ajs@ix.netcom.com  Thu Jul  4 16:46:44 2002
From: ajs@ix.netcom.com (Arthur Siegel)
Date: Thu, 4 Jul 2002 11:46:44 -0400
Subject: [Tutor] slots and inheritance - a bit more
Message-ID: <001901c22372$07512ec0$0334fea9@carol>

I also seem to be discovering that one
cannot multiherit from 2 classes derived
from "object", each with slots defined.

I guess this only seems surprising in light
of that fact that the slots are not inherited.
>>> class A(object):
               __slots__=("a")
               pass

>>> class B(object):
                __slots__=("b")
                 pass

>>> class C(A,B):
                pass

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in ?
    class C(A,B):
TypeError: multiple bases have instance lay-out conflict

Any ideas? 

Art




From ajs@ix.netcom.com  Thu Jul  4 17:20:20 2002
From: ajs@ix.netcom.com (Arthur Siegel)
Date: Thu, 4 Jul 2002 12:20:20 -0400
Subject: [Tutor] slots - a more basic issue
Message-ID: <002501c22376$b41fef20$0334fea9@carol>

Sorry for the multiple posts- but while the
fire's hot.

It now seems that I was misinterpreting slots in a more
basic way.

>>> class A(object):
            __slots__=("x","y","color")
           def __init__(self,x,y,**kws):
                  self.x=x
                  self.y=y
                  self.color=kws.get("color")
>>> a=A(1,2,color="green")
>>> a.color
'green'
>>> b=A(1,2,kolor="green")
>>> print b.color
None


My typo of "color" as "kolor" still passes silently.

How might I accomplish the control against such
typos that I thought slots were going to help me accomplish?


Art




From dman@dman.ddts.net  Thu Jul  4 18:10:01 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Thu, 4 Jul 2002 12:10:01 -0500
Subject: [Tutor] Re: slots - a more basic issue
In-Reply-To: <002501c22376$b41fef20$0334fea9@carol>
References: <002501c22376$b41fef20$0334fea9@carol>
Message-ID: <20020704171001.GA31961@dman.ddts.net>

--OgqxwSJOaUobr8KG
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, Jul 04, 2002 at 12:20:20PM -0400, Arthur Siegel wrote:
| Sorry for the multiple posts- but while the
| fire's hot.
|=20
| It now seems that I was misinterpreting slots in a more
| basic way.
|=20
| >>> class A(object):
|             __slots__=3D("x","y","color")
|            def __init__(self,x,y,**kws):
                                   ^^^^^

That allows _any_ keyword argument to be accepted.

|                   self.x=3Dx
|                   self.y=3Dy
|                   self.color=3Dkws.get("color")
| >>> a=3DA(1,2,color=3D"green")
| >>> a.color
| 'green'
| >>> b=3DA(1,2,kolor=3D"green")
| >>> print b.color
| None
|=20
|=20
| My typo of "color" as "kolor" still passes silently.

Slots are for protecting against assigning to a non-existant instance
member.  You never tried assigning any value to 'self.kolor'.
Function arguments are a different animal.

| How might I accomplish the control against such typos that I thought
| slots were going to help me accomplish?

Use a method signature such as :

             def __init__(self, x, y, color=3DNone ):

and you'll get :

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: __init__() got an unexpected keyword argument 'kolor'

-D

--=20

Come to me, all you who are weary and burdened, and I will give you
rest.  Take my yoke upon you and learn from me, for I am gentle and
humble in heart, and you will find rest for your souls.  For my yoke
is easy and my burden is light.
        Matthew 11:28-30
=20
http://dman.ddts.net/~dman/


--OgqxwSJOaUobr8KG
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0kgWkACgkQO8l8XBKTpRTkTQCgq4wwmSkgMCxtsnVLsCUgLZBL
b2cAniFS1gJHwML39612IsX3gCILMVYo
=jhoo
-----END PGP SIGNATURE-----

--OgqxwSJOaUobr8KG--



From Nicole.Seitz@urz.uni-hd.de  Thu Jul  4 20:52:06 2002
From: Nicole.Seitz@urz.uni-hd.de (Nicole Seitz)
Date: Thu, 4 Jul 2002 19:52:06 +0000
Subject: [Tutor] Attribute Error
Message-ID: <200207041952.06162.Nicole.Seitz@urz.uni-hd.de>

Hi there!

Can anyone explain why I get this traceback=20

Traceback (most recent call last):
  File "beeper.py", line 16, in ?
    b =3D Beeper()
  File "beeper.py", line 7, in __init__
    command=3Dself.beep).pack()
AttributeError: Beeper instance has no attribute 'beep'


when running


import Tkinter

class Beeper(Tkinter.Tk):
  def __init__(self):
    Tkinter.Tk.__init__(self)
    Tkinter.Button(self, text=3D"Beep",
      command=3Dself.beep).pack()
    Tkinter.Button(self, text=3D"Quit",
      command=3Dself.quit).pack()

  def beep(self):
    print "Beep"

if __name__=3D=3D"__main__":
  b =3D Beeper()
  b.mainloop()


Why has my Beeper instance no attribute 'beep' ??

Many thanx in advance.


Nicole



From alan.gauld@bt.com  Thu Jul  4 18:06:21 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 4 Jul 2002 18:06:21 +0100
Subject: [Tutor] Re: small program in Python and in C++
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C707@mbtlipnt02.btlabs.bt.co.uk>

> | That's a recipe for disaster! If you write more than a few 
> | hundered lines of code finding your definitions will be murder. 
> 
> A function that large (usually) needs to be refactored anyways.

Not so. If a function consists of say 50-60 lines of executable 
code then most industrial C++ code will typically contain at least 
as many lines of comment as there are code so you'll have 120 lines of 
text to wade thru'

In the real world many functions contain 200 plus lines of 
executable code(*) which means maybe 400-500 lines of text.

(*)If you have an object with over 100 attributes to serialize
(not an unusual occurence in real world scenarios!) refactoring 
the function isn't really practical or sensible.

> With a good editor (eg vim, where your hands stay on the keyboard) it
> is quite trivial to search for variable names.  I do it all the time,
> even though I've mostly been working with python lately.

Yes but you have to search for the definition/declaration. You have 
to keep stepping past all the usage items to get there! That is 
time consuming and error prone. Jumping to the top of the function 
is a single keystroke!

> I find it confusing, actually, to see a whole mess of types/names at
> the top of a function when I have no idea what each one really means
> yet.  

Well written variable declarations should all be commented! :-)

> I think it is easier to follow a function if you only have to
> remember the relevant variables for that section of it.  

If they are only relevant for that section then I agree they 
can be done locally (like loop counters) or that bit of the 
function could be refactored. But I'm talking abouty variables 
that are used throughout a function.

> Limiting the scope of a variable limits the length of time 
> for which you must remember what it means.

Only if reading the code sequentially, if you are jumping in 
at random - as is usually the case for maintenance programmers 
- the position of declaration is usually not an issue until 
they come to change it!!

> Of course, if you are writing a 3-5 line function (or so, something
> short) it is clearer to put the declarations at the top so they don't
> clutter the flow of the rest of the logic.

Hmm, not sure I follow the logic there. I'd have said declaring 
variables in a short function was less important since you can 
see whats happening whichever way you do it...

> Oh, also I think it is good to initialize the variable immediately.

I agree there.

> Initializing it to a senseless value like NULL isn't really helpful,

Not true. Many a NULL has caused a crash when an unitinialised 
variable would have kept running - with completely wrong results. 
A crash in those circumstances is a good thing! And NULLS help 
achieve it!

> function, whereas if you declare the variable later you can construct
> it properly then.  

OTOH If you want to use aiabvle declared further down a function near 
the top you have to go hunt for the declaration and cut n paste it 
back up to where you need it. If its declared at the top its always 
available.

> This is also even more significant in C++ than in
> Java or Python when working with classes.  Either you'll end up
> wasting some resources by first constructing a default instance of the
> class, and then later constructing the one you wanted and copying it

I see the point of wasted resource but not sure how Java/Python 
helps here. If you initialize the variable to a dummy object you 
waste resource and in all 3 languages that resource stays wasted 
till you get rid of it.

> | The only reasonable exception to this are single letter variablers
> | used as loop counters etc.
> 
> Loop counters should be declared in the opening of the loop, IMO.

Agreed, thats what I meant.

> It probably depends on whether the "regular" C++'ers started with C or
> not.

Nope, It probably depends more on how many months or years they've 
spent debugging other peoples code :-)

> C required all locals to be declared at the start of a block.  I think
> that's due to the early implementations, but I'm just hypothesizing
> here.

Its good software engineering practice as taught at the time 
- Pascal for example requires variables to be declared in a 
var section of the code, as does ADA and Modula (and even COBOL!)

> Java has the same rules as C++, and all the code I've written and read
> seems to follow the "don't declare it until you actually need it"
> style.

Yes, and maintenance programmers the world over are learning 
to hate it! Our Java style guides at work have recently been 
ammended to insist that all variables be declared at the top 
of scope - previously it was just a recommendation...)

> Of course, much of this is just a matter of style with little
> technical merit either way, so do as you please :-).

If it hits the time to fix faults its more than just style.
When an operational fault has to be fixed in lkess than 4 hours 
say, you really don't have time to cast about looking for variables.
It becomes a matter of real bottom line accounting.

Alan g.



From tim.one@comcast.net  Thu Jul  4 18:24:48 2002
From: tim.one@comcast.net (Tim Peters)
Date: Thu, 04 Jul 2002 13:24:48 -0400
Subject: [Tutor] slots and inheritance - a bit more
In-Reply-To: <001901c22372$07512ec0$0334fea9@carol>
Message-ID: <LNBBLJKPBEHFEDALKOLCIEBJACAB.tim.one@comcast.net>

[Arthur Siegel]
> I also seem to be discovering that one
> cannot multiherit from 2 classes derived
> from "object", each with slots defined.

That's true.

> I guess this only seems surprising in light
> of that fact that the slots are not inherited.

Slots are inherited.  What have you seen that made you believe they're not
inherited?

>>> class A(object):
...     __slots__ = 'a'
...
>>> class B(A):
...     pass
...
>>> b = B()
>>> b.a = 12
>>> b.x = 42
>>> b.a
12
>>> b.x
42
>>> b.__dict__  # only 'x' is in the dict; 'a' is stored in inherited slot
{'x': 42}
>>>

BTW, note that __slots__ are really an optimization gimmick.  There's no
reason to bother with them unless you have a great many instances of some
class and need to reduce memory use.  Then they can help, but then you also
have to live with the restrictions the use of __slots__ impose.




From ajs@ix.netcom.com  Thu Jul  4 19:02:05 2002
From: ajs@ix.netcom.com (Arthur Siegel)
Date: Thu, 4 Jul 2002 14:02:05 -0400
Subject: [Tutor] Re: slots - a more basic issue
Message-ID: <001501c22384$ea169940$0334fea9@carol>

Dman writes -

>Use a method signature such as :
>             def __init__(self, x, y, color=None ):
>and you'll get :

>Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>TypeError: __init__() got an unexpected keyword argument 'kolor'

Yeah, but I have lots of potential attributes, and lots
of inheritance relationships - which makes the method signature
unwieldy - just what **kw seems to be made for.

Looks like I'll end up with building a list of attributes and something
like:

for key in kws:
   if key not in optlist:
      print 'WARNING  " %s" not a valid keyword for %s'
%(key,self.__class__.__name__)

Just found a bunch of typos in my demos doing this approach.

Art




From ajs@ix.netcom.com  Thu Jul  4 19:16:39 2002
From: ajs@ix.netcom.com (Arthur Siegel)
Date: Thu, 4 Jul 2002 14:16:39 -0400
Subject: [Tutor] slots and inheritance - a bit more
References: <LNBBLJKPBEHFEDALKOLCIEBJACAB.tim.one@comcast.net>
Message-ID: <001b01c22386$f13705a0$0334fea9@carol>

Tim writes -

> Slots are inherited.  What have you seen that made you believe they're not
> inherited?
>
> >>> class A(object):
> ...     __slots__ = 'a'
> ...
> >>> class B(A):
> ...     pass
> ...
> >>> b = B()
> >>> b.a = 12
> >>> b.x = 42
> >>> b.a
> 12
> >>> b.x
> 42
> >>> b.__dict__  # only 'x' is in the dict; 'a' is stored in inherited slot
> {'x': 42}
> >>>

Helps.

But the *functionality* of slots is not inherited - unless I kill B's
__dict__.  Correct? If so, is that doable?


> BTW, note that __slots__ are really an optimization gimmick.  There's no
> reason to bother with them unless you have a great many instances of some
> class and need to reduce memory use.  Then they can help, but then you
also
> have to live with the restrictions the use of __slots__ impose.

I kind of thought the restriction - as in object.kolor = "blue" when you
meant
object.color= "blue" was of the essence of slots.  But if you mean the
multi-heritance restriction - yes.  Happens to be a deal killer in my case.

Art




From rob@uselesspython.com  Thu Jul  4 19:34:46 2002
From: rob@uselesspython.com (Rob)
Date: Thu, 04 Jul 2002 13:34:46 -0500
Subject: [Tutor] Re: small program in Python and in C++
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C707@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3D249546.2050401@uselesspython.com>

A few questions for the less-learned (such as myself)....

What exactly is refactoring? I think I may have once known, but if I did 
I don't remember.

How do NULLs help achieve an informative crash when an uninitialized 
variable wouldn't? I think I can imagine half of an answer, but not a 
whole one.

Rob
http://uselesspython.com

alan.gauld@bt.com wrote:

>>| That's a recipe for disaster! If you write more than a few 
>>| hundered lines of code finding your definitions will be murder. 
>>
>>A function that large (usually) needs to be refactored anyways.
>>
> 
> Not so. If a function consists of say 50-60 lines of executable 
> code then most industrial C++ code will typically contain at least 
> as many lines of comment as there are code so you'll have 120 lines of 
> text to wade thru'
> 
> In the real world many functions contain 200 plus lines of 
> executable code(*) which means maybe 400-500 lines of text.
> 
> (*)If you have an object with over 100 attributes to serialize
> (not an unusual occurence in real world scenarios!) refactoring 
> the function isn't really practical or sensible.
> 
> 
>>With a good editor (eg vim, where your hands stay on the keyboard) it
>>is quite trivial to search for variable names.  I do it all the time,
>>even though I've mostly been working with python lately.
>>
> 
> Yes but you have to search for the definition/declaration. You have 
> to keep stepping past all the usage items to get there! That is 
> time consuming and error prone. Jumping to the top of the function 
> is a single keystroke!
> 
> 
>>I find it confusing, actually, to see a whole mess of types/names at
>>the top of a function when I have no idea what each one really means
>>yet.  
>>
> 
> Well written variable declarations should all be commented! :-)
> 
> 
>>I think it is easier to follow a function if you only have to
>>remember the relevant variables for that section of it.  
>>
> 
> If they are only relevant for that section then I agree they 
> can be done locally (like loop counters) or that bit of the 
> function could be refactored. But I'm talking abouty variables 
> that are used throughout a function.
> 
> 
>>Limiting the scope of a variable limits the length of time 
>>for which you must remember what it means.
>>
> 
> Only if reading the code sequentially, if you are jumping in 
> at random - as is usually the case for maintenance programmers 
> - the position of declaration is usually not an issue until 
> they come to change it!!
> 
> 
>>Of course, if you are writing a 3-5 line function (or so, something
>>short) it is clearer to put the declarations at the top so they don't
>>clutter the flow of the rest of the logic.
>>
> 
> Hmm, not sure I follow the logic there. I'd have said declaring 
> variables in a short function was less important since you can 
> see whats happening whichever way you do it...
> 
> 
>>Oh, also I think it is good to initialize the variable immediately.
>>
> 
> I agree there.
> 
> 
>>Initializing it to a senseless value like NULL isn't really helpful,
>>
> 
> Not true. Many a NULL has caused a crash when an unitinialised 
> variable would have kept running - with completely wrong results. 
> A crash in those circumstances is a good thing! And NULLS help 
> achieve it!
> 
> 
>>function, whereas if you declare the variable later you can construct
>>it properly then.  
>>
> 
> OTOH If you want to use aiabvle declared further down a function near 
> the top you have to go hunt for the declaration and cut n paste it 
> back up to where you need it. If its declared at the top its always 
> available.
> 
> 
>>This is also even more significant in C++ than in
>>Java or Python when working with classes.  Either you'll end up
>>wasting some resources by first constructing a default instance of the
>>class, and then later constructing the one you wanted and copying it
>>
> 
> I see the point of wasted resource but not sure how Java/Python 
> helps here. If you initialize the variable to a dummy object you 
> waste resource and in all 3 languages that resource stays wasted 
> till you get rid of it.
> 
> 
>>| The only reasonable exception to this are single letter variablers
>>| used as loop counters etc.
>>
>>Loop counters should be declared in the opening of the loop, IMO.
>>
> 
> Agreed, thats what I meant.
> 
> 
>>It probably depends on whether the "regular" C++'ers started with C or
>>not.
>>
> 
> Nope, It probably depends more on how many months or years they've 
> spent debugging other peoples code :-)
> 
> 
>>C required all locals to be declared at the start of a block.  I think
>>that's due to the early implementations, but I'm just hypothesizing
>>here.
>>
> 
> Its good software engineering practice as taught at the time 
> - Pascal for example requires variables to be declared in a 
> var section of the code, as does ADA and Modula (and even COBOL!)
> 
> 
>>Java has the same rules as C++, and all the code I've written and read
>>seems to follow the "don't declare it until you actually need it"
>>style.
>>
> 
> Yes, and maintenance programmers the world over are learning 
> to hate it! Our Java style guides at work have recently been 
> ammended to insist that all variables be declared at the top 
> of scope - previously it was just a recommendation...)
> 
> 
>>Of course, much of this is just a matter of style with little
>>technical merit either way, so do as you please :-).
>>
> 
> If it hits the time to fix faults its more than just style.
> When an operational fault has to be fixed in lkess than 4 hours 
> say, you really don't have time to cast about looking for variables.
> It becomes a matter of real bottom line accounting.
> 
> Alan g.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show





From tim.one@comcast.net  Thu Jul  4 19:55:12 2002
From: tim.one@comcast.net (Tim Peters)
Date: Thu, 04 Jul 2002 14:55:12 -0400
Subject: [Tutor] slots and inheritance - a bit more
In-Reply-To: <001b01c22386$f13705a0$0334fea9@carol>
Message-ID: <LNBBLJKPBEHFEDALKOLCGECAACAB.tim.one@comcast.net>

[Arthur Siegel]
> But the *functionality* of slots is not inherited

I'm not sure what you mean.  The goal of slots is to save memory, and the
more-efficient memory layout at the C level is inherited (indeed, that's why
you can't inherit from more than one base class with __slots__).

> - unless I kill B's __dict__.  Correct? If so, is that doable?

In a single-inheritance hierarchy, you can specify __slots__ at all, no, or
any subset of levels.  Instances of a level that defines __slots__  have no
dicts; instances of a level that doesn't have __slots__ do have dicts.  For
example,

class A(object):
    __slots__ = 'a'

class B(A):
    __slots__ = []

Then an instance of B has no dict (because it *also* specifies __slots__,
albeit an empty set of slots), and can only use the inherited 'a' as an
attribute name.

> I kind of thought the restriction - as in object.kolor = "blue" when you
> meant object.color= "blue" was of the essence of slots.

That's a *consequence* of the memory-saving aspect.  Dicts are rather large
data structures, and the essence of slots is that an object of a class using
__slots__ has no dict.  Without a dict, the names of all attributes have to
be known at class-creation time, as there's no longer any way to add new
attributes dynamically:  the memory layout is fixed for all time when the
class is created.  It's legitimate to think of that as a feature, or to
think of that as a restriction, but in either case the lack of dynamic
attribute creation is a consequence and not a goal.  If Guido could have
made the memory layout more efficient without sacrificing dynamic attribute
creation, he would have.

> But if you mean the multi-heritance restriction - yes.  Happens to be a
> deal killer in my case.

Damn!  We'll send you a refund check at close-of-business Monday <wink>.




From ajs@ix.netcom.com  Thu Jul  4 21:00:06 2002
From: ajs@ix.netcom.com (Arthur Siegel)
Date: Thu, 4 Jul 2002 16:00:06 -0400
Subject: [Tutor] slots and inheritance - a bit more
References: <LNBBLJKPBEHFEDALKOLCGECAACAB.tim.one@comcast.net>
Message-ID: <000701c22395$687cbde0$0334fea9@carol>

> I'm not sure what you mean.  The goal of slots is to save memory, and the
> more-efficient memory layout at the C level is inherited (indeed, that's
why
> you can't inherit from more than one base class with __slots__).

>From What's New in Python 2.2:

>>Finally, it's possible to constrain the list of attributes that can be
referenced on an >>object using the new __slots__ class attribute. Python
objects are usually very >>dynamic; at any time it's possible to define a
new attribute on an instance by just >>doing obj.new_attr=1. This is
flexible and convenient, but this flexibility can also >>lead to bugs, as
when you meant to write obj.template = 'a' but made a typo and >>wrote
obj.templtae by accident.

No reading of the What's New could find any indication that what you
describe as a side effect is other than main purpose of slots.  Though I
happen
to believe you.

And it is true that Guido's http://www.python.org/2.2/descrintro.html only
talks of slots in connection with memory issues.

So I'll settle for a refund only on the What's New portion of my investment.

> [Arthur Siegel]
> > But the *functionality* of slots is not inherited
>
> > - unless I kill B's __dict__.  Correct? If so, is that doable?
>
> In a single-inheritance hierarchy, you can specify __slots__ at all, no,
or
> any subset of levels.  Instances of a level that defines __slots__  have
no
> dicts; instances of a level that doesn't have __slots__ do have dicts.
For
> example,
>
> class A(object):
>     __slots__ = 'a'
>
> class B(A):
>     __slots__ = []
> Then an instance of B has no dict (because it *also* specifies __slots__,
> albeit an empty set of slots), and can only use the inherited 'a' as an
> attribute name.

I would have thought that B's empty __slots__ would override A's __slots__
and leave B with no attribute slots.

The fact is - as you tutor - it is otherwise.

B's __slot__ declaration, in my terminology, "appends" to __slots__
of A - is what I'm learning.

>>> class A(object):
 __slots__=("a")

>>> class B(A):
 __slots__=("b")

>>> b=B()
>>> b.a=4
>>> print b.a
4

Now, I might get to where I was hoping to get with slots. No objection here
to taking advantage of a side-effect.  Basically had concluded I need to
build
an optlist for my **kw args.  __slots__ might end up working as that -  with
some
side benefits.

> > But if you mean the multi-heritance restriction - yes.  Happens to be a
> > deal killer in my case.
>
> Damn!  We'll send you a refund check at close-of-business Monday <wink>.

Knowing what I know now, slots might yet do it for me.  Hold the check
(escrowed under the normal arrangements).


Art




From charlie@begeistert.org  Thu Jul  4 23:34:43 2002
From: charlie@begeistert.org (Charlie Clark)
Date: Thu, 04 Jul 2002 22:34:43 +0000
Subject: [Tutor] Re: Tutor digest, Vol 1 #1738 - 10 msgs
In-Reply-To: <20020704195502.19686.42628.Mailman@mail.python.org>
References: <20020704195502.19686.42628.Mailman@mail.python.org>
Message-ID: <20020704223443.3347.6@gormenghast.1025797203.fake>

On 2002-07-04 at 19:55:02 [+0000], you wrote:
> class Beeper(Tkinter.Tk):
>   def __init__(self):
>     Tkinter.Tk.__init__(self)
>     Tkinter.Button(self, text=3D"Beep",
>       command=3Dself.beep).pack()
>     Tkinter.Button(self, text=3D"Quit",
>       command=3Dself.quit).pack()
> 
>   def beep(self):
>     print "Beep"
> 
> if __name__=3D=3D"__main__":
>   b =3D Beeper()
>   b.mainloop()
> 
> 
> Why has my Beeper instance no attribute 'beep' ??

Well, I think there are two things wrong but the error message is a 
standard Python gotcha: you are calling beep() before you have assigned it. 
But even if you define beep earlier I think you have a problem by calling a 
method as if it were an attribute.
self.beep is an attribute
beep(self) is a method and is directly accessible from within instances of 
the class even if the calls look the same from outside

a = Beeper()
a.beep
a.beep()

I'm not an expert on these things so I don't know what the real 
consequences of this are but look at the following:
>>> class Charlie:
...     def __init_(self):
...             self.beep = "BeeeP"
...     def beep(self):
...             print "Beep!" 
>>> a = Charlie
>>> a.beep
<unbound method Charlie.beep>
>>> a.beep()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unbound method beep() must be called with instance as first 
argument

Common sense says your naming convention is likely to cause confusion.

Charlie



From dominic.fox" <dominic.fox@ntlworld.com  Thu Jul  4 23:28:26 2002
From: dominic.fox" <dominic.fox@ntlworld.com (dominic.fox)
Date: Thu, 4 Jul 2002 23:28:26 +0100
Subject: [Tutor] SOAP
References: <20020704195502.19686.42628.Mailman@mail.python.org>
Message-ID: <000901c223aa$1e043580$4ac10550@tinypc>

Hi all,

I had some success recently talking to Blogger with xmlrpclib, so I thought
I'd try talking to Google via SOAP. That's not so easy. ZSI is somewhat
sparsely documented. Does anyone know where I can go to get up to speed on
SOAP generally and Python SOAP implementations in particular?

thanks,
Dominic




From dylan.belsey@baesystems.com  Thu Jul  4 23:35:26 2002
From: dylan.belsey@baesystems.com (BELSEY, Dylan)
Date: Fri, 5 Jul 2002 08:35:26 +1000
Subject: [Tutor] Attribute Error
Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B963209C@WTNTEX1>

Hi,
	Cut and paste your code into an IDLE edit window and ran from a DOS
prompt.  Seems to work as expected, ie. I do not get the traceback error.
In my limited experience, looking at the code, it should run OK.

-----Original Message-----
From: Nicole Seitz [mailto:Nicole.Seitz@urz.uni-hd.de]
Sent: Friday, 5 July 2002 05:52
To: tutor@python.org
Subject: [Tutor] Attribute Error


Hi there!

Can anyone explain why I get this traceback 

Traceback (most recent call last):
  File "beeper.py", line 16, in ?
    b = Beeper()
  File "beeper.py", line 7, in __init__
    command=self.beep).pack()
AttributeError: Beeper instance has no attribute 'beep'


when running


import Tkinter

class Beeper(Tkinter.Tk):
  def __init__(self):
    Tkinter.Tk.__init__(self)
    Tkinter.Button(self, text="Beep",
      command=self.beep).pack()
    Tkinter.Button(self, text="Quit",
      command=self.quit).pack()

  def beep(self):
    print "Beep"

if __name__=="__main__":
  b = Beeper()
  b.mainloop()


Why has my Beeper instance no attribute 'beep' ??

Many thanx in advance.


Nicole


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



From dyoo@hkn.eecs.berkeley.edu  Fri Jul  5 00:07:51 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 4 Jul 2002 16:07:51 -0700 (PDT)
Subject: [Tutor] SOAP
In-Reply-To: <000901c223aa$1e043580$4ac10550@tinypc>
Message-ID: <Pine.LNX.4.44.0207041600060.12348-100000@hkn.eecs.berkeley.edu>


On Thu, 4 Jul 2002, dominic.fox wrote:

> Hi all,
>
> I had some success recently talking to Blogger with xmlrpclib, so I
> thought I'd try talking to Google via SOAP. That's not so easy. ZSI is
> somewhat sparsely documented. Does anyone know where I can go to get up
> to speed on SOAP generally and Python SOAP implementations in
> particular?

Hi Dominic,

There's some tutorials on the ZSI implementation of SOAP on IBM's
wonderful "developerWorks" web site:

###
http://www-106.ibm.com/developerworks/webservices/library/ws-pyth5/
http://www-106.ibm.com/developerworks/library/ws-pyth6/?open&l=968,t=grws,p=py2
###

I haven't read these tutorials, but I'd be happy to take a look --- we can
learn SOAP together!  *grin*



Hmmm... I do remember reading that someone had developed a Google library
for Python... let me check...

    http://diveintomark.org/projects/#pygoogle

So we can take a look at the source code there if we're in a hurry.


Best of wishes to you!




From dyoo@hkn.eecs.berkeley.edu  Fri Jul  5 00:21:09 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 4 Jul 2002 16:21:09 -0700 (PDT)
Subject: [Tutor] SOAP
In-Reply-To: <Pine.LNX.4.44.0207041600060.12348-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0207041620100.12348-100000@hkn.eecs.berkeley.edu>

> There's some tutorials on the ZSI implementation of SOAP on IBM's
> wonderful "developerWorks" web site:
>
> ###
> http://www-106.ibm.com/developerworks/webservices/library/ws-pyth5/
> http://www-106.ibm.com/developerworks/library/ws-pyth6/?open&l=968,t=grws,p=py2
> ###

Hi Dominic,

I found another one:

    http://www.xml.com/pub/a/2002/06/12/soap.html

This one looks good: it talks about ZSI and Google, so it might be what
we're looking for.


Talk to you later!




From ajs@ix.netcom.com  Fri Jul  5 00:17:08 2002
From: ajs@ix.netcom.com (Arthur Siegel)
Date: Thu, 4 Jul 2002 19:17:08 -0400
Subject: [Tutor] more slot stuff
Message-ID: <000001c223d3$9cc011e0$0334fea9@carol>

Apologies to the folks who do not share my new found interest in slots.

Which I am starting to think of as the quark of the Python object world.

>>> class A(object):
 __slots__=("a")
>>> class B(A):
 __slots__=("b")
>>> b=B()
>>> b.__slots__
'b'
>>> b.a=4
In other words "a" is somehow acting as a slot for
B instances, but is not *in* B.__slots__.
How would one then reference, introspect, whatever
as to what are in fact available slots for instances of B?


And a possibly minor bug:

>>> class A(object):
 __slots__="a"

>>> class B(object):
 pass

>>> class C(A,B):
 __slots__=("b")


>>> c=C()
>>> c.a=1
>>> c.b=2
>>> c.c=3
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in ?
    c.c=3
SystemError: C:\Code\221\Objects\dictobject.c:511: bad argument to internal
function

If B is a classic class and I do the same multi-inheritance I get the normal
error message:

AttributeError: 'C' object has no attribute 'c'

So its the error message, not the behavior that I am pointing to as probably
unintended.

Art




From p.hartley@spitech.com  Fri Jul  5 04:59:07 2002
From: p.hartley@spitech.com (Paul Hartley)
Date: Fri, 5 Jul 2002 11:59:07 +0800
Subject: [Tutor] [Tutor]Upgrading python, Gadfly and Zope
Message-ID: <016701c223d8$7fd70020$ebe710ac@pc7345>

This is a multi-part message in MIME format.

------=_NextPart_000_0164_01C2241B.5DD12620
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

I have python 2.0 and need to upgrade to 2.2 (according to the version =
of Gadfly I just downloaded), do I uninstall 2.0 first or just install =
2.2 on top of 2.0?=20

Zope has its own version of python, so now I have two versions, can I =
upgrade the version in the zope directory too or do I need to update the =
whole of zope (I know this is  azope question, but it is python =
related!)

Finally, can I use the version of Gadfly that came with zope from my =
'normal' python applications? I think I must be able to. If so I might =
not install the Gadfly version I downloaded, just use the one in the =
Zope products directory.

Thank you in advance....

Paul







------=_NextPart_000_0164_01C2241B.5DD12620
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>I have python 2.0 and need to upgrade =
to 2.2=20
(according to the version of Gadfly I just downloaded), do I uninstall =
2.0 first=20
or just install 2.2 on top of 2.0? </FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Zope has its own version of python, so =
now I have=20
two versions, can I upgrade the version in the zope directory too or do =
I need=20
to update the whole of zope (I know this is&nbsp; azope question, but it =
is=20
python related!)</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Finally, can I use the version of =
Gadfly that came=20
with zope from my 'normal' python applications? I think I must be able =
to. If so=20
I might not install the Gadfly version I downloaded, just use the one in =
the=20
Zope products directory.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thank you in advance....</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Paul</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_0164_01C2241B.5DD12620--




From dman@dman.ddts.net  Fri Jul  5 07:20:23 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Fri, 5 Jul 2002 01:20:23 -0500
Subject: [Tutor] Re: more slot stuff
In-Reply-To: <000001c223d3$9cc011e0$0334fea9@carol>
References: <000001c223d3$9cc011e0$0334fea9@carol>
Message-ID: <20020705062023.GA6319@dman.ddts.net>

--1yeeQ81UyVL57Vl7
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, Jul 04, 2002 at 07:17:08PM -0400, Arthur Siegel wrote:
| Apologies to the folks who do not share my new found interest in slots.
|=20
| Which I am starting to think of as the quark of the Python object world.
|=20
| >>> class A(object):
|  __slots__=3D("a")
| >>> class B(A):
|  __slots__=3D("b")
| >>> b=3DB()
| >>> b.__slots__
| 'b'
| >>> b.a=3D4
| In other words "a" is somehow acting as a slot for
| B instances, but is not *in* B.__slots__.
| How would one then reference, introspect, whatever
| as to what are in fact available slots for instances of B?

>>> dir( b )
['__class__', '__delattr__', '__doc__', '__getattribute__',
'__getstate__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__repr__', '__setattr__', '__slots__', '__str__',
'a', 'b']

(notice the 'a' and 'b' at the end of the list)

-D

--=20

Python is executable pseudocode. Perl is executable line noise.
=20
http://dman.ddts.net/~dman/


--1yeeQ81UyVL57Vl7
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0lOqYACgkQO8l8XBKTpRRF1wCgmW3ntW2IbMpZE1e5YfKwvLyb
EgAAn1unQ0BaWXrliXc5+1rZSk/dcj4U
=JJ5O
-----END PGP SIGNATURE-----

--1yeeQ81UyVL57Vl7--



From dman@dman.ddts.net  Fri Jul  5 07:24:47 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Fri, 5 Jul 2002 01:24:47 -0500
Subject: [Tutor] Re: [Tutor]Upgrading python, Gadfly and Zope
In-Reply-To: <016701c223d8$7fd70020$ebe710ac@pc7345>
References: <016701c223d8$7fd70020$ebe710ac@pc7345>
Message-ID: <20020705062447.GB6319@dman.ddts.net>

--rS8CxjVDS/+yyDmU
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Jul 05, 2002 at 11:59:07AM +0800, Paul Hartley wrote:
| I have python 2.0 and need to upgrade to 2.2 (according to the
| version of Gadfly I just downloaded), do I uninstall 2.0 first or
| just install 2.2 on top of 2.0?=20

If you don't want to keep 2.0, I recommend uninstalling it first
(if you're on windows;  windows has a habit of not cleaning up).

| Zope has its own version of python, so now I have two versions, can
| I upgrade the version in the zope directory too or do I need to
| update the whole of zope (I know this is  azope question, but it is
| python related!)

Zope requires python 2.1.3.  Unfortunately it doesn't work with 2.2
(AFAIK).  The next major release will use a newer version of python
(2.2 or more likely 2.3).
=20
| Finally, can I use the version of Gadfly that came with zope from my
| 'normal' python applications?

Sure, just copy the modules/packages to your site-packages directory.
The version in zope is somewhere in between the gadfly releases.  The
last release I saw was really old (python 1.5.2) and didn't gave
warnings on some newer pythons and didn't work on others.  The zope
people patched it up some so that it would behave on the version of
python that zope works with.  Now the gadfly creator is back in
business updating it, and I suppose a new version is available which
is what you found.

HTH,
-D

--=20

In my Father's house are many rooms; if it were not so, I would have
told you.  I am going there to prepare a place for you.  And if I go and
prepare a place for you, I will come and take you to be with me that you
also may be where I am.
        John 14:2-3=20
=20
http://dman.ddts.net/~dman/


--rS8CxjVDS/+yyDmU
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0lO68ACgkQO8l8XBKTpRTI4ACfWsoHPxuK7U84J+4SYn3eREmg
xwgAn1BmJkhqdDo7GrzmFSvJ+HJMI+XZ
=vPOA
-----END PGP SIGNATURE-----

--rS8CxjVDS/+yyDmU--



From alan.gauld@bt.com  Fri Jul  5 11:12:26 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 5 Jul 2002 11:12:26 +0100
Subject: [Tutor] Re: small program in Python and in C++
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C70A@mbtlipnt02.btlabs.bt.co.uk>

First of all apologies to the pythonistas for dragging 
things well off topic!

> A few questions for the less-learned (such as myself)....
> 
> What exactly is refactoring? 

Taking an existing function (or class) and breaking it 
into smaller more atomic units.

Noddy example:

def bigun(s):
   f = open(s)
   str = f.read()
   str = string.replace(str,'$','#')
   for chr in str:
      c = string.toupper(chr)
      if c > 'H':
          newstr = newstr + c
   return newstr

Not very useful but looking at it we could factor out two 
functions from that:

def fileAsFixedupString(s):
   s = open(s).read()
   return string.replace(s,'$','#')

def getHiChars(str):
   for chr in str:
      c = string.toupper(chr)
      if c > 'H':
          newstr = newstr + c
   return newstr

def bigun:(s)
   str = fileAsFixedupString(s)
   return getHiChars(str)

Thats refactoring....

> How do NULLs help achieve an informative crash when an uninitialized 
> variable wouldn't? 

An uninitialised pointer, for example, will point at oome random bit 
of memory so if I do:

void f(){
  char* sp;  // not initialised
  char* s2 = "Some crappy string"; 
  
  strcpy(sp,s2); //<-- tries to copy s2 to wherever sp happens to point!
}

But if sp is set to NULL it will go KABOOM! and segv on the strcpy...
There are literally dozens of C++ standard library calls that will 
explode with a NULL input but otherwise return completely 
spurious results if fed an unitialised value!

Less predictably for numbers, initialising to zero will often 
cause errors like divide by zero failures where using an unitialised 
int may give a "valid" but wrong answer... nasty in a nuclear reactor 
controller say...

Alan G.

PS The other maintenance programmers favourite is in C/C++ 
comparisons always put the constant on the left:

if (NULL == sp)

rather than 

if (sp == NULL)

that will reliably catch single '=' signs another common C/C++ error.



From pythontutor@venix.com  Fri Jul  5 15:07:17 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri, 05 Jul 2002 10:07:17 -0400
Subject: [Tutor] Re: slots - a more basic issue
References: <001501c22384$ea169940$0334fea9@carol>
Message-ID: <3D25A815.2050404@venix.com>

We've been concerned about attribute name errors for our Record classes
which tie back to database tables.  Our solution was to have a class
attribute named fieldlist with the list of fields from the associated
database table.  Then we used __getattr__, __setattr__, and __delattr__
to enforce the requirement that all attributes had to be listed in the
class's fieldlist.  This avoids doing special handling elsewhere in the
class methods.

Here is a simplified example where the fieldlist is wired into the class
definition.  This approach may work for you.

class Example(object):
     fieldlist = ('a','b','c')

     def __getattr__(self, key):
         if key in self.fieldlist:    # provide default value of None
             return None
         else:
             raise AttributeError("%s is not an attribute of this object" % key)

     def __setattr__(self, key, value):
         if key in self.fieldlist:
             self.__dict__[key] = value
         else:
             raise AttributeError("%s is not an attribute of this object" % key)

     def __delattr__(self, key):
         raise AttributeError( "Attribute %s must not be deleted" % key)

I gave this some light testing and it seemed to work.  HTH.



Arthur Siegel wrote:

> Dman writes -
> 
> 
>>Use a method signature such as :
>>            def __init__(self, x, y, color=None ):
>>and you'll get :
>>
> 
>>Traceback (most recent call last):
>> File "<stdin>", line 1, in ?
>>TypeError: __init__() got an unexpected keyword argument 'kolor'
>>
> 
> Yeah, but I have lots of potential attributes, and lots
> of inheritance relationships - which makes the method signature
> unwieldy - just what **kw seems to be made for.
> 
> Looks like I'll end up with building a list of attributes and something
> like:
> 
> for key in kws:
>    if key not in optlist:
>       print 'WARNING  " %s" not a valid keyword for %s'
> %(key,self.__class__.__name__)
> 
> Just found a bunch of typos in my demos doing this approach.
> 
> Art
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From emil@lysator.liu.se  Fri Jul  5 16:15:07 2002
From: emil@lysator.liu.se (Emil Styrke)
Date: 05 Jul 2002 17:15:07 +0200
Subject: [Tutor] addition
References: <F4260wcP2dIulddm2ps00000992@hotmail.com>
Message-ID: <87n0t62olg.fsf@i110.ryd.student.liu.se>

"Terje Johan Abrahamsen" <terjeja@hotmail.com> writes:

> Hello,
>=20
>     I have to make a program that compares policies for an accounting
> department. It uses two different systems, AS/400 and Win Excel. I
> have built all the surounding code moving numbers back and forth,
> formatting and so forth, but the main calculations are missing. Here
> is the problem:
>=20
> In Excel up to 7 accounts can have the same policynumber, while up to
> 3 policies in the AS/400 system can have the same policynumber. Any
> number of policies in either system can match any number of policies
> in the other system. So, therefore for example 5 Excel amounts can add
> up to the approximate amount (+-$5) of 2 AS/400 accounts. If this is
> the case, these amounts should be marked. If I haven't forgotten all
> my statistics skills, that should equal up to (7!=3D5040 * 3!=3D6)=3D30240
> calculations. How can I do this? There is no way I can use my normal
> way of doing this (with less numbers) by writing in the possibilities,
> as in if a+b=3Dc:print yes, elif a+c =3D d: print yes and so forth until I
> have used all the possibilities. I need the computer to do this part
> this time. (I am a beginner, so please keep it simple.)
>

I'm not sure I understand the problem.  You want to find if a subset
of up to seven numbers adds up to approximately the same as a subset
of up to three other numbers?  In that case, the code below might do
it, although i'm sure there are better and faster ways to do it.  The
trick is to first calculate lists of all possible sums of each of the
sets and then compare them with each other.

I've intentionally left out some idioms in order to make the code
easier to understand.  Feel free to ask questions if something is
unclear!

        /Emil

#  This function takes a set of items (numbers in your case) and returns
#  a list of all possible subsets of it. (including the empty set)
#  It does this by calling itself recursively.  This concept is not the
#  easiest one to grasp for a beginner, but i couldn't find a better way.
#  If you like to, just consider it a "black box" and ignore its inner
#  workings. :)
#
#  (If you try this one out, you'll see that there are 2^n combinations
#  for a set with n elements, and not n!. (I'm too tired right now
#  to try to find out why...)
def powerset(set, res=3D[[]]):
  if len(set) =3D=3D 0:
    return res                  # If the set is empty, return our saved res=
ult
  first_element =3D set[0]        # Get the first element of the set
  other_elements =3D set[1:]      # And the rest
  new_elements =3D []             # Now we calculate a list of new elements
                                # to add to our result.  To do that we
                                # iterate through the subsets we already
                                # have and append the current element to
                                # them.
  for i in res:
    new =3D i[:]                  # We have to copy the list first, or else
                                # the original will be changed too, and
                                # we don't want that.
    new.append(first_element)
    new_elements.append(new)
  return powerset(other_elements, res + new_elements)  # Finally, we call
                                # powerset again, but with the first
                                # element of "set" removed, and our new
                                # elements added to the result variable.

#  This function takes a set of numbers and returns a list of sums of all
#  possible subsets.
def makesums(set):
  combinations =3D powerset(set)  # Get a list of combinations by calling
                                # powerset.

  sums =3D []                     # initialize the list of sums

  for i in combinations:        # Go through all the combinations
    sum =3D 0                     # Initialize the current sum to 0
    if len(i) =3D=3D 0:		# If there are no numbers in this set,
        continue		# skip to the next.
    for j in i:                 # Go through all the numbers in this subset=
..
      sum =3D sum + j             # ..and add them to "sum"
    sums.append(sum)            # Finally, we add each sum to the list of s=
ums
  return sums                   # ..and return it

# This function takes two sets (lists) of numbers and prints out "yes"
# if there is a subset of elements in set1 which add up to a subset of
# elements in set2, +-5.
def search(set1, set2):
  match =3D 0
  sums1 =3D makesums(set1)        # Get the first list of sums
  sums2 =3D makesums(set2)        # Get the second list of sums
  for i in sums1:               # For each of the first list of sums
    for j in sums2:             # Go through the second list of sums
      if i - 5 < j and i + 5 > j:  # And check if they are within +-5 of
        match =3D 1               # each other.
  if match =3D=3D 0:
    print "no"
  else:
    print "yes"
=20=20
> Thanks,
> Terje
>=20
>=20
>=20
> _________________________________________________________________
> Join the world=92s largest e-mail service with MSN
> Hotmail. http://www.hotmail.com
>=20
>=20
>=20
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor




From charlie@begeistert.org  Fri Jul  5 18:27:17 2002
From: charlie@begeistert.org (Charlie Clark)
Date: Fri, 05 Jul 2002 17:27:17 +0000
Subject: [Tutor] Re: SOAP
In-Reply-To: <20020705151802.29139.78805.Mailman@mail.python.org>
References: <20020705151802.29139.78805.Mailman@mail.python.org>
Message-ID: <20020705172717.6121.20@gormenghast.1025872442.fake>

On 2002-07-05 at 15:18:02 [+0000], you wrote:
> 
> Hi all,
> 
> I had some success recently talking to Blogger with xmlrpclib, so I thought
> I'd try talking to Google via SOAP. That's not so easy. ZSI is somewhat
> sparsely documented. Does anyone know where I can go to get up to speed on
> SOAP generally and Python SOAP implementations in particular?

Hi Dominic,

Duncan Grisby gave an excellent talk on web services at Europython last week 
comparing xmlrpc, SOAP and CORBA and covering various implementations.

The presentation is available at http://www.grisby.org/

Charlie



From Doug.Shawhan@gecits.ge.com  Fri Jul  5 18:35:37 2002
From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com)
Date: Fri, 5 Jul 2002 13:35:37 -0400
Subject: [Tutor] Interacting with Web Pages via HTTPlib, HTMLlib and other fun
Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54C7C@msxcvg02itscge.gecits.ge.com>

Hi Everyone,

I have a need to interact with a website that updates a database. The site
is part of our inventory system. It is impossible to get access to the
backend (oracle) due to various constraints. The goal is to write a script
that parses a comma-delimited text file (output from a barcode scanner) and
squirts that data into the web form. 
 
Can anyone point me to a good example of a script that does something
similar?

Thanks!

d



From jeff@ccvcorp.com  Fri Jul  5 18:55:39 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri, 05 Jul 2002 10:55:39 -0700
Subject: [Tutor] Re: Tutor digest, Vol 1 #1738 - 10 msgs
References: <20020704195502.19686.42628.Mailman@mail.python.org> <20020704223443.3347.6@gormenghast.1025797203.fake>
Message-ID: <3D25DD9B.173673DF@ccvcorp.com>


Charlie Clark wrote:

> On 2002-07-04 at 19:55:02 [+0000], you wrote:
> > class Beeper(Tkinter.Tk):
> >   def __init__(self):
> >     Tkinter.Tk.__init__(self)
> >     Tkinter.Button(self, text=3D"Beep",
> >       command=3Dself.beep).pack()
> >     Tkinter.Button(self, text=3D"Quit",
> >       command=3Dself.quit).pack()
> >
> >   def beep(self):
> >     print "Beep"
> >
> > if __name__=3D=3D"__main__":
> >   b =3D Beeper()
> >   b.mainloop()
> >
> > Why has my Beeper instance no attribute 'beep' ??
>
> Well, I think there are two things wrong but the error message is a
> standard Python gotcha: you are calling beep() before you have assigned it.

Actually, no, the beep() method is *not* being called before assigning to it.
The attribute *should* be getting created during class-definition time.  When
the instance is being initialized (b = Beeper() calls Beeper.__init__() ), the
beep() method has already been defined.

My suspicion is that the original code, which threw the AttributeError,
probably suffered from an indentation problem.  If the 'def beep(self):' line
were not properly lined up, it would not be read as part of the Beeper class;
subsequently, any attempt to use Beeper.beep() would give exactly the
AttributeError shown.  There is no such error in the code as posted, though --
Nicole, did you copy & paste the code, or did you retype it?  If you retyped it
(or fiddled with the formatting for it, or replaced tabs with spaces, or...)
then that probably corrected the error -- do the same thing with your original
code, and you should be fine.  ;)


> But even if you define beep earlier I think you have a problem by calling a
> method as if it were an attribute.
> self.beep is an attribute
> beep(self) is a method and is directly accessible from within instances of
> the class even if the calls look the same from outside

self.beep is an attribute whose value is a (bound) method object -- what Nicole
is doing (command=self.beep) is the proper way to get a reference to a bound
method.  (A bound method is one that is already associated with a specific
instance of a class -- it already has the self parameter specified -- whereas
an unbound method is *not* associated with a class instance, and needs to have
an instance passed to it.)

Jeff Shannon
Technician/Programmer
Credit International





From jeff@ccvcorp.com  Fri Jul  5 19:09:44 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri, 05 Jul 2002 11:09:44 -0700
Subject: [Tutor] Re: [Tutor]Upgrading python, Gadfly and Zope
References: <016701c223d8$7fd70020$ebe710ac@pc7345>
Message-ID: <3D25E0E8.2CE0D024@ccvcorp.com>

Paul Hartley wrote:

> I have python 2.0 and need to upgrade to 2.2 (according to the
> version of Gadfly I just downloaded), do I uninstall 2.0 first or
> just install 2.2 on top of 2.0?

That's entirely up to you.  Both versions of Python can coexist quite
happily -- they will install to different directories, and you can use
either one at your option.  The only conflict will be, which one is
the default version -- in other words, which one starts up when you
type '$ python'.  Typically, this will be whichever version you
installed last, but that can be changed.  (Let us know if you need to
know how to change it -- and be sure to mention what OS you're using.)



>  Zope has its own version of python, so now I have two versions, can
> I upgrade the version in the zope directory too or do I need to
> update the whole of zope (I know this is  azope question, but it is
> python related!)

AFAIK (though I'm mostly unfamiliar with Zope), the reason that Zope
comes with its own version is because it may not work properly with a
different version.  By including its own version, it doesn't have to
worry that you upgrading your main version will break Zope.  You
shouldn't try to upgrade Zope's python without upgrading your entire
Zope installation.


> Finally, can I use the version of Gadfly that came with zope from my
> 'normal' python applications? I think I must be able to. If so I
> might not install the Gadfly version I downloaded, just use the one
> in the Zope products directory.

There's no guarantee that that version of Gadfly will work with a
different version of Python than the one which came with Zope, but it
might -- and if your main Python installation *is* the same version,
then it definately will.  You can accomplish this by either copying
the package directory to your main Python's site-packages (though if
you're doing this, it's accomplishing much the same thing as
installing the separate Gadfly that you downloaded, and you'd be
better off just using that), or you can add the existing Gadfly
directory to Python's sys.path (either by editing sitecustomize.py, or
by using .pth files).

However, I'd think that (unless disk space is a serious concern, or
you run into problems with the two versions of Gadfly not
interoperating properly) you're probably better off using the newer,
downloaded Gadfly rather than reusing the Zope version of Gadfly.

Jeff Shannon
Technician/Programmer
Credit International







From jeff@ccvcorp.com  Fri Jul  5 19:13:40 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri, 05 Jul 2002 11:13:40 -0700
Subject: [Tutor] Re: small program in Python and in C++
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C70A@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3D25E1D4.81F9E122@ccvcorp.com>


alan.gauld@bt.com wrote:

> First of all apologies to the pythonistas for dragging
> things well off topic!
>
> > A few questions for the less-learned (such as myself)....
> >
> > What exactly is refactoring?
>
> Taking an existing function (or class) and breaking it
> into smaller more atomic units.

This is the typical case, although refactoring can also mean combining two
existing functions/classes into a single one (to eliminate overlap, for
example).

The essence of refactoring is that it is re-organizing your code to a
structure that is better-suited to the problem you're trying to solve.  Any
time you think "...instead of the way it's being done now, if we did it
*this* other way it would make more sense ...", that's refactoring.

Jeff Shannon
Technician/Programmer
Credit International





From Kyle Babich" <kb@kb5.org  Fri Jul  5 22:22:50 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Fri, 5 Jul 2002 21:22:50 +0000
Subject: [Tutor] simple problem
Message-ID: <20020705212250.A455A6D9D7@www.fastmail.fm>

I know this is simple, but I can find the answer in the documentation
(although I guess it has to be there somewhere).
Please bear with me because if you've read any of my messages you know
I'm a complete newbie to python.

I know how to do something like:
myname = "Kyle"
print "Hello, my name is", myname

But how would I call up the myname variable in the middle of the print
command?
(Ie. print "Hello, #myname variable here# where do you live?"
---
Kyle



From dominic.fox" <dominic.fox@ntlworld.com  Fri Jul  5 22:41:28 2002
From: dominic.fox" <dominic.fox@ntlworld.com (dominic.fox)
Date: Fri, 5 Jul 2002 22:41:28 +0100
Subject: [Tutor] Re: SOAP
References: <20020705151802.29139.78805.Mailman@mail.python.org>
Message-ID: <002301c2246c$b95ad1c0$4ac10550@tinypc>

Thanks to Danny and Charlie for hints & pointers on this.

xmlrpclib has slightly spoiled me for SOAP, because it's very "Pythonic" as
Dr Grisby says, and simple, and intuitive. ZSI SOAP is not any of these
things, although that's probably not its fault. The key to the magic kingdom
is guarded by a slightly fearsome-looking troll, beneath whose glowering
visage I'm currently trembling somewhat.

developerWorks is definitely the people's friend, as I've found a couple of
times before. I had a simple problem using the ZSI tutorial, however: one of
the namespaces specified by ZSI SOAP refers to a schema hosted at zolera.
com, which is currently unavailable. You therefore get an error when you try
to run the tutorial example. If all ZSI SOAP calls need zolera.com to be up
and running in order to work, then any SOAP system built on top of ZSI is
going to have an extra vulnerability; it will also not work if you want to
run it across an intranet without external internet access (which is one of
my potential deployment targets). Presumably it's possible to make a local
copy of the schema, and refer to that instead. The tutorial doesn't say how,
though; and I can't make a local copy if I can't access the remote one
because the server that hosts it is vacationing in Elbonia. I also don't
know whether the schema in question needs to be accessible by both parties
to the SOAP transaction: if it does, then there's no point in my keeping a
copy on my desktop machine's hard-disk...

pyGoogle uses SOAP.py, which is less sophisticated than ZSI but also less
newbie-frighteningly feature-intensive. I downloaded and installed SOAP.py,
and had another go. Captain Haddock was venting his spleen at me
("slubberdegullions!") within a few minutes, which was encouraging. Here's
what I tried next, and what happened:

>>> google = SOAP.SOAPProxy(
 "http://api.google.com/search/beta2",
 namespace="urn:GoogleSearch")

>>> google.doGoogleSearch(key=myLicenceKey,
       q="Python SOAP",
       start=0,
       maxResults=10,
       filter=1,
       restrict='',
       safeSearch=0,
       lr='',
       ie='latin1',
       oe='latin1')
Traceback (most recent call last):
  File "<pyshell#22>", line 10, in ?
    oe='latin1')
  File "C:\Python22\SOAPpy097\SOAP.py", line 3603, in __r_call
    self.__hd, self.__ma)
  File "C:\Python22\SOAPpy097\SOAP.py", line 3532, in __call
    raise p
faultType: <Fault SOAP-ENV:Client: No Deserializer found to deserialize a
'http://www.w3.org/1999/XMLSchema:str' using encoding style
'http://schemas.xmlsoap.org/soap/encoding/'.>

So I went and got pyGoogle, built and installed, and ran the following:

>>> import google
>>> google.LICENSE_KEY = myLicenceKey
>>> google.doGoogleSearch("Python SOAP")

and got the exact same error message. Here I am stuck!

Dominic

--> Nobody knows the trouble you've seen / walking from your desk to the
staff canteen <--
homepage: http://www.geocities.com/domfox




From shalehperry@attbi.com  Fri Jul  5 22:46:39 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 05 Jul 2002 14:46:39 -0700 (PDT)
Subject: [Tutor] simple problem
In-Reply-To: <20020705212250.A455A6D9D7@www.fastmail.fm>
Message-ID: <XFMail.20020705144639.shalehperry@attbi.com>

On 05-Jul-2002 Kyle Babich wrote:
> I know this is simple, but I can find the answer in the documentation
> (although I guess it has to be there somewhere).
> Please bear with me because if you've read any of my messages you know
> I'm a complete newbie to python.
> 
> I know how to do something like:
> myname = "Kyle"
> print "Hello, my name is", myname
> 
> But how would I call up the myname variable in the middle of the print
> command?
> (Ie. print "Hello, #myname variable here# where do you live?"
> ---

myname = 'Sean'
person = 'Kyle'

a) print "Hello, " + person + " my name is " + myname

b) print "Hello, %s my name is %s" % (person, myname)


c) print "Hello, ", person, " my name is ", myname

I tend to prefer b, many people use a.  C is kind of frowned on.



From dman@dman.ddts.net  Fri Jul  5 23:37:36 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Fri, 5 Jul 2002 17:37:36 -0500
Subject: [Tutor] Re: simple problem
In-Reply-To: <XFMail.20020705144639.shalehperry@attbi.com>
References: <20020705212250.A455A6D9D7@www.fastmail.fm> <XFMail.20020705144639.shalehperry@attbi.com>
Message-ID: <20020705223736.GA17213@dman.ddts.net>

--qMm9M+Fa2AknHoGS
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Jul 05, 2002 at 02:46:39PM -0700, Sean 'Shaleh' Perry wrote:
| On 05-Jul-2002 Kyle Babich wrote:

| > I know how to do something like:
| > myname =3D "Kyle"
| > print "Hello, my name is", myname
| >=20
| > But how would I call up the myname variable in the middle of the print
| > command?
| > (Ie. print "Hello, #myname variable here# where do you live?"
| > ---
|=20
| myname =3D 'Sean'
| person =3D 'Kyle'
|=20
| a) print "Hello, " + person + " my name is " + myname
|=20
| b) print "Hello, %s my name is %s" % (person, myname)
|=20
|=20
| c) print "Hello, ", person, " my name is ", myname
|=20
| I tend to prefer b, many people use a.  C is kind of frowned on.

I tend to use b as well, but sometimes c while I'm debugging (just
'cause it's easy to write and I'll delete the code as soon as I've
fixed it).  Both a and b will print exactly what you wrote (with an
extra newline at the end).  c will add a space in between each
section.  That is by design, just be aware of it.

-D

--=20

A perverse man stirs up dissension,
and a gossip separates close friends.
        Proverbs 16:28
=20
http://dman.ddts.net/~dman/


--qMm9M+Fa2AknHoGS
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0mH7AACgkQO8l8XBKTpRRxcQCeOFb5wXVO0183FhvUEgDpyLwc
R1cAnA3bHJKptPkKwi7ZKHcHmzew8QEo
=Meka
-----END PGP SIGNATURE-----

--qMm9M+Fa2AknHoGS--



From jeff@ccvcorp.com  Sat Jul  6 02:56:00 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri, 05 Jul 2002 18:56:00 -0700
Subject: [Tutor] Re: simple problem
References: <20020705212250.A455A6D9D7@www.fastmail.fm> <XFMail.20020705144639.shalehperry@attbi.com> <20020705223736.GA17213@dman.ddts.net>
Message-ID: <3D264E30.B706FCAD@ccvcorp.com>


Derrick 'dman' Hudson wrote:

> | myname = 'Sean'
> | person = 'Kyle'
> |
> | a) print "Hello, " + person + " my name is " + myname
> |
> | b) print "Hello, %s my name is %s" % (person, myname)
>
>   Both a and b will print exactly what you wrote (with an
> extra newline at the end).

Be aware, though, that if you're doing *lots* of this (like, for instance,
adding numerous strings inside a tight loop or something), a is much less
efficient.  Each time you add a string, the interpreter creates a new string
object and copies the contents of the existing strings there.  In this
particular example, that's three temporary string objects, but if you're
building up a long string out of numerous variables, it could be a *lot*
more.  On the other hand, method b will only create a single string object, no
matter how many different variables you insert.  Also, b will let you do a lot
more specific alignment, formatting of numbers, etc.   There's really nothing
to recommend a as being better than b, either, so learn those string
formatting codes!  :)

Jeff Shannon
Technician/Programmer
Credit International





> c will add a space in between each
> section.  That is by design, just be aware of it.
>
> -D
>
> --
>
> A perverse man stirs up dissension,
> and a gossip separates close friends.
>         Proverbs 16:28
>
> http://dman.ddts.net/~dman/
>
>   ----------------------------------------------------------------------
>    Part 1.2Type: application/pgp-signature




From dyoo@hkn.eecs.berkeley.edu  Sat Jul  6 06:02:08 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 5 Jul 2002 22:02:08 -0700 (PDT)
Subject: [Tutor] Re: SOAP
In-Reply-To: <002301c2246c$b95ad1c0$4ac10550@tinypc>
Message-ID: <Pine.LNX.4.44.0207052142250.3853-100000@hkn.eecs.berkeley.edu>

Hi Dominic,

Hmmm.  I'm reading more about this SOAP stuff, and I'm somewhat unhappy
about it; it feels so scattered all over the place.


> So I went and got pyGoogle, built and installed, and ran the following:
>
> >>> import google
> >>> google.LICENSE_KEY = myLicenceKey
> >>> google.doGoogleSearch("Python SOAP")
>
> and got the exact same error message. Here I am stuck!


I haven't been able to duplicate the error yet.  *sigh* However, I have
been able to get it to work.  Here's what it looks on my machine:

###
>>> import google
>>> google.setLicense(license_key)
>>> search = google.doGoogleSearch('final fantasy tactics')
>>> for result in search.results[:10]:
...     print result.title, result.snippet
...
<b>Final</b> <b>Fantasy</b> Classes Quiz Which <b>Final</b> <b>Fantasy</b>
Class Should You Be? 1. Gender? Male. Female Does it matter?<br> 2. Is
your main strength in magic? Of course! Magic is my life! <b>...</b>
[lots and lots of output cut]
###


I get the feeling that the error you're running into may be some conflict
between the modified SOAP.py library that's used in pygoogle, as opposed
to the original SOAP.py library if you've installed it.  If so, remove the
old version of SOAP.py in your "site-packages" directory first, and then
try again.


Talk to you later!




From asis@graffiti.net  Sat Jul  6 14:17:09 2002
From: asis@graffiti.net (Ashish)
Date: Sat, 06 Jul 2002 19:02:09 +0545
Subject: [Tutor] dynamic proxy in python oop
Message-ID: <3D26EDD5.1070708@graffiti.net>

hi just a question on python oop!

i want to make a proxy class that will call the function in another 
class when its functions are called.

proxyObject.doSomething() should call realObject.doSomething()

I don't want to define doSomething() in proxy class as i want to be able 
to change real class as i want and i am not sure about the functions 
that real class will have till runtime.

one option is to have a call() funciton in proxy and do,

proxyObject.call(somefunc, params) to call realObject.somefunc(params)

but i would rather do proxyObject.somefunc(parmas) and get it to call 
realObject.somefunc(params)

is it possible in python? if yes, how do i do it?

ashish




From asis@graffiti.net  Sat Jul  6 16:15:14 2002
From: asis@graffiti.net (Ashish)
Date: Sat, 06 Jul 2002 21:00:14 +0545
Subject: [Tutor] solution to dynamic proxy in python
Message-ID: <3D270982.2070007@graffiti.net>

well, i think i have my answer. i saw the special function __getattr__
but did not think it would work for functions too.

anyway, as i was scanning through thinking in python by bruce eckel i
found an implementation of dynamic proxy. cool!

i am really looking forward to thinking in python. i think it will be
one of the coolest python book.


anyway to all who want to see an example:

class RealClass:
      def func1(self):
          print 'func1@RealClass'

      def func2(self, arg):
          print 'func2@RealClass with arg:', arg


class Proxy:
      def __init__(self):
          self.__real = RealClass

      def __getattr__(self, name):
          return getattr(self.__real, name)



ashish





From dominic.fox" <dominic.fox@ntlworld.com  Sat Jul  6 17:00:11 2002
From: dominic.fox" <dominic.fox@ntlworld.com (dominic.fox)
Date: Sat, 6 Jul 2002 17:00:11 +0100
Subject: [Tutor] Re: SOAP
References: <20020705160004.13405.23560.Mailman@mail.python.org>
Message-ID: <002901c22506$35e7a440$4ac10550@tinypc>

OK, now I have it working (thanks to Danny). The trouble was indeed with
SOAP.py 0.97, which is apparently incompatible with Python 2.2.1. I
installed the version included with pyGoogle and everything went swimmingly.

Now I thought it might be useful to delve a little beneath the surface of
pyGoogle's helpful proxy interface, just for the sake of understanding SOAP
a little better. What seems to be going on underneath the hood is that
SOAP.py is serialising Python data types into SOAP-conformant XML and back
again, returning the deserialised results (in this case the Google search
results) as a SOAP.structType object which pyGoogle then parses and formats
in a number of helpful ways. Here's what I tried:

>>> myGoogle = SOAP.SOAPProxy(
 "http://api.google.com/search/beta2",
 namespace="urn:GoogleSearch")

>>> retval = myGoogle.doGoogleSearch(myLicenceKey, "SOAP", 0, 10,
SOAP.booleanType(0), "", SOAP.booleanType(1), "", "latin1", "latin1")

Note that you have to convert Python's 1s and 0s into SOAP.booleanType
objects in order for them to be serialized properly.

>>> retval
<SOAP.structType return at 23747008>

>>> retval._asdict
{u'searchTips': '', u'endIndex': 10, u'searchQuery': 'SOAP',
u'searchComments': '', u'resultElements': [<SOAP.structType item at
23756992>, <SOAP.structType item at 23633424>, <SOAP.structType item at
23823584>, <SOAP.structType item at 23832816>, <SOAP.structType item at
23769744>, <SOAP.structType item at 23901872>, <SOAP.structType item at
23913936>, <SOAP.structType item at 23934128>, <SOAP.structType item at
23932752>, <SOAP.structType item at 23921056>], u'directoryCategories':
[<SOAP.structType item at 23776880>], u'estimatedTotalResultsCount':
3690000, u'estimateIsExact': 0, u'startIndex': 1, u'documentFiltering': 0,
u'searchTime': 0.068235000000000004}

- finally, borrowing from pyGoogle:

>>> results = [node._asdict for node in retval.resultElements]

which breaks the sub-structs inside the struct-as-dictionary into
structs-as-dictionaries which contain the actual search results.

It looks as if SOAP is good for returning rather larger and more complex
records or data structures than XML-RPC can handle, and also for specifying
and validating those structures using XML Schemas. The question has to be
whether (or when and where) the overheads involved are worth it. Obviously
once you've got a neat little library of proxies for the API you want to use
(like pyGoogle), this isn't so much of an issue; but that might mean having
a library per SOAP service, whereas xmlrpclib gives you a fairly
transparently Pythonic way of plugging into *anything*...

Dominic




From dyoo@hkn.eecs.berkeley.edu  Sat Jul  6 19:34:29 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 6 Jul 2002 11:34:29 -0700 (PDT)
Subject: [Tutor] dynamic proxy in python oop
In-Reply-To: <3D26EDD5.1070708@graffiti.net>
Message-ID: <Pine.LNX.4.44.0207061120190.14624-100000@hkn.eecs.berkeley.edu>


On Sat, 6 Jul 2002, Ashish wrote:

> hi just a question on python oop!
>
> i want to make a proxy class that will call the function in another
> class when its functions are called.
>
> proxyObject.doSomething() should call realObject.doSomething()
>
> I don't want to define doSomething() in proxy class as i want to be able
> to change real class as i want and i am not sure about the functions
> that real class will have till runtime.

Yes, this is possible using Python.  In the expression:

    proxyObject.doSomething()

Python actually does at least two things when it sees this expression: it
looks up the 'doSomething' attribute on our proxyObject, because even
methods are attributes in Python.  Only after this, after grabbing the
method out of the object, can we call it.


We can modify the attribute lookup of any class by writing a special
method called '__getattr__'.  Here's an example:

###
class ProxyClass:
    def __init__(self, real_object):
        self.real_object = real_object

    def __getattr__(self, attribute):
	return getattr(self.real_object, attribute)
###

This ProxyClass says that any attribute lookup on a ProxyClass will
actually delegate off to the real_object.

Here's a concrete example of how this might work:

###
>>> class Person:
...     def sayHello(self):
...         print "Hello!"
...     def wipe(self):
...         print "Your face is already clean"
...
>>> some_person = Person()
>>> some_person.sayHello()
Hello!
>>> proxied_person = ProxyClass(some_person)
>>> proxied_person.sayHello()
Hello!
>>> proxied_person.wipe()
Your face is already clean
>>> some_person.sayHello
<bound method Person.sayHello of <__main__.Person instance at 0x8150b14>>
>>> proxied_person.sayHello
<bound method Person.sayHello of <__main__.Person instance at 0x8150b14>>
>>> proxied_person.jump
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 5, in __getattr__
AttributeError: Person instance has no attribute 'jump'
###


Alex Martelli wrote a really cool post about an alternative way of making
one class instance look like another one:

    http://groups.google.com/groups?selm=8ubclp01s4t%40news1.newsguy.com

which I think you might enjoy.



Hope this helps!




From mike@daboyz.org  Sat Jul  6 22:32:13 2002
From: mike@daboyz.org (Mike Barrett)
Date: Sat, 6 Jul 2002 14:32:13 -0700
Subject: [Tutor] HTML Templates
Message-ID: <20020706213212.GA484@daboyz.org>

Anyone got a favorite HTML template module that they use?  I'm looking to 
develop a dynamic website, and I thought I'd see what others were using with 
python.  I looked at Zope, but it's not quite what I'm looking for.  I'd 
rather just write CGI's.  Anyways, thanks for your help.
-- 
     ________________________________________________________________________
                Mike Barrett | "I used to read, now I go to raves."
             mike@daboyz.org | -- Random MUNI Rider, speaking
              www.daboyz.org |    to my friend Allison.
     ------------------------+-----------------------------------------------



From Kyle Babich" <kb@kb5.org  Sun Jul  7 00:00:52 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Sat, 6 Jul 2002 23:00:52 +0000
Subject: [Tutor] alternative to time.sleep()
Message-ID: <20020706230052.B6B0D6D9CF@www.fastmail.fm>

I'm looking for an alternative to time.sleep() that will visually
countdown/countup the sleep time and can be paused and resumed at any
point.  Any ideas?

Thanks
--
Kyle



From tbrauch@mindless.com  Sun Jul  7 07:16:03 2002
From: tbrauch@mindless.com (Timothy M. Brauch)
Date: Sun, 7 Jul 2002 02:16:03 -0400
Subject: [Tutor] Class attributes
Message-ID: <000601c2257d$ce1f6960$9c21840a@tmbrau00>

I have read over the Reference Manual, but I am not sure if I understand
correctly.  Here is a short version of what I want.

Let's assume I have a class BigClass, and it has attributes such as
BigClass.a & BigClass.b

Below is what I would like for an interactive session (This is just made up
and not actual results)

IMAGINARY Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on
win32
IMAGINARY Type "copyright", "credits" or "license" for more information.
IMAGINARY IDLE Fork 0.8 -- press F1 for help
>>> c = BigClass()
>>> c.a = 'First'
>>> c.b = 'Second'
>>> print c
['First', 'Second']

I thought using __str__ inside BigClass would work, but appearently I was
wrong.  Is it possible to do what I want?

 - Tim

P.S. Is there a link to a page that describes all the __command__ I can add
to a class.  I just learned about __slots__ this past week, what else is
there?




From mikalzet@libero.it  Sat Jul  6 23:39:39 2002
From: mikalzet@libero.it (mikalzet@libero.it)
Date: Sun, 7 Jul 2002 00:39:39 +0200 (CEST)
Subject: [Tutor] Shifts - first attempt at a GUI
In-Reply-To: <20020703214502.GE18632@dman.ddts.net>
Message-ID: <Pine.LNX.4.44.0207070012280.3441-100000@macchinetta.miadimora>

Well folks,

after quite a while away from the snake I've started fooling with it 
again, aiming at making (in time) a program which will earn me the 
lifelong gratitude of thousands of ER doctors out there besides getting 
things easier for me ...

This is my first shot at it, must say the Pmw are very interesting.
Under the signature you will find the code, comments welcome.
A few questions come to my mind ... I'm blurred by the hour of course
...

1) I see my final application having a button which, if pressed, creates 
the CreateScheduleTemplate window, would that be something like:

class MainApp:
	foo
	self.CreateSchema = Button(foo, ... , command = 
CreateScheduleTemplate() )
?

2) This way of doing it I have to insert shifts in the dictionary one by 
one; there should be a way of defining shifts for weekdays, saturdays and 
sundays and then automatically creating a dictionary entry for each single 
shift, any hints ? 

The idea of using a dictionary like this is that with a key
( e.g. surgical 06/07/2002 ) I obtain a list containing date and time of 
beginning and end of shift; this list can easily be enlarged by adding the 
name of the doctor who will cover it and become the data input of the 
final schedule printing function; the doctor to be added will be selected 
from a list of doctors which in some way will have to take into account a 
series of options (doc A doesn't work nights, B works parttime, C needs a 
day off for a congress, E has flower-arrangement classes on tuesday 
afternoons and so would rather not work then but will if really 
necessary and so forth). 

As I see it the dictionary will contain up to 15 keys per day, so a month 
of shifts requires 450 dictionary entries ... large enough to warrant a 
data base ? Or could pickling the data be enough ?

__
Michele Alzetta


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

#!/usr/bin/python

# Created in 2002/2003 ... (hopefully) 
# Michele Alzetta, mikalzet@libero.it
# an attempt at making a GUI program which will allow to create complex
# scheduling schemes for ER doctors - something like EPSCHED I imagine might be 
# (although I've never used it as it is far too expensive)

from Tkinter import *
import time
import Pmw

class CreateScheduleTemplate:
  
# Create the GUI interface which will eventually allow user to create the
# template for the shifts which must be covered in a schedule. 
# The shift template is being created as a dictionary, although of course it 
# will end up being pickled or saved in a file or in a database eventually

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

# Create an entry widget to allow giving each shift a name

        self._schematurni = {}
        self._InserisciNome = Pmw.EntryField(master,
                labelpos = 'w',
                label_text = 'Inserisci un nome univoco per questo turno:',
                validate = None,
                command = self.retrieve_schema)
        self._InserisciNome.pack()

# Create a date counter widget to select the shift date
        
        self._date = Pmw.Counter(master,
                labelpos = 'w',
                label_text = 'Date (4-digit year):',
                entryfield_value =
                        time.strftime('%d/%m/%Y', time.localtime()),
                entryfield_command = self.retrieve_schema,
                entryfield_validate = {'validator' : 'date', 'format' : 'dmy'},
                datatype = {'counter' : 'date', 'format' : 'dmy', 'yyyy' : 1})
        self._date.pack()

# Create two time counter widgets to select begin and end time for shift

        self._timebegin = Pmw.Counter(master,
                labelpos = 'w',
                label_text = 'Ora inizio:',
                entryfield_value =
                        time.strftime('%H:%M:%S', time.localtime()),
                entryfield_validate = {'validator' : 'time',
                        'min' : '00:00:00', 'max' : '23:59:59',
                        'minstrict' : 0, 'maxstrict' : 0},
                entryfield_command = self.retrieve_schema,
                datatype = {'counter' : 'time', 'time24' : 1},
                increment=60*60)
        self._timebegin.pack()

        self._timeend = Pmw.Counter(master,
                labelpos = 'w',
                label_text = 'Ora fine:',
                entryfield_value =
                        time.strftime('%H:%M:%S', time.localtime()),
                entryfield_validate = {'validator' : 'time',
                        'min' : '00:00:00', 'max' : '23:59:59',
                        'minstrict' : 0, 'maxstrict' : 0},
                entryfield_command = self.retrieve_schema,
                datatype = {'counter' : 'time', 'time24' : 1},
                increment=60*60)
        self._timeend.pack()

# Here I create two buttons: one to exit the program, one to insert the 
# selected data into the dictionary
# I also print the dictionary (for debugging purposes)

        self.get_schema = Button(frame, text="Inserisci", fg="red", command=self.retrieve_schema)
        self.get_schema.pack(side=LEFT)

        self.close_box = Button(frame, text="Quit", command='exit')
        self.close_box.pack(side=LEFT)

              
    def retrieve_schema(self):
        oraturno = [self._date.get(), self._timebegin.get(), self._timeend.get()]
        nometurno = self._InserisciNome.get() + ' ' + self._date.get()
        self._schematurni[nometurno] = oraturno
        print self._schematurni

if __name__ == '__main__':

    root = Tk()
    Pmw.initialise(root)
    app = CreateScheduleTemplate(root)
    root.mainloop()





From shalehperry@attbi.com  Sun Jul  7 08:03:43 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun, 07 Jul 2002 00:03:43 -0700 (PDT)
Subject: [Tutor] Class attributes
In-Reply-To: <000601c2257d$ce1f6960$9c21840a@tmbrau00>
Message-ID: <XFMail.20020707000343.shalehperry@attbi.com>

On 07-Jul-2002 Timothy M. Brauch wrote:
> I have read over the Reference Manual, but I am not sure if I understand
> correctly.  Here is a short version of what I want.
> 
> Let's assume I have a class BigClass, and it has attributes such as
> BigClass.a & BigClass.b
> 
> Below is what I would like for an interactive session (This is just made up
> and not actual results)
> 
> IMAGINARY Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on
> win32
> IMAGINARY Type "copyright", "credits" or "license" for more information.
> IMAGINARY IDLE Fork 0.8 -- press F1 for help
>>>> c = BigClass()
>>>> c.a = 'First'
>>>> c.b = 'Second'
>>>> print c
> ['First', 'Second']
> 
> I thought using __str__ inside BigClass would work, but appearently I was
> wrong.  Is it possible to do what I want?
> 
>  - Tim
> 
> P.S. Is there a link to a page that describes all the __command__ I can add
> to a class.  I just learned about __slots__ this past week, what else is
> there?
> 

>>> class BigClass:
...   def __str__(self):
...     return '[%s, %s]' % (self.a, self.b)
... 
>>> b = BigClass()
>>> b.a = 'Sean'
>>> b.b = 'Perry'
>>> print b
[Sean, Perry]

look at the library and language reference they are all defined there.

This is from 2.1's language reference "Function, Method, and Variable Index", so
__slots__ is not there:

* __add__:                               Emulating numeric types.
* __call__:                              Emulating callable objects.
* __cmp__:                               Basic customization.
* __coerce__:                            Emulating numeric types.
* __complex__:                           Emulating numeric types.
* __contains__:                          Emulating container types.
* __del__:                               Basic customization.
* __delattr__:                           Customizing attribute access.
* __delitem__:                           Emulating container types.
* __delslice__:                          Additional methods for emulation of se\
quence types.
* __div__:                               Emulating numeric types.
* __getattr__:                           Customizing attribute access.
* __getitem__:                           Emulating container types.
* __getslice__:                          Additional methods for emulation of se\
quence types.
* __hash__:                              Basic customization.
* __iadd__:                              Emulating numeric types.
* __import__:                            import statement.
* __init__:                              Basic customization.
* __iter__:                              Emulating container types.
* __len__:                               Emulating container types.
* __lt__:                                Basic customization.
* __neg__:                               Emulating numeric types.
* __nonzero__:                           Basic customization.
* __oct__:                               Emulating numeric types.
* __radd__:                              Emulating numeric types.
* __rcmp__:                              Basic customization.
* __repr__:                              Basic customization.
* __setattr__:                           Customizing attribute access.
* __setitem__:                           Emulating container types.
* __setslice__:                          Additional methods for emulation of se\
quence types.
* __str__:                               Basic customization.




From ak@silmarill.org  Sun Jul  7 08:34:13 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Sun, 7 Jul 2002 03:34:13 -0400
Subject: [Tutor] alternative to time.sleep()
In-Reply-To: <20020706230052.B6B0D6D9CF@www.fastmail.fm>
References: <20020706230052.B6B0D6D9CF@www.fastmail.fm>
Message-ID: <20020707073413.GA21699@ak.silmarill.org>

On Sat, Jul 06, 2002 at 11:00:52PM +0000, Kyle Babich wrote:
> I'm looking for an alternative to time.sleep() that will visually
> countdown/countup the sleep time and can be paused and resumed at any
> point.  Any ideas?
> 
> Thanks
> --
> Kyle
>
You have to have a separate thread that prints time left, sleeps one
sec, prints time left, etc. And main thread will wait for input and if
you hit 'p'enter it'll set second_thread.paused variable.

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

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From paulsid@shaw.ca  Sun Jul  7 08:59:40 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Sun, 07 Jul 2002 01:59:40 -0600
Subject: [Tutor] Class attributes
References: <000601c2257d$ce1f6960$9c21840a@tmbrau00>
Message-ID: <3D27F4EC.A1E8422@shaw.ca>

"Timothy M. Brauch" wrote:

> Below is what I would like for an interactive session (This is just made up
> and not actual results)
> 
> IMAGINARY Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on
> win32
> IMAGINARY Type "copyright", "credits" or "license" for more information.
> IMAGINARY IDLE Fork 0.8 -- press F1 for help
> >>> c = BigClass()
> >>> c.a = 'First'
> >>> c.b = 'Second'
> >>> print c
> ['First', 'Second']
> 
> I thought using __str__ inside BigClass would work, but appearently I was
> wrong.  Is it possible to do what I want?

Yes, in several different ways.  Here are two:

1) Exploit the fact that classes hold their attributes in a dictionary:

class C:
    def __repr__(self):
        return repr(self.__dict__.values())

>>> c = C()
>>> c.a = "First"
>>> c.b = "Second"
>>> print c
['First', 'Second']

Note that the order of elements is undefined because it comes from a
dictionary.

2) Maintain a list yourself.  This is a rudimentary but you can build on
it:

class B:
    def __init__(self):
        self._mainlist = []
    def __setattr__(self, name, value):
        if name != "_mainlist":
            self._mainlist.append(value)
        self.__dict__[name] = value
    def __str__(self):
        return str(self._mainlist)
    def __repr__(self):
        return repr(self._mainlist)

>>> b = B()
>>> b.a = "First"
>>> b.b = "Second"
>>> print b
['First', 'Second']

Method #1 is obviously way easier but method #2 gives you more control
if you need it.

Fun stuff!  :-)

> P.S. Is there a link to a page that describes all the __command__ I can add
> to a class.  I just learned about __slots__ this past week, what else is
> there?

Go to the Python Language Reference and click Index.  Underscore is the
first heading and all of the __xxx__'s are listed there, with links.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From Kyle Babich" <kb@kb5.org  Sun Jul  7 11:54:32 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Sun, 7 Jul 2002 10:54:32 +0000
Subject: [Tutor] please help debug
Message-ID: <20020707105432.E43856DA17@www.fastmail.fm>

I'm writing a program that tracks each hour spent on the computer for
my parents but I can't get hour() to execute, and time.sleep() won't
sleep.  Can someone please help me fix these problems?

Here is what I wrote so far:

#! C:\Python22\python.exe

import time
time = time.strftime( "%I:%M:%S %Z", time.localtime(time.time()) )

def hour():
	print "The current time is %(time)s" % vars()
	begin = raw_input( "Begin hour?  (Y/N):  " )
	
	if begin == "Y":
		time.sleep(3600)
	elif begin == "y":
		time.sleep(3600)
	elif begin == "N":
		excuse = raw_input( "Why not?  " )
	elif begin == "n":
		excuse1 = raw_input( "Why not?  " )
	else:
		begin1 = raw_input( "Begin hour?  (Y/N):  " )
		if begin1 == "Y":
			time.sleep(3600)
		elif begin1 == "y":
			time.sleep(3600)
		elif begin1 == "N":
			excuse2 = raw_input( "Why not?  " )
		elif begin1 == "n":
			excuse3 = raw_input( "Why not?  " )
		else:
			print "FAILED"

username = raw_input( "Please type your name:  " )

if username == "Kyle":
	print
	hour()
elif username == "Jason":
	print
	hour()
elif username == "Chelsea":
	print
	hour()
elif username == "John":
	print
	hour()
elif username == "Cheryl":
	print
	hour()
else:
	print "FAILED"



Also, if it makes a difference, I'm writing it to be used on Win98 with
Python 2.2 installed.
--
Kyle



From lumbricus@gmx.net  Sun Jul  7 15:07:52 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Sun, 7 Jul 2002 16:07:52 +0200 (MEST)
Subject: [Tutor] alternative to time.sleep()
References: <20020706230052.B6B0D6D9CF@www.fastmail.fm>
Message-ID: <15624.1026050872@www33.gmx.net>

> I'm looking for an alternative to time.sleep() that will visually
> countdown/countup the sleep time and can be paused and resumed at any

>From the OSF1 manpage of sleep(3):

" The suspension time may be longer than
requested due to the scheduling of other activity by the system.
In a multi-threaded environment, the sleep() function is redefined so that
only the calling thread is suspended."

These may cause problems.

> point.  Any ideas?
> 
> Thanks
> --
> Kyle

HTH, HAND
J"o!

-- 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net




From emil@lysator.liu.se  Sun Jul  7 15:56:50 2002
From: emil@lysator.liu.se (Emil Styrke)
Date: 07 Jul 2002 16:56:50 +0200
Subject: [Tutor] please help debug
In-Reply-To: <20020707105432.E43856DA17@www.fastmail.fm>
References: <20020707105432.E43856DA17@www.fastmail.fm>
Message-ID: <87elef37t9.fsf@i110.ryd.student.liu.se>

"Kyle Babich" <kb@kb5.org> writes:

> I'm writing a program that tracks each hour spent on the computer for
> my parents but I can't get hour() to execute, and time.sleep() won't
> sleep.  Can someone please help me fix these problems?
> 
> Here is what I wrote so far:
> 
> #! C:\Python22\python.exe
> 
> import time
> time = time.strftime( "%I:%M:%S %Z", time.localtime(time.time()) )

You should use another name for this variable, it collides with the
time module.


> def hour():
> 	print "The current time is %(time)s" % vars()

This fails because time doesn't exist in vars(), it only contains
local variables.  Try using globals() instead.  Better yet, move the
global assignment into the function.


        /Emil




From ajs@ix.netcom.com  Sun Jul  7 18:30:21 2002
From: ajs@ix.netcom.com (Arthur Siegel)
Date: Sun, 7 Jul 2002 13:30:21 -0400
Subject: [Tutor] now new style properties and inheritance
Message-ID: <000901c225db$fc85fc20$0334fea9@carol>

Thought I'd share more of my new style class 
explorations - and ask for any insights I may 
be missing.

An unexpected (to me) twist in the use of properties.
with inheritance. It seems that the property declaration
must be redeclared when a method in overridden a sub-class.

>>> class A(object):
            def get_prop(self):
                  print "A's property"
            prop= property(get_prop)
>>> class B(A):
            def get_prop(self):
                 print "B's property"
>>> a=A()
>>> a.prop
A's property
>>> b=B()
>>> b.prop
A's property

But -

>>> class B(A):
             def get_prop(self):
                   print "B's property"
              prop = property(get_prop)
>>> a=A()
>>> a.prop
A's property
>>> b=B()
>>> b.prop
B's property

New style classes, I am finding, are indeed newer than
I had imagined.

Am I missing something, for a change.

Art




From ak@silmarill.org  Sun Jul  7 20:05:29 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Sun, 7 Jul 2002 15:05:29 -0400
Subject: [Tutor] please help debug
In-Reply-To: <20020707105432.E43856DA17@www.fastmail.fm>
References: <20020707105432.E43856DA17@www.fastmail.fm>
Message-ID: <20020707190529.GA421@ak.silmarill.org>

On Sun, Jul 07, 2002 at 10:54:32AM +0000, Kyle Babich wrote:
> I'm writing a program that tracks each hour spent on the computer for
> my parents but I can't get hour() to execute, and time.sleep() won't
> sleep.  Can someone please help me fix these problems?
> 
> Here is what I wrote so far:
> 
> #! C:\Python22\python.exe
> 
> import time
> time = time.strftime( "%I:%M:%S %Z", time.localtime(time.time()) )
>
_time = ...
> 
> def hour():
> 	print "The current time is %(time)s" % vars()
 print "The current time is", _time
> 	begin = raw_input( "Begin hour?  (Y/N):  " )
> 	
> 	if begin == "Y":
> 		time.sleep(3600)
> 	elif begin == "y":
> 		time.sleep(3600)
> 	elif begin == "N":
> 		excuse = raw_input( "Why not?  " )
> 	elif begin == "n":
> 		excuse1 = raw_input( "Why not?  " )
> 	else:
> 		begin1 = raw_input( "Begin hour?  (Y/N):  " )
> 		if begin1 == "Y":
> 			time.sleep(3600)
> 		elif begin1 == "y":
> 			time.sleep(3600)
> 		elif begin1 == "N":
> 			excuse2 = raw_input( "Why not?  " )
> 		elif begin1 == "n":
> 			excuse3 = raw_input( "Why not?  " )
> 		else:
> 			print "FAILED"
# there's something wrong here, if you want to keep asking until you
# get yes or no, you can use while 1:

while 1:
    answer = raw_input("Begin hour? [Y/N] ")
    if answer in "Yy":
	time.sleep(1*60*60) # one hour
	break
    elif answer in "Nn":
	break

# this will keep asking until it gets yes or no answer..
# 'in' tests if a given item is in given collection. e.g. letter in
# string, string in list of strings, etc.
> 
> username = raw_input( "Please type your name:  " )
> 
> if username == "Kyle":
> 	print
> 	hour()
> elif username == "Jason":
> 	print
> 	hour()
> elif username == "Chelsea":
> 	print
> 	hour()
> elif username == "John":
> 	print
> 	hour()
> elif username == "Cheryl":
> 	print
> 	hour()
# this one liner will replace the above lines.. and it'll work case
# insensitively
if username.lower() in "kyle jason chelsea john cheryl".split():
    print
    hour()
> else:
> 	print "FAILED"
> 
> 
> 
> Also, if it makes a difference, I'm writing it to be used on Win98 with
> Python 2.2 installed.
> --
> Kyle
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From Kyle Babich" <kb@kb5.org  Sun Jul  7 20:29:44 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Sun, 7 Jul 2002 19:29:44 +0000
Subject: [Tutor] please help debug
Message-ID: <20020707192945.0413D6D9FF@www.fastmail.fm>

This is a multi-part message in MIME format.

--_----------=_102607018447490
Content-Disposition: inline
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset="ISO-8859-1"

My e-mail program deletes spaces for some reason.  I have attached a
copy.

On Sun, 7 Jul 2002 08:12:13 -0400, "Charles Mantha"
<charles_mantha@hotmail.com> said:
> Where are the intendations? after each (:) there should be an
> intendation...
> 
> Ok, well its kinda late here and I dont have much time to check the
> rest.
> But if I find something, ill tell ya.
> 
> 
> ----- Original Message -----
> From: "Kyle Babich" <kb@kb5.org>
> To: "tutor" <tutor@python.org>
> Sent: Sunday, July 07, 2002 6:54 AM
> Subject: [Tutor] please help debug
> 
> 
> > I'm writing a program that tracks each hour spent on the computer for
> > my parents but I can't get hour() to execute, and time.sleep() won't
> > sleep.  Can someone please help me fix these problems?
> >
> > Here is what I wrote so far:
> >
> > #! C:\Python22\python.exe
> >
> > import time
> > time = time.strftime( "%I:%M:%S %Z", time.localtime(time.time()) )
> >
> > def hour():
> > print "The current time is %(time)s" % vars()
> > begin = raw_input( "Begin hour?  (Y/N):  " )
> >
> > if begin == "Y":
> > time.sleep(3600)
> > elif begin == "y":
> > time.sleep(3600)
> > elif begin == "N":
> > excuse = raw_input( "Why not?  " )
> > elif begin == "n":
> > excuse1 = raw_input( "Why not?  " )
> > else:
> > begin1 = raw_input( "Begin hour?  (Y/N):  " )
> > if begin1 == "Y":
> > time.sleep(3600)
> > elif begin1 == "y":
> > time.sleep(3600)
> > elif begin1 == "N":
> > excuse2 = raw_input( "Why not?  " )
> > elif begin1 == "n":
> > excuse3 = raw_input( "Why not?  " )
> > else:
> > print "FAILED"
> >
> > username = raw_input( "Please type your name:  " )
> >
> > if username == "Kyle":
> > print
> > hour()
> > elif username == "Jason":
> > print
> > hour()
> > elif username == "Chelsea":
> > print
> > hour()
> > elif username == "John":
> > print
> > hour()
> > elif username == "Cheryl":
> > print
> > hour()
> > else:
> > print "FAILED"
> >
> >
> >
> > Also, if it makes a difference, I'm writing it to be used on Win98 with
> > Python 2.2 installed.
> > --
> > Kyle
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> 
> 
> 

--
Kyle
--_----------=_102607018447490
Content-Disposition: attachment; filename="time.py"
Content-Transfer-Encoding: base64
Content-Type: application/unknown; name="time.py"

IyEgQzpcUHl0aG9uMjJccHl0aG9uLmV4ZQ0KDQppbXBvcnQgdGltZQ0KdGlt
ZSA9IHRpbWUuc3RyZnRpbWUoICIlSTolTTolUyAlWiIsIHRpbWUubG9jYWx0
aW1lKHRpbWUudGltZSgpKSApDQoNCmRlZiBob3VyKCk6DQoJcHJpbnQgIlRo
ZSBjdXJyZW50IHRpbWUgaXMgJSh0aW1lKXMiICUgdmFycygpDQoJYmVnaW4g
PSByYXdfaW5wdXQoICJCZWdpbiBob3VyPyAgKFkvTik6ICAiICkNCgkNCglp
ZiBiZWdpbiA9PSAiWSI6DQoJCXRpbWUuc2xlZXAoMzYwMCkNCgllbGlmIGJl
Z2luID09ICJ5IjoNCgkJdGltZS5zbGVlcCgzNjAwKQ0KCWVsaWYgYmVnaW4g
PT0gIk4iOg0KCQlleGN1c2UgPSByYXdfaW5wdXQoICJXaHkgbm90PyAgIiAp
DQoJZWxpZiBiZWdpbiA9PSAibiI6DQoJCWV4Y3VzZTEgPSByYXdfaW5wdXQo
ICJXaHkgbm90PyAgIiApDQoJZWxzZToNCgkJYmVnaW4xID0gcmF3X2lucHV0
KCAiQmVnaW4gaG91cj8gIChZL04pOiAgIiApDQoJCWlmIGJlZ2luMSA9PSAi
WSI6DQoJCQl0aW1lLnNsZWVwKDM2MDApDQoJCWVsaWYgYmVnaW4xID09ICJ5
IjoNCgkJCXRpbWUuc2xlZXAoMzYwMCkNCgkJZWxpZiBiZWdpbjEgPT0gIk4i
Og0KCQkJZXhjdXNlMiA9IHJhd19pbnB1dCggIldoeSBub3Q/ICAiICkNCgkJ
ZWxpZiBiZWdpbjEgPT0gIm4iOg0KCQkJZXhjdXNlMyA9IHJhd19pbnB1dCgg
IldoeSBub3Q/ICAiICkNCgkJZWxzZToNCgkJCXByaW50ICJGQUlMRUQiDQoN
CnVzZXJuYW1lID0gcmF3X2lucHV0KCAiUGxlYXNlIHR5cGUgeW91ciBuYW1l
OiAgIiApDQoNCmlmIHVzZXJuYW1lID09ICJLeWxlIjoNCglwcmludA0KCWhv
dXIoKQ0KZWxpZiB1c2VybmFtZSA9PSAiSmFzb24iOg0KCXByaW50DQoJaG91
cigpDQplbGlmIHVzZXJuYW1lID09ICJDaGVsc2VhIjoNCglwcmludA0KCWhv
dXIoKQ0KZWxpZiB1c2VybmFtZSA9PSAiSm9obiI6DQoJcHJpbnQNCglob3Vy
KCkNCmVsaWYgdXNlcm5hbWUgPT0gIkNoZXJ5bCI6DQoJcHJpbnQNCglob3Vy
KCkNCmVsc2U6DQoJcHJpbnQgIkZBSUxFRCINCg==

--_----------=_102607018447490--




From ak@silmarill.org  Sun Jul  7 21:02:21 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Sun, 7 Jul 2002 16:02:21 -0400
Subject: [Tutor] please help debug
In-Reply-To: <20020707192945.0413D6D9FF@www.fastmail.fm>
References: <20020707192945.0413D6D9FF@www.fastmail.fm>
Message-ID: <20020707200221.GA878@ak.silmarill.org>

On Sun, Jul 07, 2002 at 07:29:44PM +0000, Kyle Babich wrote:
> My e-mail program deletes spaces for some reason.  I have attached a
> copy.
>
I did see spaces. I think some email clients (ms outlook?) don't show
tabs. So, try to convert tabs to spaces before mailiing a list post. In
vim this is done with :set expandtab

> 
> On Sun, 7 Jul 2002 08:12:13 -0400, "Charles Mantha"
> <charles_mantha@hotmail.com> said:
> > Where are the intendations? after each (:) there should be an
> > intendation...
> > 
> > Ok, well its kinda late here and I dont have much time to check the
> > rest.
> > But if I find something, ill tell ya.
> > 
> > 
> > ----- Original Message -----
> > From: "Kyle Babich" <kb@kb5.org>
> > To: "tutor" <tutor@python.org>
> > Sent: Sunday, July 07, 2002 6:54 AM
> > Subject: [Tutor] please help debug
> > 
> > 
> > > I'm writing a program that tracks each hour spent on the computer for
> > > my parents but I can't get hour() to execute, and time.sleep() won't
> > > sleep.  Can someone please help me fix these problems?
> > >
> > > Here is what I wrote so far:
> > >
> > > #! C:\Python22\python.exe
> > >
> > > import time
> > > time = time.strftime( "%I:%M:%S %Z", time.localtime(time.time()) )
> > >
> > > def hour():
> > > print "The current time is %(time)s" % vars()
> > > begin = raw_input( "Begin hour?  (Y/N):  " )
> > >
> > > if begin == "Y":
> > > time.sleep(3600)
> > > elif begin == "y":
> > > time.sleep(3600)
> > > elif begin == "N":
> > > excuse = raw_input( "Why not?  " )
> > > elif begin == "n":
> > > excuse1 = raw_input( "Why not?  " )
> > > else:
> > > begin1 = raw_input( "Begin hour?  (Y/N):  " )
> > > if begin1 == "Y":
> > > time.sleep(3600)
> > > elif begin1 == "y":
> > > time.sleep(3600)
> > > elif begin1 == "N":
> > > excuse2 = raw_input( "Why not?  " )
> > > elif begin1 == "n":
> > > excuse3 = raw_input( "Why not?  " )
> > > else:
> > > print "FAILED"
> > >
> > > username = raw_input( "Please type your name:  " )
> > >
> > > if username == "Kyle":
> > > print
> > > hour()
> > > elif username == "Jason":
> > > print
> > > hour()
> > > elif username == "Chelsea":
> > > print
> > > hour()
> > > elif username == "John":
> > > print
> > > hour()
> > > elif username == "Cheryl":
> > > print
> > > hour()
> > > else:
> > > print "FAILED"
> > >
> > >
> > >
> > > Also, if it makes a difference, I'm writing it to be used on Win98 with
> > > Python 2.2 installed.
> > > --
> > > Kyle
> > >
> > >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > 
> > 
> > 
> > 
> 
> --
> Kyle


-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From Kyle Babich" <kb@kb5.org  Sun Jul  7 21:04:07 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Sun, 7 Jul 2002 20:04:07 +0000
Subject: [Tutor] alternative to time.sleep()
Message-ID: <20020707200407.5A6726DA67@www.fastmail.fm>

Ok, that's definetly a downside but how do I suspend it at all?

On Sun, 7 Jul 2002 16:07:52 +0200 (MEST), lumbricus@gmx.net said:
> > I'm looking for an alternative to time.sleep() that will visually
> > countdown/countup the sleep time and can be paused and resumed at any
> 
> >From the OSF1 manpage of sleep(3):
> 
> " The suspension time may be longer than
> requested due to the scheduling of other activity by the system.
> In a multi-threaded environment, the sleep() function is redefined so
> that
> only the calling thread is suspended."
> 
> These may cause problems.
> 
> > point.  Any ideas?
> > 
> > Thanks
> > --
> > Kyle
> 
> HTH, HAND
> J"o!
> 
> -- 
> 
> -- 
> GMX - Die Kommunikationsplattform im Internet.
> http://www.gmx.net
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 

--
Kyle



From phthenry@earthlink.net  Sun Jul  7 21:11:12 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Sun, 7 Jul 2002 16:11:12 -0400
Subject: [Tutor] replacing something on last line
Message-ID: <20020707161112.D2438@localhost.localdomain>

For the life of me, I can't figure out how to change the last
instance of something in a file. For example, given:

text
text 
text
text Special Special

I want to replace just the last Special in the file

Thanks!

Paul

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From ak@silmarill.org  Sun Jul  7 21:32:46 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Sun, 7 Jul 2002 16:32:46 -0400
Subject: [Tutor] replacing something on last line
In-Reply-To: <20020707161112.D2438@localhost.localdomain>
References: <20020707161112.D2438@localhost.localdomain>
Message-ID: <20020707203246.GA1067@ak.silmarill.org>

On Sun, Jul 07, 2002 at 04:11:12PM -0400, Paul Tremblay wrote:
> For the life of me, I can't figure out how to change the last
> instance of something in a file. For example, given:
> 
> text
> text 
> text
> text Special Special
> 
> I want to replace just the last Special in the file
> 
> Thanks!
> 
> Paul
>
Reverse, change first, reverse again and write?

> 
> -- 
> 
> ************************
> *Paul Tremblay         *
> *phthenry@earthlink.net*
> ************************
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From glingl@aon.at  Sun Jul  7 21:32:29 2002
From: glingl@aon.at (Gregor Lingl)
Date: Sun, 7 Jul 2002 22:32:29 +0200
Subject: [Tutor] what is returned by dir(obj)?
References: <20020707161112.D2438@localhost.localdomain>
Message-ID: <000901c225f5$6a3aaa40$1615a8c0@mega>

Hi!
I'm still a newbie in looking behind the scene.

When playing around with VPython I encountered the
following:

>>> from visual import *
Visual-2002-06-14
>>> s=sphere() # beautiful white sphere displayed immediately
>>> s
<Primitive object at 0x01563D34>
>>> dir(s)
['__class__', 'axis', 'blue', 'color', 'constr',
 'display', 'frame', 'green', 'name', 'pos', 'radius', 
'red', 'rotate', 'up', 'visible', 'x', 'y', 'z']
>>> s.__methods__
['rotate']
>>> s.__dict__
{'__class__': <built-in method sphere of tuple object at 0x00A65590>}
>>> s.__members__
['axis', 'blue', 'color', 'display', 'frame', 'green', 
'pos', 'radius', 'red', 'up', 'visible', 'x', 'y', 'z']
>>> s.name
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in ?
    s.name
AttributeError: name
>>> 

So, what are 'name' and 'constr', which both do not appear
neither in s.__members__ nor in s.__dict__ nor in s.__methods,
in the list returned by dir(s)?

Or what is generally returned by dir() ?

Perhaps there is somebody who can explain this.

Thanks, Gregor






From glingl@aon.at  Sun Jul  7 21:45:39 2002
From: glingl@aon.at (Gregor Lingl)
Date: Sun, 7 Jul 2002 22:45:39 +0200
Subject: [Tutor] replacing something on last line
References: <20020707161112.D2438@localhost.localdomain>
Message-ID: <001b01c225f7$41221e20$1615a8c0@mega>

... or try to use this:

>>> s = """text
text 
text
text Special Special
"""
>>> last = s.rfind('Special')
>>> last
29
>>> print s[:last]+s[last:].replace('Special','General')
text
text 
text
text Special General

>>> 

Gregor





From kemal.taskin@pandora.be  Sun Jul  7 21:57:05 2002
From: kemal.taskin@pandora.be (Kemal Taskin)
Date: 07 Jul 2002 22:57:05 +0200
Subject: [Tutor] Newbie: game problem
Message-ID: <1026075426.1004.14.camel@D5777294.kabel.telenet.be>

Hi list
(my English is not perfect, so sorry for that)

I'm a newbie and I'm writing now a game called robots.  You're being
chased by robots.  They are armed, and if a robot manages to catch you
you're dead.  The robots are always moving towards you, even if there's
something in the way.

Now I'm trying to write the code used to move the player. I use the
numeric keypad of the keyboard to allow the player to move. To write
this game I use the Livewires package. ( see
www.livewires.org.uk/python)

This is my code for the moment:
------------------------------
#!/usr/bin/python
from livewires import *
begin_graphics()
allow_moveables()
def place_player():
	global player_x
	global player_y
	global player_shape
	player_x = random_between(0,63)
	player_y = random_between(0,47)
	player_shape = circle(10*player_x, 10*player_y, 5, filled=1)

def move_player():
	global player_x 
	global player_y
	keys = keys_pressed()
	if 'q' in keys:
		pass #later this will exit the game
	elif '1' in keys:
		move_to(player_shape, player_x - 10, player_y - 10)
		player_x = player_x
		player_y = player_y
		return
	elif '8' in keys:
		move_to(player_shape, player_x + 0, player_y + 10)
		player_x = player_x
		player_y = player_y
		return
	#and so on ....

place_player()
finished = 0
while not finished:
	move_player()

end_graphics()

-------------------------------
The problem is that I can only move the robot one time. I think that the
problem is in the function move_player()
Can somebody help me with this problem.

Thanks





From abli@freemail.hu  Sun Jul  7 23:38:52 2002
From: abli@freemail.hu (Abel Daniel)
Date: Mon, 8 Jul 2002 00:38:52 +0200
Subject: [Tutor] Newbie: game problem
In-Reply-To: <1026075426.1004.14.camel@D5777294.kabel.telenet.be>
References: <1026075426.1004.14.camel@D5777294.kabel.telenet.be>
Message-ID: <20020707223852.GA6717@hooloovoo>

On Sun, Jul 07, 2002 at 10:57:05PM +0200 Kemal Taskin (kemal.taskin@pandora.be) wrote:
> def move_player():
> 	global player_x 
> 	global player_y
> 	keys = keys_pressed()
> 	if 'q' in keys:
> 		pass #later this will exit the game
> 	elif '1' in keys:
> 		move_to(player_shape, player_x - 10, player_y - 10)
> 		player_x = player_x
> 		player_y = player_y
> 		return
> 	elif '8' in keys:
> 		move_to(player_shape, player_x + 0, player_y + 10)
> 		player_x = player_x
> 		player_y = player_y
> 		return
> 	#and so on ....
> 
> place_player()
> finished = 0
> while not finished:
> 	move_player()
> 
I think the problem is that you dont modify the global variables
player_x and player_y in move_player().
You would need something like this:

elif '1' in keys:
	player_x = player_x - 10
	player_y = player_y - 10
	move_to(player_shape, player_x, player_y)
	return

Also, i dont think the current layout of the code is good.
You basically use a structure like this:
while 1:
	key = keys_pressed() # i guess here you only get _one_ key
	if 'q' in key:
		# do something
	elif 'n' in key:
		# do something else
	..and so on...
The difference is that you break this structure into two functions,
which means that your move_player() function will be called all the
time. This will mean a lot of overhead because calling a function is a
constly think (i.e. it takes time). Of course premature optimalization
is the root of all evil, but in this case it looks like this is the only
place, where you will be using this function, so there is no reason to
do it this way.

Rename that function to some think like move_player_until_quit()
(so that you can see at a glance what it wants to do. currently it does
more than the name implies, it is more like
get_one_keypress_and_move_player() and not move_player() )
and have the while loop entirely in it.

abli
abli@freemail.hu
p.s. i didnt look at the livewire package, i assumed the functions do
what you used them for.
	




From sarmstrong13@mac.com  Mon Jul  8 00:08:12 2002
From: sarmstrong13@mac.com (SA)
Date: Sun, 07 Jul 2002 18:08:12 -0500
Subject: [Tutor] Simple Python Question.
Message-ID: <B94E340C.900D%sarmstrong13@mac.com>

What is the best way to look up all the python modules present in Python
while in IDLE?

Basically, I've been importing modules and then using the dir() and help()
commands to try to get a feel for how the module works. What I would like to
do is, while I'm working out a program in interactive mode, I would like to
list all of the modules available(preferably by category), their contents,
and how they are used in a program. I guess if there is a gui app that does
this also that would be good.(You know, it list all available modules on my
system, their contents, and then uses something like help() to tell me how
to use the module and all of it's classes and functions)

Thanks.
SA

-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me




From ajs@ix.netcom.com  Mon Jul  8 00:48:11 2002
From: ajs@ix.netcom.com (Arthur Siegel)
Date: Sun, 7 Jul 2002 19:48:11 -0400
Subject: [Tutor] Properties - when and why
Message-ID: <001d01c22610$f0919480$0334fea9@carol>

Learning something about properties - as usual the hard way.
Beginning to conclude that they, as I recently learned with __slots__,
are more "special case" than I first understood.

Say self.W and self.U are each 3 element vectors referenced on
initialization, with attributes x,y, z. V is a calculated vector.  V=W-U

def get_V(self):
   return self.W-self.U

V=properties(get_V)

But occasionally I need to access V's attributes individually.

def V_homogenous(self):
    return array((V.x,V.y,V.z,1.))

Have I not just made three calls to the vector subtraction
of the get_V method? Not good.

Could have done:
def get_V(self):
   self._V  = self.W - self.V
   return self._V

def V_homogenous(self):
    return array((self._V.x,self._V.y,self._V.z,1.))

But now the use of the properties facility seems superfluous and
redundant. As a practical matter its self._V, the old style attribute
I will be referencing, not self.V, the new style property.

Is the when and why of using properties something that can be
explained in few enough words?

Art





From charles_mantha@hotmail.com  Mon Jul  8 01:24:10 2002
From: charles_mantha@hotmail.com (Charles Mantha)
Date: Sun, 7 Jul 2002 20:24:10 -0400
Subject: [Tutor] please help debug
References: <20020707192945.0413D6D9FF@www.fastmail.fm>
Message-ID: <OE48uv5JYvgs0LtQ5A800000e16@hotmail.com>

Ok, I have taken the challenge to help you debugging this. I'm newbie too
(discovered Python a little over a week ago ;-). I have alrdy fixed the
first bug :

This is your original version :
import time
time = time.strftime( "%I:%M:%S %Z", time.localtime(time.time()) )
def hour():
 print "The current time is %(time)s" % vars()


Which made the following error :
Please type your name:  Kyle

Traceback (most recent call last):
  File "C:\Python22\time.py", line 35, in ?
    hour()
  File "C:\Python22\time.py", line 7, in hour
    print "The current time is %(time)s" % vars()
KeyError: time

Now here is MY version of ur code :
from time import *
time = strftime( "%I:%M:%S %Z", localtime(time()) )

def hour():
 print "The current time is %s" % ctime()

You can notice that I changed the command <import time> to <from time import
*> . This way it imports all the possible commands(?) and you do not have to
add the time. infront of each statements(?).

The result :
Please type your name:  Kyle

The current time is Sun Jul 07 20:18:30 2002
Begin hour?  (Y/N):

Ok, this is only the beginning. Ill try to do as much as I can with the rest
of the bugs and then post my "discoveries" (im learning as I advance in this
task ;-).


*note : the (?) after the words is because I am not sure im using the
correct words >:( .

----- Original Message -----
From: "Kyle Babich" <kb@kb5.org>
To: "tutor" <tutor@python.org>
Sent: Sunday, July 07, 2002 3:29 PM
Subject: Re: [Tutor] please help debug


> My e-mail program deletes spaces for some reason.  I have attached a
> copy.
>




From phthenry@earthlink.net  Mon Jul  8 05:35:55 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Mon, 8 Jul 2002 00:35:55 -0400
Subject: [Tutor] substituting with a group
Message-ID: <20020708003554.A15016@localhost.localdomain>

Given the following line:

{the quick {brown fox"

I want to produce the following line:

<the> quick <brown> fox

I know that in perl, you use an expression like this:

$string =~ s/\{(\w+)/<$1>/g;

In other words, I want to substitute using the group generated
from the search. How do you do this in python?

(Core Python didn't give me any hint.)

Thanks! 

Paul



-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From phthenry@earthlink.net  Mon Jul  8 05:41:51 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Mon, 8 Jul 2002 00:41:51 -0400
Subject: [Tutor] replacing something on last line
In-Reply-To: <20020707203246.GA1067@ak.silmarill.org>
References: <20020707161112.D2438@localhost.localdomain> <20020707203246.GA1067@ak.silmarill.org>
Message-ID: <20020708004151.B15016@localhost.localdomain>

On Sun, Jul 07, 2002 at 04:32:46PM -0400, Andrei Kulakov wrote:

> Reverse, change first, reverse again and write?
> 

Could you give me an example? I am not sure how to use the reverse fuction or method.

Thanks

Paul

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From glingl@aon.at  Mon Jul  8 06:09:06 2002
From: glingl@aon.at (Gregor Lingl)
Date: Mon, 8 Jul 2002 07:09:06 +0200
Subject: [Tutor] substituting with a group
References: <20020708003554.A15016@localhost.localdomain>
Message-ID: <001901c2263d$95f2e7e0$1615a8c0@mega>

for instance:

>>> import re
>>> s="(the quick (brown fox"
>>> p = re.compile('\((\w+)')
>>> p.sub(r'<\1>',s)
'<the> quick <brown> fox'
>>> 

... maybe there are more elegant ways.

Gregor


----- Original Message ----- 
From: "Paul Tremblay" <phthenry@earthlink.net>
To: <tutor@python.org>
Sent: Monday, July 08, 2002 6:35 AM
Subject: [Tutor] substituting with a group


> Given the following line:
> 
> {the quick {brown fox"
> 
> I want to produce the following line:
> 
> <the> quick <brown> fox
> 
> I know that in perl, you use an expression like this:
> 
> $string =~ s/\{(\w+)/<$1>/g;
> 
> In other words, I want to substitute using the group generated
> from the search. How do you do this in python?
> 
> (Core Python didn't give me any hint.)
> 
> Thanks! 
> 
> Paul
> 
> 
> 
> -- 
> 
> ************************
> *Paul Tremblay         *
> *phthenry@earthlink.net*
> ************************
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




From glingl@aon.at  Mon Jul  8 06:30:07 2002
From: glingl@aon.at (Gregor Lingl)
Date: Mon, 8 Jul 2002 07:30:07 +0200
Subject: [Tutor] replacing something on last line
References: <20020707161112.D2438@localhost.localdomain> <20020707203246.GA1067@ak.silmarill.org> <20020708004151.B15016@localhost.localdomain>
Message-ID: <004b01c22640$857fe8b0$1615a8c0@mega>

BTW, there is a very fine Regular Expression HOWTO
at http://py-howto.sourceforge.net/regex/regex.html

Gregor




From ak@silmarill.org  Mon Jul  8 08:17:33 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 8 Jul 2002 03:17:33 -0400
Subject: [Tutor] replacing something on last line
In-Reply-To: <20020708004151.B15016@localhost.localdomain>
References: <20020707161112.D2438@localhost.localdomain> <20020707203246.GA1067@ak.silmarill.org> <20020708004151.B15016@localhost.localdomain>
Message-ID: <20020708071733.GA4421@ak.silmarill.org>

On Mon, Jul 08, 2002 at 12:41:51AM -0400, Paul Tremblay wrote:
> On Sun, Jul 07, 2002 at 04:32:46PM -0400, Andrei Kulakov wrote:
> 
> > Reverse, change first, reverse again and write?
> > 
> 
> Could you give me an example? I am not sure how to use the reverse fuction or method.
>

rfind from another post is more straighforward.. but you could also use
reverse method of lists: my_list.reverse(). List could be a list of
lines in files or a list of words in that line (you'd have to use
split() string method).

> 
> Thanks
> 
> Paul
> 
> -- 
> 
> ************************
> *Paul Tremblay         *
> *phthenry@earthlink.net*
> ************************
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From tbrauch@tbrauch.com  Sun Jul  7 08:27:09 2002
From: tbrauch@tbrauch.com (Timothy M. Brauch)
Date: Sun, 7 Jul 2002 03:27:09 -0400
Subject: [Tutor] Class attributes
References: <XFMail.20020707000343.shalehperry@attbi.com>
Message-ID: <000b01c22587$bcb22780$9c21840a@tmbrau00>

>
> >>> class BigClass:
> ...   def __str__(self):
> ...     return '[%s, %s]' % (self.a, self.b)

I see, I was leaving out the quotes.  __str__ only works when you return a
string.  It makes sense.  In fact, I think I knew that, but for some reason
it just wasn't sinking in when I coded it.

 - Tim




From ashish@shrestha.net.np  Sun Jul  7 03:50:21 2002
From: ashish@shrestha.net.np (Ashish Shrestha)
Date: Sun, 07 Jul 2002 08:35:21 +0545
Subject: [Tutor] dynamic proxy in python oop
References: <Pine.LNX.4.44.0207061120190.14624-100000@hkn.eecs.berkeley.edu>
Message-ID: <3D27AC6D.70100@shrestha.net.np>

Danny Yoo wrote:
> Python actually does at least two things when it sees this expression: it
> looks up the 'doSomething' attribute on our proxyObject, because even
> methods are attributes in Python.  Only after this, after grabbing the
> method out of the object, can we call it.
> 
Yup, this is what I had forgotten -- functions are attributes too!

> Alex Martelli wrote a really cool post about an alternative way of making
> one class instance look like another one:
> 
>     http://groups.google.com/groups?selm=8ubclp01s4t%40news1.newsguy.com
Will check it out!

Also, found Thinking in Python, Sect04 real useful.

Ashish




From dyoo@hkn.eecs.berkeley.edu  Mon Jul  8 08:55:55 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 8 Jul 2002 00:55:55 -0700 (PDT)
Subject: [Tutor] Properties - when and why  [using caching]
In-Reply-To: <001d01c22610$f0919480$0334fea9@carol>
Message-ID: <Pine.LNX.4.44.0207080041170.16445-100000@hkn.eecs.berkeley.edu>


On Sun, 7 Jul 2002, Arthur Siegel wrote:

> Say self.W and self.U are each 3 element vectors referenced on
> initialization, with attributes x,y, z. V is a calculated vector.  V=W-U
>
> def get_V(self):
>    return self.W-self.U
>
> V=properties(get_V)
>
> But occasionally I need to access V's attributes individually.
>
> def V_homogenous(self):
>     return array((V.x,V.y,V.z,1.))
>
> Have I not just made three calls to the vector subtraction
> of the get_V method?

Hi Arthur,

Yes, but this actually isn't as bad as one might think.  The "refactoring"
folks, in fact, recommend something like this, turning attribute access
into a method call.  I think properties are there to disguise what looks
like a simple attribute access with a full-fledged method that we can
control.


You're right that separate access to V.x, V.y, and V.z will cause Python
to call get_V three times, and each time will compute that vector
subtraction.  But we can fix this!  To reduce the cost of computing
methods, we can use a cache that saves the last calculation of
'self.W-self.U'.  That is, compute it once, and then cache it aside.

###
def __init__(self):
    ## Somewhere within the initializer, let's make our class as being
    ## "dirty"
    self._dirty_V = 1

def get_V(self):
    if self._dirty_V:
        self._precomputed_V = self.W - self.U
        self._dirty_V = 0
    return self._precomputed_V
###


As long as the 'x', 'y', and 'z' attributes don't change, then there's no
need to do that expensive vector subtraction again whenever we want 'V'.
We should also attach, within each of the set()er property methods, a
little switch to make 'V' dirty again.


Notice that because get_V() is a method, we can do this optimization
without disturbing the user of our class instance.  This is a great
demonstration of the advantage of properties.  Without the use of
properties, we can't smuggle this caching code within an attribute access,
at least, not without writing really tricky code...  *grin*



> Could have done:
> def get_V(self):
>    self._V  = self.W - self.V
>    return self._V
>
> def V_homogenous(self):
>     return array((self._V.x,self._V.y,self._V.z,1.))


Yes, this is the same idea.  We do need to make sure that get_V() gets
called before V_homogenous():  otherwise, self._V may not be initialized
by then if we're not careful.


Hope this helps!




From dyoo@hkn.eecs.berkeley.edu  Mon Jul  8 09:04:37 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 8 Jul 2002 01:04:37 -0700 (PDT)
Subject: [Tutor] substituting with a group
In-Reply-To: <20020708003554.A15016@localhost.localdomain>
Message-ID: <Pine.LNX.4.44.0207080101420.16445-100000@hkn.eecs.berkeley.edu>


On Mon, 8 Jul 2002, Paul Tremblay wrote:

> Given the following line:
>
> {the quick {brown fox"
>
> I want to produce the following line:
>
> <the> quick <brown> fox
>
> I know that in perl, you use an expression like this:
>
> $string =~ s/\{(\w+)/<$1>/g;
>
> In other words, I want to substitute using the group generated
> from the search. How do you do this in python?

Hi Paul,

Instead of using "$1", Python's regular expression engine uses '\1'
instead.  So you can do something like:

###
>>> re.sub(r'(\w+) (\w+)', r'\2 \1', 'hello world this is a test')
'world hello is this test a'
###


Hope this helps!




From adi.clepcea@sysrom.ro  Mon Jul  8 12:00:59 2002
From: adi.clepcea@sysrom.ro (Adi Clepcea)
Date: Mon, 8 Jul 2002 14:00:59 +0300 (E. Europe Daylight Time)
Subject: [Tutor] ODBC problem
Message-ID: <3D2970EB.000005.01140@adi-clepcea>

--------------Boundary-00=_NXFX6RO0000000000000
Content-Type: Text/Plain;
  charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable


I have a simple code that runs just fine when is not in an cgi.
The code uses the odbc module to retrieve data from a database.

However, when in a cgi, the code gives me the following error:

'dbi.operation-error', '[Microsoft][ODBC Driver Manager] Data source name=
 not found and no default driver specified in LOGIN'

the code is:

"o=3Dodbc.odbc('Agenda/user/password')
 cur=3Do.cursor()"

TIA
Adi
--------------Boundary-00=_NXFX6RO0000000000000
Content-Type: Text/HTML;
  charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<html>
<head>
<meta name=3D"GENERATOR" content=3D"IncrediMail 1.0">
</head>

<BODY background=3D"" bgColor=3D#ffffff style=3D"BACKGROUND-POSITION: 0px=
 0px; FONT-SIZE: 10pt; MARGIN: 1px; FONT-FAMILY: Arial" scroll=3Dyes ORGY=
POS=3D"0">
<TABLE border=3D0 cellPadding=3D0 cellSpacing=3D0 id=3DINCREDIMAINTABLE w=
idth=3D"95%">
<TR>

<TD id=3DINCREDITEXTREGION width=3D"100%" style=3D"PADDING-RIGHT: 7px; PA=
DDING-LEFT: 7px; FONT-SIZE: 10pt; FONT-FAMILY: Arial"=20
   >
      <DIV>&nbsp;</DIV>
      <DIV>I have a simple code that runs just fine when is not in an cgi=
=2E</DIV>
      <DIV>The code uses the odbc module to retrieve data from a database=
=2E</DIV>
      <DIV>&nbsp;</DIV>
      <DIV>However, when in a cgi, the code gives me the following error:=
</DIV>
      <DIV>&nbsp;</DIV>
      <DIV>'dbi.operation-error', '[Microsoft][ODBC Driver Manager] Data =
source=20
      name not found and no default driver specified in LOGIN'</DIV>
      <DIV>&nbsp;</DIV>
      <DIV>the code is:</DIV>
      <DIV>&nbsp;</DIV>
      <DIV>"o=3Dodbc.odbc('Agenda/user/password')<BR>&nbsp;cur=3Do.cursor=
()"</DIV>
      <DIV>&nbsp;</DIV>
      <DIV>TIA</DIV>
      <DIV>Adi</DIV></TD>
</TR>

<TR>
<TD id=3DINCREDIFOOTER width=3D"100%">

=09<TABLE cellPadding=3D0 cellSpacing=3D0 width=3D"100%">
=09<TR>
=09<TD width=3D"100%"></TD>
=09<TD align=3Dmiddle id=3DINCREDISOUND vAlign=3Dbottom></TD>
=09<TD align=3Dmiddle id=3DINCREDIANIM vAlign=3Dbottom></TD>
=09</TR>
=09</TABLE>

</TD>
</TR>

</TABLE><SPAN=20
id=3DIncrediStamp><SPAN dir=3Dltr><FONT face=3D"Arial, Helvetica, sans-se=
rif"=20
size=3D2>_________________________________________________<BR><FONT=20
face=3D"Comic Sans MS" size=3D2><I>IncrediMail</I> - <B>Email has finally=
=20
evolved</B> - </FONT><A href=3D"http://www.incredimail.com/imstampa.html"=
><FONT=20
face=3D"Times New Roman" size=3D3><B><U>Click=20
Here</U></B></FONT></A></SPAN></SPAN></FONT>
</BODY>
</html>
--------------Boundary-00=_NXFX6RO0000000000000--




From sarmstrong13@mac.com  Mon Jul  8 12:40:20 2002
From: sarmstrong13@mac.com (SA)
Date: Mon, 08 Jul 2002 06:40:20 -0500
Subject: [Tutor] CGI question??
Message-ID: <B94EE454.9041%sarmstrong13@mac.com>

Hello Everyone-

    Alright. What I have is a html template file that is called by my
program. Instead of a person clicking on link to another html file, I would
like them to click on that link and a new text file be loaded between the
"<pre></pre>" in the body of the html template. I know there is a way to do
this with a query string and href, but I can't seem to figure out how it is
called in the python program or how clicking on the href query string will
pass the name of the text value to cgi.parse_qs? Any help is welcome?

Basically I have a lot of text files and one html template and a python cgi
script. The text files will be placed into the body by re all I need now is
a way to link the next text file to replace the first text file when the
user clicks the link.

Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me




From Kyle Babich" <kb@kb5.org  Mon Jul  8 13:28:45 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Mon, 8 Jul 2002 12:28:45 +0000
Subject: [Tutor] bug hunting again
Message-ID: <20020708122845.EC0576DADB@www.fastmail.fm>

This is a multi-part message in MIME format.

--_----------=_1026131325166220
Content-Disposition: inline
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset="ISO-8859-1"

I have attached a copy.  The problem is with the hour program I have
been working on (from my last few messages).  Something is stopping the
program from running and I have a few ideas but I could use some help. 
Please tell me if you can find what is stopping the program from
running.  Thank you.
--
Kyle
--_----------=_1026131325166220
Content-Disposition: attachment; filename="time.py"
Content-Transfer-Encoding: base64
Content-Type: application/unknown; name="time.py"

IyEgQzpcUHl0aG9uMjJccHl0aG9uLmV4ZQ0KDQppbXBvcnQgdGltZQ0KaW1w
b3J0IHN5cw0KDQpkZWYgaG91cigpOg0KCWN1cnJ0aW1lID0gdGltZS5zdHJm
dGltZSggIiVJOiVNOiVTJXAgJVoiLCB0aW1lLmxvY2FsdGltZSh0aW1lLnRp
bWUoKSkgKQ0KCQ0KCWxvZ3QgPSBvcGVuKCAibG9nLmRhdCIsICJhIiApDQoJ
bG9ndC53cml0ZSggIiAgWyUoY3VycnRpbWUpc10iICUgdmFycygpICkNCgls
b2d0LmNsb3NlKCkNCgkNCglwcmludCAiVGhlIGN1cnJlbnQgdGltZSBpcyAl
KGN1cnJ0aW1lKXMiICUgdmFycygpDQoJd2hpbGUgMToNCgkJYmVnaW4gPSBy
YXdfaW5wdXQoICJCZWdpbiBob3VyPyAgW1kvTl06ICAiICkNCgkNCgkJaWYg
YmVnaW4gaW4gIll5IjoNCgkJCXRpbWUuc2xlZXAoIDUgKQ0KDQoJCQlsb2dl
ID0gb3BlbiggImxvZy5kYXQiLCAiYSIgKQ0KCQkJbG9nZS53cml0ZSggIiBb
IiArIHRpbWUuc3RyZnRpbWUoICIlSTolTTolUyVwICVaIiwgdGltZS5sb2Nh
bHRpbWUodGltZS50aW1lKCkpICkgKyAiXVxuIiAlIHZhcnMoKSApDQoJCQls
b2dlLmNsb3NlKCkNCgkJCQ0KCQkJcHJpbnQNCgkJCXByaW50ICJIb3VyIENv
bXBsZXRlIg0KCQkJdGltZS5zbGVlcCggMzAgKQ0KCQkJc3lzLmV4aXQoKQ0K
CQllbGlmIGJlZ2luIGluICJObiI6DQoJCQlwcmludA0KCQkJaG91cigpDQoJ
CWVsc2U6DQoJCQlwcmludCAiRkFJTEVEIg0KCQkJdGltZS5zbGVlcCggMzAg
KQ0KCQkJc3lzLmV4aXQoKQ0KDQpkZWYgY3VzdG9tKCk6DQoJc2xlZXB0aW1l
ID0gcmF3X2lucHV0KCAiUGxlYXNlIGVudGVyIHRpbWUgdG8gc2xlZXAgaW4g
bWludXRlczogICIpDQoNCglsb2djdSA9IG9wZW4oICJsb2cuZGF0IiwgImEi
ICkNCglsb2djdS53cml0ZSggcHJpbnQgIiAgWyUoc2xlZXB0aW1lKXNdIiAl
IHZhcnMoKSApDQoJbG9jY3UuY2xvc2UoKQ0KDQoJd2hpbGUgMToNCgkJY29u
ZmlybSA9IHJhd19pbnB1dCggIkNvbmZpcm0gJShzbGVlcHRpbWUpcyBtaW51
dGVzPyAgW1kvTl06ICAiICkNCg0KCQlpZiBjb25maXJtIGluICJZeSI6DQoJ
CQlob3VyMigpDQoJCWVsaWYgY29uZmlybSBpbiAiTm4iOg0KCQkJY3VzdG9t
KCkNCgkJZWxzZToNCgkJCXByaW50ICJGQUlMRUQiDQoJCQl0aW1lLnNsZWVw
KCAzMCApDQoJCQlzeXMuZXhpdCgpDQoNCgkNCmRlZiBob3VyMigpOg0KCWN1
cnJ0aW1lID0gdGltZS5zdHJmdGltZSggIiVJOiVNOiVTJXAgJVoiLCB0aW1l
LmxvY2FsdGltZSh0aW1lLnRpbWUoKSkgKQ0KCQ0KCWxvZ3QgPSBvcGVuKCAi
bG9nLmRhdCIsICJhIiApDQoJbG9ndC53cml0ZSggIiBbJShjdXJydGltZSlz
XSIgJSB2YXJzKCkgKQ0KCWxvZ3QuY2xvc2UoKQ0KCQ0KCXByaW50ICJUaGUg
Y3VycmVudCB0aW1lIGlzICUoY3VycnRpbWUpcyIgJSB2YXJzKCkNCgl3aGls
ZSAxOg0KCQliZWdpbiA9IHJhd19pbnB1dCggIkJlZ2luIHRpbWU/ICBbWS9O
XTogICIgKQ0KCQ0KCQlpZiBiZWdpbiBpbiAiWXkiOg0KCQkJdGltZS5zbGVl
cCggc2xlZXB0aW1lKjYwICkNCg0KCQkJbG9nZSA9IG9wZW4oICJsb2cuZGF0
IiwgImEiICkNCgkJCWxvZ2Uud3JpdGUoICIgWyIgKyB0aW1lLnN0cmZ0aW1l
KCAiJUk6JU06JVMlcCAlWiIsIHRpbWUubG9jYWx0aW1lKHRpbWUudGltZSgp
KSApICsgIl1cbiIgJSB2YXJzKCkgKQ0KCQkJbG9nZS5jbG9zZSgpDQoJCQkN
CgkJCXByaW50DQoJCQlwcmludCAiVGltZSBDb21wbGV0ZSINCgkJCXRpbWUu
c2xlZXAoIDMwICkNCgkJCXN5cy5leGl0KCkNCgkJZWxpZiBiZWdpbiBpbiAi
Tm4iOg0KCQkJcHJpbnQNCgkJCWhvdXIoKQ0KCQllbHNlOg0KCQkJcHJpbnQg
IkZBSUxFRCINCgkJCXRpbWUuc2xlZXAoIDMwICkNCgkJCXN5cy5leGl0KCkN
Cg0KdXNlcm5hbWUgPSByYXdfaW5wdXQoICJQbGVhc2UgdHlwZSB5b3VyIGZp
cnN0IG5hbWU6ICAiICkNCg0KbG9ndSA9IG9wZW4oICJsb2cuZGF0IiwgImEi
ICkNCmxvZ3Uud3JpdGUoICIlKHVzZXJuYW1lKXMiICUgdmFycygpICkNCmxv
Z3UuY2xvc2UoKQ0KDQppZiB1c2VybmFtZS5sb3dlcigpIGluICJreWxlIGph
c29uIGNoZWxzZWEgam9obiBjaGVyeWwiLnNwbGl0KCk6DQoJcHJpbnQNCglo
b3VyKCkNCmVsaWYgdXNlcm5hbWUubG93ZXIoKSBpbiAia3lsZSxjdXN0b20g
amFzb24sY3VzdG9tIGNoZWxzZWEsY3VzdG9tIGpvaG4sY3VzdG9tIGNoZXJ5
bCxjdXN0b20iLnNwbGl0KCk6DQoJcHJpbnQNCgljdXN0b20oKQ0KZWxzZToN
CglwcmludA0KCXByaW50ICJGQUlMRUQiDQoJdGltZS5zbGVlcCggMzAgKQ0K
CXN5cy5leGl0KCkNCg==

--_----------=_1026131325166220--




From dman@dman.ddts.net  Mon Jul  8 13:55:15 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Mon, 8 Jul 2002 07:55:15 -0500
Subject: [Tutor] Re: replacing something on last line
In-Reply-To: <20020707203246.GA1067@ak.silmarill.org>
References: <20020707161112.D2438@localhost.localdomain> <20020707203246.GA1067@ak.silmarill.org>
Message-ID: <20020708125515.GA27479@dman.ddts.net>

--WIyZ46R2i8wDzkSu
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sun, Jul 07, 2002 at 04:32:46PM -0400, Andrei Kulakov wrote:
| On Sun, Jul 07, 2002 at 04:11:12PM -0400, Paul Tremblay wrote:
| > For the life of me, I can't figure out how to change the last
| > instance of something in a file. For example, given:
| >=20
| > text
| > text=20
| > text
| > text Special Special
| >=20
| > I want to replace just the last Special in the file

| Reverse, change first, reverse again and write?

Or just use '-1' as the index :

data =3D f.readlines()
f.close()
data[-1] =3D data[-1].replace( "Special" , "Not so special anymore" )
f =3D open(  ) # reopen the file for writing, there are more robust ways of=
 doing this
f.writelines( data )

You could also use a variety of loops to avoid reading the whole file
into memory at once.=20

-D

--=20
=20
Emacs is a nice operating system, it lacks a decent editor though
=20
http://dman.ddts.net/~dman/


--WIyZ46R2i8wDzkSu
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0pi7IACgkQO8l8XBKTpRQJRwCeJfk/Dg/qDv4qoGGIDadExQlV
tXAAoKCyHyKWmEnrxJmU8oXVhRlFiVKI
=Sj47
-----END PGP SIGNATURE-----

--WIyZ46R2i8wDzkSu--



From dman@dman.ddts.net  Mon Jul  8 13:59:34 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Mon, 8 Jul 2002 07:59:34 -0500
Subject: [Tutor] Re: ODBC problem
In-Reply-To: <3D2970EB.000005.01140@adi-clepcea>
References: <3D2970EB.000005.01140@adi-clepcea>
Message-ID: <20020708125934.GB27479@dman.ddts.net>

--rJwd6BRFiFCcLxzm
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jul 08, 2002 at 02:00:59PM +0300, Adi Clepcea wrote:
|=20
| I have a simple code that runs just fine when is not in an cgi.
| The code uses the odbc module to retrieve data from a database.
|=20
| However, when in a cgi, the code gives me the following error:
|=20
| 'dbi.operation-error', '[Microsoft][ODBC Driver Manager] Data source name=
 not found and no default driver specified in LOGIN'
|=20
| the code is:
|=20
| "o=3Dodbc.odbc('Agenda/user/password')
|  cur=3Do.cursor()"

Where did you define the data source?  I think you'll want it in the
"system" tab of the control panel gui.  If it is in the "user" tab,
then only the user that created it can access it (I think).

(assuming you're using Windows as the OS on which the script is run)

-D

--=20
=20
Religion that God our Father accepts as pure and faultless is this: to
look after orphans and widows in their distress and to keep oneself from
being polluted by the world.
        James 1:27
=20
http://dman.ddts.net/~dman/


--rJwd6BRFiFCcLxzm
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0pjLUACgkQO8l8XBKTpRQpcACcCzRCmBEl2n0Zezp6umiH2Toy
YioAoLfpetkMe9uhEbaAvkoBYXMnH1yl
=g1iE
-----END PGP SIGNATURE-----

--rJwd6BRFiFCcLxzm--



From dman@dman.ddts.net  Mon Jul  8 14:02:42 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Mon, 8 Jul 2002 08:02:42 -0500
Subject: [Tutor] Re: substituting with a group
In-Reply-To: <20020708003554.A15016@localhost.localdomain>
References: <20020708003554.A15016@localhost.localdomain>
Message-ID: <20020708130242.GC27479@dman.ddts.net>

--jousvV0MzM2p6OtC
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jul 08, 2002 at 12:35:55AM -0400, Paul Tremblay wrote:
=20
| I know that in perl, you use an expression like this:
|=20
| $string =3D~ s/\{(\w+)/<$1>/g;
|=20
| In other words, I want to substitute using the group generated
| from the search. How do you do this in python?

One way to use backreferences is like this :

match =3D re.search( 'regex' , 'text' )
if match is None :
    print "No match"
else :
    for i in xrange( len(match.groups()) ) :
        print "Group %d in the match was '%s'" % (i , match.group(i) )


That is, the regex search/match functions will return a "match"
object.  That object has methods (namely group() and groups()) to let
you access the groups and other attributes of the match.  There's a
lot you can do with it, if the need/use arises.

-D

--=20
=20
Stay away from a foolish man,
for you will not find knowledge on his lips.
        Proverbs 14:7
=20
http://dman.ddts.net/~dman/


--jousvV0MzM2p6OtC
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0pjXIACgkQO8l8XBKTpRSiNACaAsM80DKVJVSPTEaDDuc6tz5Z
ZzkAnAsQB7mXi/u5wdzn276G5XOk/cQ+
=LBvf
-----END PGP SIGNATURE-----

--jousvV0MzM2p6OtC--



From ak@silmarill.org  Mon Jul  8 14:16:16 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 8 Jul 2002 09:16:16 -0400
Subject: [Tutor] bug hunting again
In-Reply-To: <20020708122845.EC0576DADB@www.fastmail.fm>
References: <20020708122845.EC0576DADB@www.fastmail.fm>
Message-ID: <20020708131616.GA7292@ak.silmarill.org>

On Mon, Jul 08, 2002 at 12:28:45PM +0000, Kyle Babich wrote:
> I have attached a copy.  The problem is with the hour program I have
> been working on (from my last few messages).  Something is stopping the
> program from running and I have a few ideas but I could use some help. 
> Please tell me if you can find what is stopping the program from
> running.  Thank you.
> --
> Kyle

I got this traceback:

  File "time.py", line 40
    logcu.write( print "  [%(sleeptime)s]" % vars() )

print is for printing stuff to the screen. Here, you should omit it -
you're writing to the log file.

 - Andrei

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From ak@silmarill.org  Mon Jul  8 14:18:11 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 8 Jul 2002 09:18:11 -0400
Subject: [Tutor] Re: replacing something on last line
In-Reply-To: <20020708125515.GA27479@dman.ddts.net>
References: <20020707161112.D2438@localhost.localdomain> <20020707203246.GA1067@ak.silmarill.org> <20020708125515.GA27479@dman.ddts.net>
Message-ID: <20020708131811.GB7292@ak.silmarill.org>

On Mon, Jul 08, 2002 at 07:55:15AM -0500, Derrick 'dman' Hudson wrote:
> On Sun, Jul 07, 2002 at 04:32:46PM -0400, Andrei Kulakov wrote:
> | On Sun, Jul 07, 2002 at 04:11:12PM -0400, Paul Tremblay wrote:
> | > For the life of me, I can't figure out how to change the last
> | > instance of something in a file. For example, given:
> | > 
> | > text
> | > text 
> | > text
> | > text Special Special
> | > 
> | > I want to replace just the last Special in the file
> 
> | Reverse, change first, reverse again and write?
> 
> Or just use '-1' as the index :
> 
> data = f.readlines()
> f.close()
> data[-1] = data[-1].replace( "Special" , "Not so special anymore" )
>
No good if it's not on the last line! Besides, this would replace both
words on the line, where he wants to replace just the last word.

> f = open(  ) # reopen the file for writing, there are more robust ways of doing this
> f.writelines( data )
> 
> You could also use a variety of loops to avoid reading the whole file
> into memory at once. 
> 
> -D
> 
> -- 
>  
> Emacs is a nice operating system, it lacks a decent editor though
>  
> http://dman.ddts.net/~dman/
> 



-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From alex@gabuzomeu.net  Mon Jul  8 15:19:27 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Mon, 08 Jul 2002 16:19:27 +0200
Subject: [Tutor] HTML Templates
In-Reply-To: <20020707160005.29452.84950.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020708160726.00d722a0@pop3.norton.antivirus>

At 12:00 07/07/2002 -0400, you wrote:
>Date: Sat, 6 Jul 2002 14:32:13 -0700
>From: Mike Barrett <mike@daboyz.org>
>Subject: [Tutor] HTML Templates
>
>Anyone got a favorite HTML template module that they use?  I'm looking to
>develop a dynamic website, and I thought I'd see what others were using 
>with python.

When looking for a toolkit/framework to develop Web sites, I came across 
several options, such as:
- Application servers: WebWare, SkunkWeb, Quixote
- Toolkits: Albatross

I used WebWare once. I started looking into Albatross a couple of days ago.

>I looked at Zope, but it's not quite what I'm looking for.  I'd
>rather just write CGI's.  Anyways, thanks for your help.

You might be interested in Albatross. The doc says that apps developped 
with this toolkit can be run both as CGIs and with mod_python.


Alexandre





From alan.gauld@bt.com  Mon Jul  8 17:13:56 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 8 Jul 2002 17:13:56 +0100
Subject: [Tutor] alternative to time.sleep()
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C718@mbtlipnt02.btlabs.bt.co.uk>

> I'm looking for an alternative to time.sleep() that will visually
> countdown/countup the sleep time and can be paused and resumed at any
> point.  Any ideas?

This what you mean?

def visualSleep(t):
   try:
      s = 0
      while s < t:
        print "Sleeping for %d Seconds" % s
        time.sleep(1)
        s += 1
   except: return s

Hit Ctrl C to trigger the exception and get the 
current 'time' back. It only works for integral seconds 
but you could use a multiplies to resolve to milliseconds 
if you really want!

You can do clever things to make the string update in 
place but thats too fancy for me :-)

Alan G



From alan.gauld@bt.com  Mon Jul  8 17:50:25 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 8 Jul 2002 17:50:25 +0100
Subject: [Tutor] bug hunting again
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C719@mbtlipnt02.btlabs.bt.co.uk>

A quick look suggests you don't actually start the 
program anywhere in your file.

How are you trying to run it?

> been working on (from my last few messages).  Something is 
> stopping the program from running 

What actually happens? Do you get any errors?
Either from DOS, Windows or Python?

> Please tell me if you can find what is stopping the program from
> running.  Thank you.

Assuming you want it to run by double clicking the file icon
you will need something like:

if __name__ == "__main":
    hour()

If you are importing it into IDLE(say) then you should 
get something back when you type time.hour()

BUT as somebody already pointed out naming things the same 
as python module names is a bad idea. When you import 
your time module you will hide the python time module.
Rename your file to hourtracker.py or something...

Slightly confused and needing more info

Alan G



From alex@gabuzomeu.net  Mon Jul  8 18:03:18 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Mon, 08 Jul 2002 19:03:18 +0200
Subject: [Tutor] CMS written in Python
Message-ID: <4.3.2.7.2.20020708185109.00b77ef0@pop3.norton.antivirus>

Hello,


Are you aware of a CMS (Content Management System) written in Python and 
available under a free-software/open-source license? Besides Zope and Zope 
modules, I mean.

There are dozens of options in PHP (PHPNuke, PostNuke, etc), but I couldn't 
find similar tools in Python.

I am looking for a stand-alone tool I could adapt to publish a dynamic Web 
site.


Thanks.

Alexandre




From pythontutor@venix.com  Mon Jul  8 18:44:06 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Mon, 08 Jul 2002 13:44:06 -0400
Subject: [Tutor] Simple Python Question.
References: <B94E340C.900D%sarmstrong13@mac.com>
Message-ID: <3D29CF66.4060607@venix.com>

It sounds like you are looking for the module index??
http://www.python.org/doc/current/modindex.html
Global Module Index

This file should be available through the Idle help.

I hope this is what you are looking for.

SA wrote:

> What is the best way to look up all the python modules present in Python
> while in IDLE?
> 
> Basically, I've been importing modules and then using the dir() and help()
> commands to try to get a feel for how the module works. What I would like to
> do is, while I'm working out a program in interactive mode, I would like to
> list all of the modules available(preferably by category), their contents,
> and how they are used in a program. I guess if there is a gui app that does
> this also that would be good.(You know, it list all available modules on my
> system, their contents, and then uses something like help() to tell me how
> to use the module and all of it's classes and functions)
> 
> Thanks.
> SA
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From sarmstrong13@mac.com  Mon Jul  8 19:03:49 2002
From: sarmstrong13@mac.com (SA)
Date: Mon, 08 Jul 2002 13:03:49 -0500
Subject: [Tutor] Simple Python Question.
In-Reply-To: <3D29CF66.4060607@venix.com>
Message-ID: <B94F3E35.9086%sarmstrong13@mac.com>

Close. I knew about that already. What I was interested in is some type of
"Explorer" app that had a hierarchial menu in the left field and when an
item in that field is clicked on it would display the help() info in the
right.
By the way, I do not use idle on my MacOSX box because it does not want to
work properly. I therefore have to use the command line idle.

Thanks.
SA


On 7/8/02 12:44 PM, "Lloyd Kvam" <pythontutor@venix.com> wrote:

> It sounds like you are looking for the module index??
> http://www.python.org/doc/current/modindex.html
> Global Module Index
> 
> This file should be available through the Idle help.
> 
> I hope this is what you are looking for.
> 




From Kyle Babich" <kb@kb5.org  Mon Jul  8 19:32:59 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Mon, 8 Jul 2002 18:32:59 +0000
Subject: [Tutor] bug hunting again
Message-ID: <20020708183259.C690D6DB2E@www.fastmail.fm>

This is a multi-part message in MIME format.

--_----------=_1026153179112942
Content-Disposition: inline
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset="ISO-8859-1"

Ok now my problem is this:

  File "hourtracker.py", line 92, in ?
    if username.lower() in "kyle jason chelsea john cheryl".split():
AttributeError: 'string' object has no attribute 'lower'

But I don't see what is wrong.
I have attached a new copy.

On Mon, 8 Jul 2002 17:50:25 +0100 , alan.gauld@bt.com said:
> A quick look suggests you don't actually start the 
> program anywhere in your file.
> 
> How are you trying to run it?
> 
> > been working on (from my last few messages).  Something is 
> > stopping the program from running 
> 
> What actually happens? Do you get any errors?
> Either from DOS, Windows or Python?
> 
> > Please tell me if you can find what is stopping the program from
> > running.  Thank you.
> 
> Assuming you want it to run by double clicking the file icon
> you will need something like:
> 
> if __name__ == "__main":
>     hour()
> 
> If you are importing it into IDLE(say) then you should 
> get something back when you type time.hour()
> 
> BUT as somebody already pointed out naming things the same 
> as python module names is a bad idea. When you import 
> your time module you will hide the python time module.
> Rename your file to hourtracker.py or something...
> 
> Slightly confused and needing more info
> 
> Alan G
> 
> 
> 
> 

--
Kyle
--_----------=_1026153179112942
Content-Disposition: attachment; filename="hourtracker.py"
Content-Transfer-Encoding: base64
Content-Type: application/unknown; name="hourtracker.py"

IyEgQzpcUHl0aG9uMjJccHl0aG9uLmV4ZQ0KDQppbXBvcnQgdGltZQ0KaW1w
b3J0IHN5cw0KDQpkZWYgaG91cigpOg0KCWN1cnJ0aW1lID0gdGltZS5zdHJm
dGltZSggIiVJOiVNOiVTJXAgJVoiLCB0aW1lLmxvY2FsdGltZSh0aW1lLnRp
bWUoKSkgKQ0KCQ0KCWxvZ3QgPSBvcGVuKCAibG9nLmRhdCIsICJhIiApDQoJ
bG9ndC53cml0ZSggIiAgWyUoY3VycnRpbWUpc10iICUgdmFycygpICkNCgls
b2d0LmNsb3NlKCkNCgkNCglwcmludCAiVGhlIGN1cnJlbnQgdGltZSBpcyAl
KGN1cnJ0aW1lKXMiICUgdmFycygpDQoJd2hpbGUgMToNCgkJYmVnaW4gPSBy
YXdfaW5wdXQoICJCZWdpbiBob3VyPyAgW1kvTl06ICAiICkNCgkNCgkJaWYg
YmVnaW4gaW4gIll5IjoNCgkJCXRpbWUuc2xlZXAoIDUgKQ0KDQoJCQlsb2dl
ID0gb3BlbiggImxvZy5kYXQiLCAiYSIgKQ0KCQkJbG9nZS53cml0ZSggIiBb
IiArIHRpbWUuc3RyZnRpbWUoICIlSTolTTolUyVwICVaIiwgdGltZS5sb2Nh
bHRpbWUodGltZS50aW1lKCkpICkgKyAiXVxuIiAlIHZhcnMoKSApDQoJCQls
b2dlLmNsb3NlKCkNCgkJCQ0KCQkJcHJpbnQNCgkJCXByaW50ICJIb3VyIENv
bXBsZXRlIg0KCQkJdGltZS5zbGVlcCggMzAgKQ0KCQkJc3lzLmV4aXQoKQ0K
CQllbGlmIGJlZ2luIGluICJObiI6DQoJCQlwcmludA0KCQkJaG91cigpDQoJ
CWVsc2U6DQoJCQlwcmludCAiRkFJTEVEIg0KCQkJdGltZS5zbGVlcCggMzAg
KQ0KCQkJc3lzLmV4aXQoKQ0KDQpkZWYgY3VzdG9tKCk6DQoJc2xlZXB0aW1l
ID0gcmF3X2lucHV0KCAiUGxlYXNlIGVudGVyIHRpbWUgdG8gc2xlZXAgaW4g
bWludXRlczogICIpDQoNCglsb2djdSA9IG9wZW4oICJsb2cuZGF0IiwgImEi
ICkNCglsb2djdS53cml0ZSggIiAgWyUoc2xlZXB0aW1lKXNdIiAlIHZhcnMo
KSApDQoJbG9jY3UuY2xvc2UoKQ0KDQoJd2hpbGUgMToNCgkJY29uZmlybSA9
IHJhd19pbnB1dCggIkNvbmZpcm0gJShzbGVlcHRpbWUpcyBtaW51dGVzPyAg
W1kvTl06ICAiICkNCg0KCQlpZiBjb25maXJtIGluICJZeSI6DQoJCQlob3Vy
MigpDQoJCWVsaWYgY29uZmlybSBpbiAiTm4iOg0KCQkJY3VzdG9tKCkNCgkJ
ZWxzZToNCgkJCXByaW50ICJGQUlMRUQiDQoJCQl0aW1lLnNsZWVwKCAzMCAp
DQoJCQlzeXMuZXhpdCgpDQoNCgkNCmRlZiBob3VyMigpOg0KCWN1cnJ0aW1l
ID0gdGltZS5zdHJmdGltZSggIiVJOiVNOiVTJXAgJVoiLCB0aW1lLmxvY2Fs
dGltZSh0aW1lLnRpbWUoKSkgKQ0KCQ0KCWxvZ3QgPSBvcGVuKCAibG9nLmRh
dCIsICJhIiApDQoJbG9ndC53cml0ZSggIiBbJShjdXJydGltZSlzXSIgJSB2
YXJzKCkgKQ0KCWxvZ3QuY2xvc2UoKQ0KCQ0KCXByaW50ICJUaGUgY3VycmVu
dCB0aW1lIGlzICUoY3VycnRpbWUpcyIgJSB2YXJzKCkNCgl3aGlsZSAxOg0K
CQliZWdpbiA9IHJhd19pbnB1dCggIkJlZ2luIHRpbWU/ICBbWS9OXTogICIg
KQ0KCQ0KCQlpZiBiZWdpbiBpbiAiWXkiOg0KCQkJdGltZS5zbGVlcCggc2xl
ZXB0aW1lKjYwICkNCg0KCQkJbG9nZSA9IG9wZW4oICJsb2cuZGF0IiwgImEi
ICkNCgkJCWxvZ2Uud3JpdGUoICIgWyIgKyB0aW1lLnN0cmZ0aW1lKCAiJUk6
JU06JVMlcCAlWiIsIHRpbWUubG9jYWx0aW1lKHRpbWUudGltZSgpKSApICsg
Il1cbiIgJSB2YXJzKCkgKQ0KCQkJbG9nZS5jbG9zZSgpDQoJCQkNCgkJCXBy
aW50DQoJCQlwcmludCAiVGltZSBDb21wbGV0ZSINCgkJCXRpbWUuc2xlZXAo
IDMwICkNCgkJCXN5cy5leGl0KCkNCgkJZWxpZiBiZWdpbiBpbiAiTm4iOg0K
CQkJcHJpbnQNCgkJCWhvdXIoKQ0KCQllbHNlOg0KCQkJcHJpbnQgIkZBSUxF
RCINCgkJCXRpbWUuc2xlZXAoIDMwICkNCgkJCXN5cy5leGl0KCkNCg0KdXNl
cm5hbWUgPSByYXdfaW5wdXQoICJQbGVhc2UgdHlwZSB5b3VyIGZpcnN0IG5h
bWU6ICAiICkNCg0KbG9ndSA9IG9wZW4oICJsb2cuZGF0IiwgImEiICkNCmxv
Z3Uud3JpdGUoICIlKHVzZXJuYW1lKXMiICUgdmFycygpICkNCmxvZ3UuY2xv
c2UoKQ0KDQppZiB1c2VybmFtZS5sb3dlcigpIGluICJreWxlIGphc29uIGNo
ZWxzZWEgam9obiBjaGVyeWwiLnNwbGl0KCk6DQoJcHJpbnQNCglob3VyKCkN
CmVsaWYgdXNlcm5hbWUubG93ZXIoKSBpbiAia3lsZS5jdXN0b20gamFzb24u
Y3VzdG9tIGNoZWxzZWEuY3VzdG9tIGpvaG4uY3VzdG9tIGNoZXJ5bC5jdXN0
b20iLnNwbGl0KCk6DQoJcHJpbnQNCgljdXN0b20oKQ0KZWxzZToNCglwcmlu
dA0KCXByaW50ICJGQUlMRUQiDQoJdGltZS5zbGVlcCggMzAgKQ0KCXN5cy5l
eGl0KCkNCg==

--_----------=_1026153179112942--




From pythontutor@venix.com  Mon Jul  8 19:58:12 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Mon, 08 Jul 2002 14:58:12 -0400
Subject: [Tutor] bug hunting again
References: <20020708183259.C690D6DB2E@www.fastmail.fm>
Message-ID: <3D29E0C4.8030206@venix.com>

That worked here!?

Kyle Babich wrote:

> Ok now my problem is this:
> 
>   File "hourtracker.py", line 92, in ?
>     if username.lower() in "kyle jason chelsea john cheryl".split():
> AttributeError: 'string' object has no attribute 'lower'
> 
> But I don't see what is wrong.
> I have attached a new copy.
> 
> On Mon, 8 Jul 2002 17:50:25 +0100 , alan.gauld@bt.com said:
> 
>>A quick look suggests you don't actually start the 
>>program anywhere in your file.
>>
>>How are you trying to run it?
>>
>>
>>>been working on (from my last few messages).  Something is 
>>>stopping the program from running 
>>>
>>What actually happens? Do you get any errors?
>>Either from DOS, Windows or Python?
>>
>>
>>>Please tell me if you can find what is stopping the program from
>>>running.  Thank you.
>>>
>>Assuming you want it to run by double clicking the file icon
>>you will need something like:
>>
>>if __name__ == "__main":
>>    hour()
>>
>>If you are importing it into IDLE(say) then you should 
>>get something back when you type time.hour()
>>
>>BUT as somebody already pointed out naming things the same 
>>as python module names is a bad idea. When you import 
>>your time module you will hide the python time module.
>>Rename your file to hourtracker.py or something...
>>
>>Slightly confused and needing more info
>>
>>Alan G
>>
>>
>>
>>
>>
> 
> --
> Kyle
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From Kyle Babich" <kb@kb5.org  Mon Jul  8 20:16:53 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Mon, 8 Jul 2002 19:16:53 +0000
Subject: [Tutor] bug hunting again
Message-ID: <20020708191653.9779B6D9A9@www.fastmail.fm>

When you run it and it asks for a name put in one of the usernames with
the .custom at the end and any amount of time.  That's where the error
comes in.

On Mon, 08 Jul 2002 14:58:12 -0400, "Lloyd Kvam"
<pythontutor@venix.com> said:
> That worked here!?
> 
> Kyle Babich wrote:
> 
> > Ok now my problem is this:
> > 
> >   File "hourtracker.py", line 92, in ?
> >     if username.lower() in "kyle jason chelsea john cheryl".split():
> > AttributeError: 'string' object has no attribute 'lower'
> > 
> > But I don't see what is wrong.
> > I have attached a new copy.
> > 
> > On Mon, 8 Jul 2002 17:50:25 +0100 , alan.gauld@bt.com said:
> > 
> >>A quick look suggests you don't actually start the 
> >>program anywhere in your file.
> >>
> >>How are you trying to run it?
> >>
> >>
> >>>been working on (from my last few messages).  Something is 
> >>>stopping the program from running 
> >>>
> >>What actually happens? Do you get any errors?
> >>Either from DOS, Windows or Python?
> >>
> >>
> >>>Please tell me if you can find what is stopping the program from
> >>>running.  Thank you.
> >>>
> >>Assuming you want it to run by double clicking the file icon
> >>you will need something like:
> >>
> >>if __name__ == "__main":
> >>    hour()
> >>
> >>If you are importing it into IDLE(say) then you should 
> >>get something back when you type time.hour()
> >>
> >>BUT as somebody already pointed out naming things the same 
> >>as python module names is a bad idea. When you import 
> >>your time module you will hide the python time module.
> >>Rename your file to hourtracker.py or something...
> >>
> >>Slightly confused and needing more info
> >>
> >>Alan G
> >>
> >>
> >>
> >>
> >>
> > 
> > --
> > Kyle
> > 
> 
> 
> -- 
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
> 
> voice: 
> 603-443-6155
> fax: 
> 801-459-9582
> 
> 
> 
> 
> 

--
Kyle



From dyoo@hkn.eecs.berkeley.edu  Mon Jul  8 20:37:35 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 8 Jul 2002 12:37:35 -0700 (PDT)
Subject: [Tutor] bug hunting again
In-Reply-To: <20020708183259.C690D6DB2E@www.fastmail.fm>
Message-ID: <Pine.LNX.4.44.0207081229390.28440-100000@hkn.eecs.berkeley.edu>


On Mon, 8 Jul 2002, Kyle Babich wrote:

> Ok now my problem is this:
>
>   File "hourtracker.py", line 92, in ?
>     if username.lower() in "kyle jason chelsea john cheryl".split():
> AttributeError: 'string' object has no attribute 'lower'
>
> But I don't see what is wrong.

Hi Kyle,

Just to make sure: which version of Python are you running?  Can you check
to see if it is Python 1.52, or Python 2.2?  If it's 1.52, the reason
you're running into problems is because strings didn't have methods at
that time.


In 1.52, we'll get an error if we try using a string method:

###
[dyoo@tesuque dyoo]$ /usr/bin/python
Python 1.5.2 (#1, Apr  3 2002, 18:16:26)  [GCC 2.96 20000731 (Red Hat
Linux 7.2 2 on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> ''.lower()
Traceback (innermost last):
  File "<stdin>", line 1, in ?
AttributeError: 'string' object has no attribute 'lower'
###

and this looks like the error that you're running into.


If you're stuck using 1.52 and can't upgrade to a newer version, then you
may need to reword things.  The equivalent way of saying:

    if username.lower() in "kyle jason chelsea john cheryl".split():

in 1.52 style would be:

    if string.lower(username) in \
        string.split("kyle jason chelsea john cheryl")

(The line was getting long, so I use a "continuation" character '\' here
to tell Python that there's more stuff on the next line.)




Hope this helps!




From ak@silmarill.org  Mon Jul  8 20:40:28 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 8 Jul 2002 15:40:28 -0400
Subject: [Tutor] bug hunting again
In-Reply-To: <20020708183259.C690D6DB2E@www.fastmail.fm>
References: <20020708183259.C690D6DB2E@www.fastmail.fm>
Message-ID: <20020708194028.GA9777@ak.silmarill.org>

On Mon, Jul 08, 2002 at 06:32:59PM +0000, Kyle Babich wrote:
> Ok now my problem is this:
> 
>   File "hourtracker.py", line 92, in ?
>     if username.lower() in "kyle jason chelsea john cheryl".split():
> AttributeError: 'string' object has no attribute 'lower'
>
You must have a rather old python. Either upgrade or use:

import string
string.lower(username)

> 
> But I don't see what is wrong.
> I have attached a new copy.
> 
> On Mon, 8 Jul 2002 17:50:25 +0100 , alan.gauld@bt.com said:
> > A quick look suggests you don't actually start the 
> > program anywhere in your file.
> > 
> > How are you trying to run it?
> > 
> > > been working on (from my last few messages).  Something is 
> > > stopping the program from running 
> > 
> > What actually happens? Do you get any errors?
> > Either from DOS, Windows or Python?
> > 
> > > Please tell me if you can find what is stopping the program from
> > > running.  Thank you.
> > 
> > Assuming you want it to run by double clicking the file icon
> > you will need something like:
> > 
> > if __name__ == "__main":
> >     hour()
> > 
> > If you are importing it into IDLE(say) then you should 
> > get something back when you type time.hour()
> > 
> > BUT as somebody already pointed out naming things the same 
> > as python module names is a bad idea. When you import 
> > your time module you will hide the python time module.
> > Rename your file to hourtracker.py or something...
> > 
> > Slightly confused and needing more info
> > 
> > Alan G
> > 
> > 
> > 
> > 
> 
> --
> Kyle


-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From dyoo@hkn.eecs.berkeley.edu  Mon Jul  8 20:40:50 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 8 Jul 2002 12:40:50 -0700 (PDT)
Subject: [Tutor] bug hunting again
In-Reply-To: <Pine.LNX.4.44.0207081229390.28440-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0207081239070.28440-100000@hkn.eecs.berkeley.edu>


> If you're stuck using 1.52 and can't upgrade to a newer version, then you
> may need to reword things.  The equivalent way of saying:
>
>     if username.lower() in "kyle jason chelsea john cheryl".split():
>
> in 1.52 style would be:
>
>     if string.lower(username) in \
>         string.split("kyle jason chelsea john cheryl")
>
> (The line was getting long, so I use a "continuation" character '\' here
> to tell Python that there's more stuff on the next line.)



Oh, one other thing: if you do the above, you'll need to put the line:

###
import string
###

at the top of your program, so that Python knows that when we say
'string', we mean the standard 'string' library:

    http://www.python.org/doc/lib/module-string.html


Hope this helps!




From Kyle Babich" <kb@kb5.org  Mon Jul  8 20:47:56 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Mon, 8 Jul 2002 19:47:56 +0000
Subject: [Tutor] bug hunting again
Message-ID: <20020708194756.B6D0F6DA3D@www.fastmail.fm>

I'm using Python 2.2 for Windows.

On Mon, 8 Jul 2002 12:40:50 -0700 (PDT), "Danny Yoo"
<dyoo@hkn.eecs.berkeley.edu> said:
> 
> 
> > If you're stuck using 1.52 and can't upgrade to a newer version, then you
> > may need to reword things.  The equivalent way of saying:
> >
> >     if username.lower() in "kyle jason chelsea john cheryl".split():
> >
> > in 1.52 style would be:
> >
> >     if string.lower(username) in \
> >         string.split("kyle jason chelsea john cheryl")
> >
> > (The line was getting long, so I use a "continuation" character '\' here
> > to tell Python that there's more stuff on the next line.)
> 
> 
> 
> Oh, one other thing: if you do the above, you'll need to put the line:
> 
> ###
> import string
> ###
> 
> at the top of your program, so that Python knows that when we say
> 'string', we mean the standard 'string' library:
> 
>     http://www.python.org/doc/lib/module-string.html
> 
> 
> Hope this helps!
> 
> 
> 
> 
> 

--
Kyle



From ak@silmarill.org  Mon Jul  8 21:17:34 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 8 Jul 2002 16:17:34 -0400
Subject: [Tutor] bug hunting again
In-Reply-To: <20020708194756.B6D0F6DA3D@www.fastmail.fm>
References: <20020708194756.B6D0F6DA3D@www.fastmail.fm>
Message-ID: <20020708201734.GA10081@ak.silmarill.org>

On Mon, Jul 08, 2002 at 07:47:56PM +0000, Kyle Babich wrote:
> I'm using Python 2.2 for Windows.
>
This error really indicates that you're using an old interpreter.. It
could be that you have both 2.2. and an older one installed; and
unbeknownst to you your script runs with the latter.

To make sure, type at the top of your script:

import sys
print "Python version is", sys.version

> 
> On Mon, 8 Jul 2002 12:40:50 -0700 (PDT), "Danny Yoo"
> <dyoo@hkn.eecs.berkeley.edu> said:
> > 
> > 
> > > If you're stuck using 1.52 and can't upgrade to a newer version, then you
> > > may need to reword things.  The equivalent way of saying:
> > >
> > >     if username.lower() in "kyle jason chelsea john cheryl".split():
> > >
> > > in 1.52 style would be:
> > >
> > >     if string.lower(username) in \
> > >         string.split("kyle jason chelsea john cheryl")
> > >
> > > (The line was getting long, so I use a "continuation" character '\' here
> > > to tell Python that there's more stuff on the next line.)
> > 
> > 
> > 
> > Oh, one other thing: if you do the above, you'll need to put the line:
> > 
> > ###
> > import string
> > ###
> > 
> > at the top of your program, so that Python knows that when we say
> > 'string', we mean the standard 'string' library:
> > 
> >     http://www.python.org/doc/lib/module-string.html
> > 
> > 
> > Hope this helps!
> > 
> > 
> > 
> > 
> > 
> 
> --
> Kyle
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From Doug.Shawhan@gecits.ge.com  Mon Jul  8 21:21:52 2002
From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com)
Date: Mon, 8 Jul 2002 16:21:52 -0400
Subject: [Tutor] urllib and urllib2 - better documentation for the sdupit?
Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54C88@msxcvg02itscge.gecits.ge.com>

Urllib and urllib2 seem to have an abundance of goodies for handling nasty
things like proxies. In fact when I look at the info provided:

>>> dir(urllib)
['FancyURLopener', 'MAXFTPCACHE', 'URLopener', '__all__', '__builtins__',
'__doc__', '__file__', '__name__', '__version__', '_fast_quote',
'_fast_safe', '_fast_safe_test', '_ftperrors', '_hostprog', '_localhost',
'_noheaders', '_nportprog', '_passwdprog', '_portprog', '_queryprog',
'_tagprog', '_thishost', '_typeprog', '_urlopener', '_userprog',
'_valueprog', 'addbase', 'addclosehook', 'addinfo', 'addinfourl',
'always_safe', 'basejoin', 'ftpcache', 'ftperrors', 'ftpwrapper',
'getproxies', 'getproxies_environment', 'getproxies_registry', 'localhost',
'main', 'noheaders', 'os', 'pathname2url', 'proxy_bypass', 'quote',
'quote_plus', 'reporthook', 'socket', 'splitattr', 'splitgophertype',
'splithost', 'splitnport', 'splitpasswd', 'splitport', 'splitquery',
'splittag', 'splittype', 'splituser', 'splitvalue', 'stat', 'string', 'sys',
'test', 'test1', 'thishost', 'time', 'toBytes', 'types', 'unquote',
'unquote_plus', 'unwrap', 'url2pathname', 'urlcleanup', 'urlencode',
'urlopen', 'urlretrieve']
>>> dir(urllib2)
['AbstractBasicAuthHandler', 'AbstractDigestAuthHandler',
'AbstractHTTPHandler', 'BaseHandler', 'CacheFTPHandler', 'CustomProxy',
'CustomProxyHandler', 'FTPHandler', 'FileHandler', 'GopherError',
'GopherHandler', 'HTTPBasicAuthHandler', 'HTTPDefaultErrorHandler',
'HTTPDigestAuthHandler', 'HTTPError', 'HTTPHandler', 'HTTPPasswordMgr',
'HTTPPasswordMgrWithDefaultRealm', 'HTTPRedirectHandler', 'OpenerDirector',
'OpenerFactory', 'ProxyBasicAuthHandler', 'ProxyDigestAuthHandler',
'ProxyHandler', 'Request', 'StringIO', 'URLError', 'UnknownHandler',
'__builtins__', '__doc__', '__file__', '__name__', '__version__', '_opener',
'addinfourl', 'base64', 'build_opener', 'encode_digest', 'ftplib',
'ftpwrapper', 'getproxies', 'gopherlib', 'httplib', 'inspect',
'install_opener', 'localhost', 'md5', 'mimetools', 'mimetypes', 'noheaders',
'os', 'parse_http_list', 'parse_keqv_list', 'posixpath', 're', 'rfc822',
'sha', 'socket', 'splitattr', 'splitgophertype', 'splithost', 'splitport',
'splitquery', 'splittype', 'stat', 'sys', 'time', 'types', 'unquote',
'unwrap', 'url2pathname', 'urlopen', 'urlparse']

...everything I could possibly want (with the exception of SSL?) seems to be
there... the only problem is, I can't find documentation/examples that
covers more than a few of the options. I read Fredrik Lundh's entry on
urllib in Python Standard Library and found the basic examples for reading
and returning each element of a page as a list, which is in itself very
handy.

Does anyone have a good source for step-by-step usage of all the
functionality provided by these modules?

Thanks!

d



From kemu@linuxmail.org  Mon Jul  8 21:42:45 2002
From: kemu@linuxmail.org (Jonas Geiregat)
Date: Tue, 09 Jul 2002 04:42:45 +0800
Subject: [Tutor] py magazine
Message-ID: <20020708204245.4611.qmail@linuxmail.org>

does anyone ever subscribe to that magazine py and got the first edition in his mail box, if you do still got that edition ?
-- 
Get your free email from www.linuxmail.org 


Powered by Outblaze



From rob@uselesspython.com  Mon Jul  8 21:51:47 2002
From: rob@uselesspython.com (Rob)
Date: Mon, 08 Jul 2002 15:51:47 -0500
Subject: [Tutor] py magazine
References: <20020708204245.4611.qmail@linuxmail.org>
Message-ID: <3D29FB63.2030202@uselesspython.com>

I'm not sure I completely follow your question, but I have the first 
issue of Py.

Rob Andrews
http://uselesspython.com

Jonas Geiregat wrote:

 > does anyone ever subscribe to that magazine py and got the first
 > edition in his mail box, if you do still got that edition ?
 >


-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show





From pythontutor@venix.com  Mon Jul  8 21:49:19 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Mon, 08 Jul 2002 16:49:19 -0400
Subject: [Tutor] bug hunting again
References: <20020708191653.9779B6D9A9@www.fastmail.fm>
Message-ID: <3D29FACF.4090908@venix.com>

Used:
	kyle.current
	1 minute

Traceback (most recent call last):
   File "F:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript
     exec codeObject in __main__.__dict__
   File "E:\ptg\campgrnd\hourtracker.py", line 97, in ?
     custom()
   File "E:\ptg\campgrnd\hourtracker.py", line 41, in custom
     loccu.close()
NameError: global name 'loccu' is not defined

I changed loccu to logcu and tried again

The current time is 04:43:38PM Eastern Daylight Time
Traceback (most recent call last):
   File "F:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript
     exec codeObject in __main__.__dict__
   File "E:\ptg\campgrnd\hourtracker.py", line 97, in ?
     custom()
   File "E:\ptg\campgrnd\hourtracker.py", line 47, in custom
     hour2()
   File "E:\ptg\campgrnd\hourtracker.py", line 68, in hour2
     time.sleep( sleeptime*60 )
NameError: global name 'sleeptime' is not defined

I think you are all set!  You will want to rethink things a bit to
reduce the number of global variables.

Kyle Babich wrote:

> When you run it and it asks for a name put in one of the usernames with
> the .custom at the end and any amount of time.  That's where the error
> comes in.
> 
> On Mon, 08 Jul 2002 14:58:12 -0400, "Lloyd Kvam"
> <pythontutor@venix.com> said:
> 
>>That worked here!?
>>
>>Kyle Babich wrote:
>>
>>
>>>Ok now my problem is this:
>>>
>>>  File "hourtracker.py", line 92, in ?
>>>    if username.lower() in "kyle jason chelsea john cheryl".split():
>>>AttributeError: 'string' object has no attribute 'lower'
>>>
>>>But I don't see what is wrong.
>>>I have attached a new copy.
>>>
>>>On Mon, 8 Jul 2002 17:50:25 +0100 , alan.gauld@bt.com said:
>>>
>>>
>>>>A quick look suggests you don't actually start the 
>>>>program anywhere in your file.
>>>>
>>>>How are you trying to run it?
>>>>
>>>>
>>>>
>>>>>been working on (from my last few messages).  Something is 
>>>>>stopping the program from running 
>>>>>
>>>>>
>>>>What actually happens? Do you get any errors?
>>>>Either from DOS, Windows or Python?
>>>>
>>>>
>>>>
>>>>>Please tell me if you can find what is stopping the program from
>>>>>running.  Thank you.
>>>>>
>>>>>
>>>>Assuming you want it to run by double clicking the file icon
>>>>you will need something like:
>>>>
>>>>if __name__ == "__main":
>>>>   hour()
>>>>
>>>>If you are importing it into IDLE(say) then you should 
>>>>get something back when you type time.hour()
>>>>
>>>>BUT as somebody already pointed out naming things the same 
>>>>as python module names is a bad idea. When you import 
>>>>your time module you will hide the python time module.
>>>>Rename your file to hourtracker.py or something...
>>>>
>>>>Slightly confused and needing more info
>>>>
>>>>Alan G
>>>>
>>>>
>>>>
>>>>
>>>>
>>>>
>>>--
>>>Kyle
>>>
>>>
>>
>>-- 
>>Lloyd Kvam
>>Venix Corp.
>>1 Court Street, Suite 378
>>Lebanon, NH 03766-1358
>>
>>voice: 
>>603-443-6155
>>fax: 
>>801-459-9582
>>
>>
>>
>>
>>
>>
> 
> --
> Kyle
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From Michael.Baker@IGT.com  Mon Jul  8 22:11:27 2002
From: Michael.Baker@IGT.com (Baker.Michael)
Date: Mon, 8 Jul 2002 14:11:27 -0700
Subject: [Tutor] zip archive comparison
Message-ID: <5A021171E87BD411AF7700508B6940D00347C66D@anchorgaming.anchorgaming.com>

hi all.

i need to compare two zip archives (created with python) and generate a new
archive containing new or modified files. each archive has the same internal
directory structure (with subdirs). i can easily extract new filenames
through the zipfile module and get date & time through the date_time
attribute, but i don't find a easy way to compare files with like names. i
have used dircmp objects created from the filecp module for directory
comparisons, but i don't find an easy way to check subdirs. i have also used
os.path.getmtime for file-by-file comparisons, but this doesn't help with
subdirs.

is there another module/function that i can use for this??

i need something that handles recursion like os.makedirs, but more like
os.comparedirs :)

thanks in advance



From phthenry@earthlink.net  Mon Jul  8 22:53:33 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Mon, 8 Jul 2002 17:53:33 -0400
Subject: [Tutor] replacing something on last line
In-Reply-To: <20020708071733.GA4421@ak.silmarill.org>
References: <20020707161112.D2438@localhost.localdomain> <20020707203246.GA1067@ak.silmarill.org> <20020708004151.B15016@localhost.localdomain> <20020708071733.GA4421@ak.silmarill.org>
Message-ID: <20020708175333.D15016@localhost.localdomain>

On Mon, Jul 08, 2002 at 03:17:33AM -0400, Andrei Kulakov wrote:

> rfind from another post is more straighforward.. but you could also use
> reverse method of lists: my_list.reverse(). List could be a list of
> lines in files or a list of words in that line (you'd have to use
> split() string method).
> 

Thanks Andrei (and Gregor too).

The problems with these two methods is that you have to read the
whole file in at once. One of my files is 1.8 megs. Is this too
big? (I have 64 megs of ram.)

I devised my own way using a linux utility called tac (which you
probably know about). Tac reverses the lines in a file. I am
working with an rtf file, and the character I want to substitute
almost always occurs by itself on the last line of the file.
However, if it didn't, I could use Gergor's method, once I have
reversed the file:

os.system('tac file1 > file2)
readObj = open(file2,'r')
line = 1
found_flag = 0
while line:
	if not found_flag:
		result = re.search('}'),line
		if result != None:
			##substitute the last occurence as Gregor showed
			found_flag = 1
			print line, # or write it to another file
	else:
		print line, # or write it to another file
		


This seems like a dirty way to substitute, but it works. Is there
a python way of reversing the lines in a file without reading the
whole file in?

Paul

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From phthenry@earthlink.net  Mon Jul  8 22:56:10 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Mon, 8 Jul 2002 17:56:10 -0400
Subject: [Tutor] substituting with a group
In-Reply-To: <Pine.LNX.4.44.0207080101420.16445-100000@hkn.eecs.berkeley.edu>
References: <20020708003554.A15016@localhost.localdomain> <Pine.LNX.4.44.0207080101420.16445-100000@hkn.eecs.berkeley.edu>
Message-ID: <20020708175609.E15016@localhost.localdomain>

On Mon, Jul 08, 2002 at 01:04:37AM -0700, Danny Yoo wrote:
> From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
>
> Instead of using "$1", Python's regular expression engine uses '\1'
> instead.  So you can do something like:
> 
> ###
> >>> re.sub(r'(\w+) (\w+)', r'\2 \1', 'hello world this is a test')
> 'world hello is this test a'
> ###
> 
> 
> Hope this helps!
> 

Yes! (The previous post was also helpful.)

Thanks

Paul

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From ak@silmarill.org  Mon Jul  8 23:06:39 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 8 Jul 2002 18:06:39 -0400
Subject: [Tutor] replacing something on last line
In-Reply-To: <20020708175333.D15016@localhost.localdomain>
References: <20020707161112.D2438@localhost.localdomain> <20020707203246.GA1067@ak.silmarill.org> <20020708004151.B15016@localhost.localdomain> <20020708071733.GA4421@ak.silmarill.org> <20020708175333.D15016@localhost.localdomain>
Message-ID: <20020708220639.GA11055@ak.silmarill.org>

On Mon, Jul 08, 2002 at 05:53:33PM -0400, Paul Tremblay wrote:
> On Mon, Jul 08, 2002 at 03:17:33AM -0400, Andrei Kulakov wrote:
> 
> > rfind from another post is more straighforward.. but you could also use
> > reverse method of lists: my_list.reverse(). List could be a list of
> > lines in files or a list of words in that line (you'd have to use
> > split() string method).
> > 
> 
> Thanks Andrei (and Gregor too).
> 
> The problems with these two methods is that you have to read the
> whole file in at once. One of my files is 1.8 megs. Is this too
> big? (I have 64 megs of ram.)
> 
> I devised my own way using a linux utility called tac (which you
> probably know about). Tac reverses the lines in a file. I am
> working with an rtf file, and the character I want to substitute
> almost always occurs by itself on the last line of the file.
> However, if it didn't, I could use Gergor's method, once I have
> reversed the file:
> 
> os.system('tac file1 > file2)
> readObj = open(file2,'r')
> line = 1
> found_flag = 0
> while line:
> 	if not found_flag:
> 		result = re.search('}'),line
> 		if result != None:
> 			##substitute the last occurence as Gregor showed
> 			found_flag = 1
> 			print line, # or write it to another file
> 	else:
> 		print line, # or write it to another file
> 		
> 
> 
> This seems like a dirty way to substitute, but it works. Is there
> a python way of reversing the lines in a file without reading the
> whole file in?
>
Yes but it's kind of complex. You have to f.seek() to seek to almost
end of file, then file.read(block) then you can read the block and see
if that word's in there.

But since you want to replace it, you'd still have to read all the file
in and re-write it to disk; besides, 1.8mb is no big deal, but test how
long it takes..

> 
> Paul
> 
> -- 
> 
> ************************
> *Paul Tremblay         *
> *phthenry@earthlink.net*
> ************************
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From kemu@linuxmail.org  Tue Jul  9 02:13:24 2002
From: kemu@linuxmail.org (Jonas Geiregat)
Date: Tue, 09 Jul 2002 09:13:24 +0800
Subject: [Tutor] python from shell
Message-ID: <20020709011324.9547.qmail@linuxmail.org>

is there a way I could start my python appz from command line just like other normall apps
ex. vim => and vim starts 

where should I place my .py file ?
what changes do I have to make in my .py file or somewhere else ?


-- 
Get your free email from www.linuxmail.org 


Powered by Outblaze



From guillermo.fernandez@epfl.ch  Tue Jul  9 02:27:40 2002
From: guillermo.fernandez@epfl.ch (Guillermo Fernandez)
Date: Tue, 09 Jul 2002 10:57:40 +0930
Subject: [Tutor] python from shell
References: <20020709011324.9547.qmail@linuxmail.org>
Message-ID: <3D2A3C0C.AC5C2935@epfl.ch>

> is there a way I could start my python appz from command line just like other normall apps
> ex. vim => and vim starts
Yes

> where should I place my .py file ?
In your path. Your path is the variable PATH. Try the command "echo
$PATH" in your terminal. That's the directories where your shell is
going to look for the program you started.

You can also put it in a directory of your choice and add this directory
to your path, but it's easier to directly put it in a directory already
existing in your path variable.

> what changes do I have to make in my .py file or somewhere else ?
You have to add #! and the path of your python command in the first line
of your code. In my case is:
#! /usr/bin/python

You can even get rid of the .py extension!

Than you have to make the file executable (chmod 755 file.py) and put
these file in one of your directories of your path.
Typically, I put my files in /usr/local/bin/

Exacmple:
>> cat > example
#! /usr/bin/python
print "Hello world"
^C
>> cat example
#! /usr/bin/python
print "Hello world"
>> ls -l example
-rw-r--r--    1 guille      users        8843 jui  9 10:55 example
>> chmod 755 example
>> ls -l example
-rwxr-xr-x    1 guille      users        8843 jui  9 10:55 example
>> mv example /usr/local/bin/
>> example
Hello world
>>

Guille



From joel@prettyhipprogramming.com  Tue Jul  9 02:35:33 2002
From: joel@prettyhipprogramming.com (Joel Ricker)
Date: Mon, 8 Jul 2002 21:35:33 -0400
Subject: [Tutor] time.sleep problem
Message-ID: <007801c226e8$eb4aa100$e1e03942@joeltklrijxxms>

This is a multi-part message in MIME format.

------=_NextPart_000_0075_01C226C7.6404F8B0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Activestate Python 2.2.1, Windows 2000

I'm working on a script that uses time.sleep() but have found that on my =
installation, any sleep value over a few seconds seems to hang the =
script.  Not only does it not seem to respond anymore, it doesn't =
respond to ctrl+c.

Anybody else having this problem? Did I find a bug or could I just be =
doing something stupid?

My code, just in case:

    wait =3D None
   =20
    for o, a in opts:
        if o in ("-t", "--time"):
            wait =3D int(a) * 60
   =20
    while (1):
        addr =3D socket.gethostbyname(socket.getfqdn())
        print "The current address is", addr
        time.sleep(wait * 60)  =20

Tnx
Joel

------=_NextPart_000_0075_01C226C7.6404F8B0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2479.6" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Activestate Python 2.2.1, Windows =
2000</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I'm working on a script that uses =
time.sleep() but=20
have found that on my installation, any sleep value over a few seconds =
seems to=20
hang the script.&nbsp; Not only does it not seem to respond anymore, it =
doesn't=20
respond to ctrl+c.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Anybody else having this =
problem?&nbsp;Did I find a=20
bug or could I just be doing something stupid?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>My code, just in case:</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;wait =3D=20
None<BR>&nbsp;&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp; for o, a in=20
opts:<BR>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if o in ("-t",=20
"--time"):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;=20
wait =3D int(a) * 60<BR>&nbsp;&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp; while=20
(1):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; addr =3D=20
socket.gethostbyname(socket.getfqdn())<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;=20
print "The current address is",=20
addr<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; time.sleep(wait *=20
60)&nbsp;&nbsp; </FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Tnx</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Joel</FONT></DIV></BODY></HTML>

------=_NextPart_000_0075_01C226C7.6404F8B0--




From stuart@sharedreality.org  Tue Jul  9 02:33:44 2002
From: stuart@sharedreality.org (Stuart Smith)
Date: Tue, 09 Jul 2002 02:33:44 +0100
Subject: [Tutor] py magazine
In-Reply-To: <3D29FB63.2030202@uselesspython.com>
References: <20020708204245.4611.qmail@linuxmail.org>
Message-ID: <5.1.1.6.0.20020709023120.00b59878@sharedreality.org>

I also have the first issue of Py - actually I have two copies of it as the 
guy sent out an extra one by mistake.  Funnily enough the same mistake 
happened with the second issue too, so I have a second copy of that one as 
well.

At 15:51 08/07/2002 -0500, Rob wrote:
>I'm not sure I completely follow your question, but I have the first issue 
>of Py.
>
>Rob Andrews
>http://uselesspython.com
>
>Jonas Geiregat wrote:
>
> > does anyone ever subscribe to that magazine py and got the first
> > edition in his mail box, if you do still got that edition ?
> >




From dylan.belsey@baesystems.com  Tue Jul  9 02:46:01 2002
From: dylan.belsey@baesystems.com (BELSEY, Dylan)
Date: Tue, 9 Jul 2002 11:16:01 +0930
Subject: [Tutor] time.sleep problem
Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B96320A1@WTNTEX1>

Is "a" supposed to be seconds?  If so, then by the time you do the sleep()
call the value will be in the hours range, having multiplied by 3600.
Haven't checked what the possible range is for the arg in the sleep() fn.
You may want to check this out too.
HTH

-----Original Message-----
From: Joel Ricker [mailto:joel@prettyhipprogramming.com]
Sent: Tuesday, 9 July 2002 11:36
To: tutor@python.org
Subject: [Tutor] time.sleep problem


Activestate Python 2.2.1, Windows 2000
 
I'm working on a script that uses time.sleep() but have found that on my
installation, any sleep value over a few seconds seems to hang the script.
Not only does it not seem to respond anymore, it doesn't respond to ctrl+c.
 
Anybody else having this problem? Did I find a bug or could I just be doing
something stupid?
 
My code, just in case:
 
    wait = None
    
    for o, a in opts:
        if o in ("-t", "--time"):
            wait = int(a) * 60
    
    while (1):
        addr = socket.gethostbyname(socket.getfqdn())
        print "The current address is", addr
        time.sleep(wait * 60)   
 
Tnx
Joel




From sarmstrong13@mac.com  Tue Jul  9 02:44:07 2002
From: sarmstrong13@mac.com (SA)
Date: Mon, 08 Jul 2002 20:44:07 -0500
Subject: [Tutor] CGI Question
Message-ID: <B94FAA17.90E2%sarmstrong13@mac.com>

Hi Everyone-

The following is the test code in python:

#!/usr/bin/env python

import cgi

print "Content-Type: text/plain\n\n"

The_Form = cgi.parse_qs(pageID)

for pageID in The_Form.keys():
    print "The text file is: " + pageID
    
print "Finished!"

The following is my html code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html lang="en">
<head>
    <title>CGI Test</title>
    <meta name="generator" content="BBEdit 6.5.2">
</head>
<body>
Click on the link below to test your CGI:
<a href="http://localhost/cgi-bin/test2?pageID=testtext"
title="TestFile">TestFile</a>
</body>
</html>

The file testtext just has the single line:
Hello World!

When I click on the link I get a server error message. I have everythin
working correctly because I can run some other python cgi scripts that
display text messages no problem. The cgi program has the correct executable
permissions and is located in the correct directory.

So my question is, what am I doing wrong?

Parse_qs should take the pageID and produce a dictionary with pageID as the
key and testtext as the value, correct?

Do I need to read the value of testtext and store it in a variable to be
written to the display?

Thanks.
SA




From joel@prettyhipprogramming.com  Tue Jul  9 02:54:13 2002
From: joel@prettyhipprogramming.com (Joel Ricker)
Date: Mon, 8 Jul 2002 21:54:13 -0400
Subject: [Tutor] time.sleep problem
References: <86C3892A0C52D411AF5000A0C9EAA3B96320A0@WTNTEX1>
Message-ID: <00c801c226eb$86b564c0$e1e03942@joeltklrijxxms>

> Is "a" supposed to be seconds?  If so, then by the time you do the sleep()
> call the value will be in the hours range, having multiplied by 3600.
> Haven't checked what the possible range is for the arg in the sleep() fn.
> You may want to check this out too.
> HTH

Doh!  Can't believe I missed that.  I was multiplying in the call to sleep
but realized why shouldn't I do it when I initalize it from the options but
never took the sleep multiplier out.  Leave it to me to assume it must be a
bug :)

BTW, while running should it be that unresponsive?  It will still pick up
shutdown signals right?

Joel




From dylan.belsey@baesystems.com  Tue Jul  9 03:08:26 2002
From: dylan.belsey@baesystems.com (BELSEY, Dylan)
Date: Tue, 9 Jul 2002 12:08:26 +1000
Subject: [Tutor] time.sleep problem
Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B96320A2@WTNTEX1>

Just tried the following code in a DOS window: 

C:\>python
Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> import time
>>> time.sleep(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyboardInterrupt
>>>

	While doing the sleep I tried CTRL-C and you are right, it doesn't
react immediately. When trying it another time, it waits till the code
finishes and then returns me to the DOS prompt.  Perhaps it is an issue with
the processor or thread being caught/held in the sleep call and being unable
to respond to the shutdown signal immediately.  However, I am out of my
depth here so don't take it as gospel.  Undoubtedly someone else on the list
will have a more coherent explanation. 

-----Original Message-----
From: Joel Ricker [mailto:joel@prettyhipprogramming.com]
Sent: Tuesday, 9 July 2002 11:54
To: BELSEY, Dylan; tutor@python.org
Subject: Re: [Tutor] time.sleep problem


> Is "a" supposed to be seconds?  If so, then by the time you do the sleep()
> call the value will be in the hours range, having multiplied by 3600.
> Haven't checked what the possible range is for the arg in the sleep() fn.
> You may want to check this out too.
> HTH

Doh!  Can't believe I missed that.  I was multiplying in the call to sleep
but realized why shouldn't I do it when I initalize it from the options but
never took the sleep multiplier out.  Leave it to me to assume it must be a
bug :)

BTW, while running should it be that unresponsive?  It will still pick up
shutdown signals right?

Joel



From joel@prettyhipprogramming.com  Tue Jul  9 03:20:48 2002
From: joel@prettyhipprogramming.com (Joel Ricker)
Date: Mon, 8 Jul 2002 22:20:48 -0400
Subject: [Tutor] time.sleep problem
References: <86C3892A0C52D411AF5000A0C9EAA3B96320A2@WTNTEX1>
Message-ID: <00d801c226ef$3d53b350$e1e03942@joeltklrijxxms>

>  Perhaps it is an issue with
> the processor or thread being caught/held in the sleep call and being
unable
> to respond to the shutdown signal immediately.  However, I am out of my
> depth here so don't take it as gospel.  Undoubtedly someone else on the
list
> will have a more coherent explanation.

According to the documentation, any caught signal should "wake" the script
back up.  But I'm with you, I'm sure someone much more talented than me will
have the answer.

Joel




From tim.one@comcast.net  Tue Jul  9 04:28:31 2002
From: tim.one@comcast.net (Tim Peters)
Date: Mon, 08 Jul 2002 23:28:31 -0400
Subject: [Tutor] time.sleep problem
In-Reply-To: <86C3892A0C52D411AF5000A0C9EAA3B96320A2@WTNTEX1>
Message-ID: <LNBBLJKPBEHFEDALKOLCOEAAADAB.tim.one@comcast.net>

[BELSEY, Dylan]
> ...
> 	While doing the sleep I tried CTRL-C and you are right, it doesn't
> react immediately. When trying it another time, it waits till the code
> finishes and then returns me to the DOS prompt.  Perhaps it is an
> issue with the processor or thread being caught/held in the sleep call
> and  being unable to respond to the shutdown signal immediately.

time.sleep() on Windows is implemented by calling Microsoft's Sleep()
function (part of the Win32 API).  The Win32 Sleep() can't be interrupted.
Here are some comments from the floatsleep() function in Python's
timemodule.c:

#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
...
#ifdef EINTR
...
#else
...
#endif
#elif defined(macintosh)
#define MacTicks	(* (long *)0x16A)
...
		/* XXX Should call some yielding function here */
...
#elif defined(__WATCOMC__) && !defined(__QNX__)
	/* XXX Can't interrupt this sleep */
...
#elif defined(MS_WINDOWS)
...
		/* XXX Can't interrupt this sleep */
...
#elif defined(PYOS_OS2)
	/* This Sleep *IS* Interruptable by Exceptions */
...
#elif defined(__BEOS__)
	/* This sleep *CAN BE* interrupted. */
...
#elif defined(RISCOS)
...
	/* This sleep *CAN BE* interrupted. */
...
#elif defined(PLAN9)
...
		/* This sleep *CAN BE* interrupted. */
...
#else
	/* XXX Can't interrupt this sleep */
...
#endif

You're in the MS_WINDOWS part of this miserable maze; just be thankful
you're on the outside looking in <wink>.




From adi.clepcea@sysrom.ro  Tue Jul  9 05:44:17 2002
From: adi.clepcea@sysrom.ro (Adi Clepcea)
Date: Tue, 9 Jul 2002 07:44:17 +0300 (E. Europe Daylight Time)
Subject: [Tutor] Thanks for ODBC tip
Message-ID: <3D2A6A21.000005.00988@adi-clepcea>

--------------Boundary-00=_T5TY6RO0000000000000
Content-Type: Text/Plain;
  charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

You were right, the problem was that I was using a user not a system data=
base.
Thanks Derrick!
Adi
--------------Boundary-00=_T5TY6RO0000000000000
Content-Type: Text/HTML;
  charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<html>
<head>
<meta name=3D"GENERATOR" content=3D"IncrediMail 1.0">
</head>

<BODY background=3D"" bgColor=3D#ffffff style=3D"BACKGROUND-POSITION: 0px=
 0px; FONT-SIZE: 10pt; MARGIN: 1px; FONT-FAMILY: Arial" scroll=3Dyes ORGY=
POS=3D"0">
<TABLE border=3D0 cellPadding=3D0 cellSpacing=3D0 id=3DINCREDIMAINTABLE w=
idth=3D"95%">
<TR>

<TD id=3DINCREDITEXTREGION width=3D"100%" style=3D"PADDING-RIGHT: 7px; PA=
DDING-LEFT: 7px; FONT-SIZE: 10pt; FONT-FAMILY: Arial"=20
   >
      <DIV>You were right, the problem was that I was using a user not a =
system=20
      database.</DIV>
      <DIV>Thanks Derrick!</DIV>
      <DIV>Adi</DIV></TD>
</TR>

<TR>
<TD id=3DINCREDIFOOTER width=3D"100%">

=09<TABLE cellPadding=3D0 cellSpacing=3D0 width=3D"100%">
=09<TR>
=09<TD width=3D"100%"></TD>
=09<TD align=3Dmiddle id=3DINCREDISOUND vAlign=3Dbottom></TD>
=09<TD align=3Dmiddle id=3DINCREDIANIM vAlign=3Dbottom></TD>
=09</TR>
=09</TABLE>

</TD>
</TR>

</TABLE><SPAN=20
id=3DIncrediStamp><SPAN dir=3Dltr><FONT face=3D"Arial, Helvetica, sans-se=
rif"=20
size=3D2>_________________________________________________<BR><FONT=20
face=3D"Comic Sans MS" size=3D2><I>IncrediMail</I> - <B>Email has finally=
=20
evolved</B> - </FONT><A href=3D"http://www.incredimail.com/imstampa.html"=
><FONT=20
face=3D"Times New Roman" size=3D3><B><U>Click=20
Here</U></B></FONT></A></SPAN></SPAN></FONT>
</BODY>
</html>
--------------Boundary-00=_T5TY6RO0000000000000--




From joel@prettyhipprogramming.com  Tue Jul  9 06:19:20 2002
From: joel@prettyhipprogramming.com (Joel Ricker)
Date: Tue, 9 Jul 2002 01:19:20 -0400
Subject: [Tutor] time.sleep problem
References: <LNBBLJKPBEHFEDALKOLCOEAAADAB.tim.one@comcast.net>
Message-ID: <00e601c22708$2e4aa260$e1e03942@joeltklrijxxms>

From: "Tim Peters" <tim.one@comcast.net>

> #elif defined(MS_WINDOWS)
> ...
> /* XXX Can't interrupt this sleep */

Ah, well I guess sleep() is out.

My plan is to have this script automatically start up when the system is
turned on and continue indefinitely until the system is shutdown,
periodically running a portion of code.  Granted when Windows wants to shut
something down, it will but I'm hoping for a more graceful solution.

Should I just go with a timing solution, using time.clock() maybe to
accumulate how much time has passed and check it against how many minutes to
wait?

Joel




From sarmstrong13@mac.com  Tue Jul  9 13:40:04 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 09 Jul 2002 07:40:04 -0500
Subject: [Tutor] CGI Question
In-Reply-To: <B94FAA17.90E2%sarmstrong13@mac.com>
Message-ID: <B95043D4.9101%sarmstrong13@mac.com>

I've now managed to get the script to work part way. I got rid of the server
error by changing:
#!/usr/bin/env python

To

#!/sw/bin/python

Sw/bin is the directory where my default python is located. For some reason
my Apache setup chokes on the /usr/bin/env executable.

So this fixes the server error. I then set the program to display the value
for the key "pageID", but what I get is a blank page. This makes me wonder
if the value is being passed to the key? Once again the href portion of the
html is:

<a href="http://localhost/cgi-bin/test2?pageID=testtext"
title="TestFile">TestFile</a>

When I click on the link it redirects me to the python script and the script
is being executed, but the value for the dictionary key pageID is not being
displayed.

Below is the test script I wrote:

#!/sw/bin/python

import cgi
import re


print "Content-Type: text/plain\n\n"

The_Form = cgi.FieldStorage()

for pageID in The_Form.keys():
    print "The text file is: " + pageID
    
print "Finished!"

Any ideas on what I'm doing wrong and why the script is not receiving the
value 'testtext'?

Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me


On 7/8/02 8:44 PM, "SA" <sarmstrong13@mac.com> wrote:
> When I click on the link I get a server error message. I have everythin
> working correctly because I can run some other python cgi scripts that
> display text messages no problem. The cgi program has the correct executable
> permissions and is located in the correct directory.
> 
> So my question is, what am I doing wrong?
> 
> Parse_qs should take the pageID and produce a dictionary with pageID as the
> key and testtext as the value, correct?
> 
> Do I need to read the value of testtext and store it in a variable to be
> written to the display?
> 
> Thanks.
> SA
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




From scot@possum.in-berlin.de  Tue Jul  9 13:37:22 2002
From: scot@possum.in-berlin.de (Scot W. Stevenson)
Date: Tue, 9 Jul 2002 14:37:22 +0200
Subject: [Tutor] python from shell
In-Reply-To: <3D2A3C0C.AC5C2935@epfl.ch>
References: <20020709011324.9547.qmail@linuxmail.org> <3D2A3C0C.AC5C2935@epfl.ch>
Message-ID: <200207091437.22333.scot@possum.in-berlin.de>

Hello Guillermo,=20

> You have to add #! and the path of your python command in the first lin=
e
> of your code. In my case is:
> #! /usr/bin/python

I've been using=20

#!/usr/bin/env python

instead with no ill effects so far - which, if I understand correctly,=20
gives the program the environment variables, too.

Y, Scot

--=20
  Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany




From sarmstrong13@mac.com  Tue Jul  9 15:18:25 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 09 Jul 2002 09:18:25 -0500
Subject: [Tutor] python from shell
In-Reply-To: <200207091437.22333.scot@possum.in-berlin.de>
Message-ID: <B9505AE1.910A%sarmstrong13@mac.com>

On 7/9/02 7:37 AM, "Scot W. Stevenson" <scot@possum.in-berlin.de> wrote:

> Hello Guillermo, 
> 
>> You have to add #! and the path of your python command in the first line
>> of your code. In my case is:
>> #! /usr/bin/python
> 
> I've been using 
> 
> #!/usr/bin/env python
> 
> instead with no ill effects so far - which, if I understand correctly,
> gives the program the environment variables, too.
> 
> Y, Scot
The only problem I've seen with this so far is when I write a cgi script.
For some reason /usr/bin/env chokes my Apache server and spews an error. In
a regular python script, this works fine for me. I just changed that line to
the direct route to python for my cgi scripts.

Good Luck.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me




From terjeja@hotmail.com  Tue Jul  9 15:36:02 2002
From: terjeja@hotmail.com (Terje Johan Abrahamsen)
Date: Tue, 09 Jul 2002 14:36:02 +0000
Subject: [Tutor] Comparing lists
Message-ID: <F29Kljq65Rn8P5o7P6u00000e60@hotmail.com>

I have two lists of different length. Actually each list can differ in 
lenght every time. For example lista = [12, 34, 56] & listb = [14, 16, 34, 
81]. What I now need to do is to check if the lists have one or more common 
numbers. In this case 34 exists in each list. Then I would like the function 
to somehow indicate this. Does it exist a simple way to do this? I have made 
a somehow functioning function that does this, but it is probably about 
50-60 lines. (If lista[0] == listb[0], if lista[1] == listb[0] and so 
forth....)

Any suggestions?

Thanks,
Terje



_________________________________________________________________
Join the world’s largest e-mail service with MSN Hotmail. 
http://www.hotmail.com




From rob@uselesspython.com  Tue Jul  9 15:49:22 2002
From: rob@uselesspython.com (Rob)
Date: Tue, 09 Jul 2002 09:49:22 -0500
Subject: [Tutor] Comparing lists
References: <F29Kljq65Rn8P5o7P6u00000e60@hotmail.com>
Message-ID: <3D2AF7F2.4090404@uselesspython.com>

Are you trying to find out if 34 (or whatever else) exists in both lists 
*at all* or in the same place?

 >>> lista = [34, 42, 13]
 >>> listb = [42, 13, 34]

These two lists, for instance, contain all the same values, but they are 
not identical due to the placement of the 34.

 >>> if lista == listb:
	print 'equal'
elif lista != listb:
	print 'inequal'

	
inequal

Rob
http://uselesspython.com

Terje Johan Abrahamsen wrote:

> I have two lists of different length. Actually each list can differ in 
> lenght every time. For example lista = [12, 34, 56] & listb = [14, 16, 
> 34, 81]. What I now need to do is to check if the lists have one or more 
> common numbers. In this case 34 exists in each list. Then I would like 
> the function to somehow indicate this. Does it exist a simple way to do 
> this? I have made a somehow functioning function that does this, but it 
> is probably about 50-60 lines. (If lista[0] == listb[0], if lista[1] == 
> listb[0] and so forth....)
> 
> Any suggestions?
> 
> Thanks,
> Terje
> 
> 
> 
> _________________________________________________________________
> Join the world's largest e-mail service with MSN Hotmail. 
> http://www.hotmail.com
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show





From terjeja@hotmail.com  Tue Jul  9 15:55:28 2002
From: terjeja@hotmail.com (Terje Johan Abrahamsen)
Date: Tue, 09 Jul 2002 14:55:28 +0000
Subject: [Tutor] Comparing lists
Message-ID: <F13oyNW3FAcYA6aEdHy0000ada6@hotmail.com>

I am trying to find out if there is some number that exists in both lists. 
It doesn't matter if they are in the same place or not. I just want to find 
if some number exists in both lists, or if all numbers differs from all 
numbers in the other list.


>Are you trying to find out if 34 (or whatever else) exists in both lists
>*at all* or in the same place?
>
> >>> lista = [34, 42, 13]
> >>> listb = [42, 13, 34]
>
>These two lists, for instance, contain all the same values, but they are
>not identical due to the placement of the 34.
>
> >>> if lista == listb:
>	print 'equal'
>elif lista != listb:
>	print 'inequal'
>
>
>inequal
>
>Rob
>http://uselesspython.com
>
>Terje Johan Abrahamsen wrote:
>
>>I have two lists of different length. Actually each list can differ in
>>lenght every time. For example lista = [12, 34, 56] & listb = [14, 16,
>>34, 81]. What I now need to do is to check if the lists have one or more
>>common numbers. In this case 34 exists in each list. Then I would like
>>the function to somehow indicate this. Does it exist a simple way to do
>>this? I have made a somehow functioning function that does this, but it
>>is probably about 50-60 lines. (If lista[0] == listb[0], if lista[1] ==
>>listb[0] and so forth....)
>>
>>Any suggestions?
>>
>>Thanks,
>>Terje
>>
>>
>>
>>_________________________________________________________________
>>Join the world's largest e-mail service with MSN Hotmail.
>>http://www.hotmail.com
>>
>>
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>
>
>--
>"Giving the Linus Torvalds Award to the Free Software Foundation is a
>bit like giving the Han Solo Award to the Rebel Alliance."
>--Richard Stallman at the 1999 LinuxWorld show
>
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor




_________________________________________________________________
MSN Photos is the easiest way to share and print your photos: 
http://photos.msn.com/support/worldwide.aspx




From rob@uselesspython.com  Tue Jul  9 16:01:07 2002
From: rob@uselesspython.com (Rob)
Date: Tue, 09 Jul 2002 10:01:07 -0500
Subject: [Fwd: Re: [Tutor] Comparing lists]
Message-ID: <3D2AFAB3.5020601@uselesspython.com>

From: terjeja@hotmail.com

-------- Original Message --------

I am trying to find out if there is some number that exists in both lists.
It doesn't matter if they are in the same place or not. I just want to find
if some number exists in both lists, or if all numbers differs from all
numbers in the other list.


 >Are you trying to find out if 34 (or whatever else) exists in both lists
 >*at all* or in the same place?
 >
 > >>> lista = [34, 42, 13]
 > >>> listb = [42, 13, 34]
 >
 >These two lists, for instance, contain all the same values, but they are
 >not identical due to the placement of the 34.
 >
 > >>> if lista == listb:
 >	print 'equal'
 >elif lista != listb:
 >	print 'inequal'
 >
 >
 >inequal
 >
 >Rob
 >http://uselesspython.com
 >
 >Terje Johan Abrahamsen wrote:
 >
 >>I have two lists of different length. Actually each list can differ in
 >>lenght every time. For example lista = [12, 34, 56] & listb = [14, 16,
 >>34, 81]. What I now need to do is to check if the lists have one or more
 >>common numbers. In this case 34 exists in each list. Then I would like
 >>the function to somehow indicate this. Does it exist a simple way to do
 >>this? I have made a somehow functioning function that does this, but it
 >>is probably about 50-60 lines. (If lista[0] == listb[0], if lista[1] ==
 >>listb[0] and so forth....)
 >>
 >>Any suggestions?
 >>
 >>Thanks,
 >>Terje
 >>
 >>
 >>
 >>_________________________________________________________________
 >>Join the world's largest e-mail service with MSN Hotmail.
 >>http://www.hotmail.com
 >>
 >>
 >>
 >>_______________________________________________
 >>Tutor maillist  -  Tutor@python.org
 >>http://mail.python.org/mailman/listinfo/tutor
 >>
 >
 >
 >--
 >"Giving the Linus Torvalds Award to the Free Software Foundation is a
 >bit like giving the Han Solo Award to the Rebel Alliance."
 >--Richard Stallman at the 1999 LinuxWorld show
 >
 >
 >
 >
 >_______________________________________________
 >Tutor maillist  -  Tutor@python.org
 >http://mail.python.org/mailman/listinfo/tutor




_________________________________________________________________
MSN Photos is the easiest way to share and print your photos:
http://photos.msn.com/support/worldwide.aspx



-- 
"Giving the Linus Torvalds Award to the Free Software Foundation is a 
bit like giving the Han Solo Award to the Rebel Alliance."
--Richard Stallman at the 1999 LinuxWorld show





From pythontutor@venix.com  Tue Jul  9 15:57:25 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 09 Jul 2002 10:57:25 -0400
Subject: [Tutor] python from shell
References: <B9505AE1.910A%sarmstrong13@mac.com>
Message-ID: <3D2AF9D5.4030100@venix.com>

#!/usr/bin/env python
finds python using your environment.  A cgi script is running in the
httpd server's environment wich may not support finding python.  It is
quite common for cgi scripts to point directly to python.

SA wrote:

> On 7/9/02 7:37 AM, "Scot W. Stevenson" <scot@possum.in-berlin.de> wrote:
> 
> 
>>Hello Guillermo, 
>>
>>
>>>You have to add #! and the path of your python command in the first line
>>>of your code. In my case is:
>>>#! /usr/bin/python
>>>
>>I've been using 
>>
>>#!/usr/bin/env python
>>
>>instead with no ill effects so far - which, if I understand correctly,
>>gives the program the environment variables, too.
>>
>>Y, Scot
>>
> The only problem I've seen with this so far is when I write a cgi script.
> For some reason /usr/bin/env chokes my Apache server and spews an error. In
> a regular python script, this works fine for me. I just changed that line to
> the direct route to python for my cgi scripts.
> 
> Good Luck.
> SA
> 
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From pythontutor@venix.com  Tue Jul  9 16:03:00 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 09 Jul 2002 11:03:00 -0400
Subject: [Tutor] Comparing lists
References: <F29Kljq65Rn8P5o7P6u00000e60@hotmail.com>
Message-ID: <3D2AFB24.4010601@venix.com>

This is untested:

def inBoth(alist, blist):
	return [a for a in alist if a in blist]

This can be slow for large lists.  It will be empty if there are no entries
in common.

Terje Johan Abrahamsen wrote:

> I have two lists of different length. Actually each list can differ in 
> lenght every time. For example lista = [12, 34, 56] & listb = [14, 16, 
> 34, 81]. What I now need to do is to check if the lists have one or more 
> common numbers. In this case 34 exists in each list. Then I would like 
> the function to somehow indicate this. Does it exist a simple way to do 
> this? I have made a somehow functioning function that does this, but it 
> is probably about 50-60 lines. (If lista[0] == listb[0], if lista[1] == 
> listb[0] and so forth....)
> 
> Any suggestions?
> 
> Thanks,
> Terje
> 
> 
> 
> _________________________________________________________________
> Join the world's largest e-mail service with MSN Hotmail. 
> http://www.hotmail.com
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From asis@graffiti.net  Tue Jul  9 16:05:18 2002
From: asis@graffiti.net (Ashish)
Date: Tue, 09 Jul 2002 20:50:18 +0545
Subject: [Tutor] Comparing lists
References: <F29Kljq65Rn8P5o7P6u00000e60@hotmail.com>
Message-ID: <3D2AFBAE.9080208@graffiti.net>

Terje Johan Abrahamsen wrote:
> I have two lists of different length. Actually each list can differ in 
> lenght every time. For example lista = [12, 34, 56] & listb = [14, 16, 
> 34, 81]. What I now need to do is to check if the lists have one or more 
> common numbers. In this case 34 exists in each list. Then I would like 
> the function to somehow indicate this. Does it exist a simple way to do 
> this? I have made a somehow functioning function that does this, but it 
> is probably about 50-60 lines. (If lista[0] == listb[0], if lista[1] == 
> listb[0] and so forth....)
> 


may be
common = []
for i in lista:
     if i in listb:
         common.append(i)



-- 
Ashish Shrestha
Gha 2-482, Balajutar, Kathmandu, Nepal
Phone: 977-1-350593.




From anthony.barker@bmo.com  Tue Jul  9 17:07:04 2002
From: anthony.barker@bmo.com (anthony.barker@bmo.com)
Date: Tue, 9 Jul 2002 12:07:04 -0400
Subject: [Tutor] Lisp Macros in Python
Message-ID: <OFE5D74BC9.4A2D1CB6-ON85256BF1.0058206F-85256BF1.00595315@notes.bmo.com>

This is a multipart message in MIME format.
--=_alternative 0059531085256BF1_=
Content-Type: text/plain; charset="us-ascii"

I was reading the very interesting:

http://www.paulgraham.com/icad.html


 Is is possible to implement something like Lisp Macros in python? Does 
anyone have any information about this?

As an aside - Will there every be a compiled Python - Like Lisp?

Thanks,

Anthony
--=_alternative 0059531085256BF1_=
Content-Type: text/html; charset="us-ascii"


<br><font size=2 face="sans-serif">I was reading the very interesting:</font>
<br><font size=2 face="sans-serif"><br>
http://www.paulgraham.com/icad.html<br>
</font>
<br>
<br><font size=2 face="sans-serif">&nbsp;Is is possible to implement something like Lisp Macros in python? Does anyone have any information about this?</font>
<br>
<br><font size=2 face="sans-serif">As an aside - Will there every be a compiled Python - Like Lisp?</font>
<br>
<br><font size=2 face="sans-serif">Thanks,</font>
<br>
<br><font size=2 face="sans-serif">Anthony</font>
--=_alternative 0059531085256BF1_=--



From dman@dman.ddts.net  Tue Jul  9 17:30:05 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 9 Jul 2002 11:30:05 -0500
Subject: [Tutor] Re: CMS written in Python
In-Reply-To: <4.3.2.7.2.20020708185109.00b77ef0@pop3.norton.antivirus>
References: <4.3.2.7.2.20020708185109.00b77ef0@pop3.norton.antivirus>
Message-ID: <20020709163005.GA17757@dman.ddts.net>

--5vNYLRcllDrimb99
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jul 08, 2002 at 07:03:18PM +0200, Alexandre Ratti wrote:

| Are you aware of a CMS (Content Management System) written in Python and=
=20
| available under a free-software/open-source license? Besides Zope and Zop=
e=20
| modules, I mean.

Why not zope?

| There are dozens of options in PHP (PHPNuke, PostNuke, etc), but I couldn=
't=20
| find similar tools in Python.

Zope is the main one.  Lots of people work on it, rather than
re-invent their own.
=20
| I am looking for a stand-alone tool I could adapt to publish a dynamic We=
b=20
| site.

zope
quixote
python server pages
spyce (I think that's the name of a recent one)
pyweblib

There's a bunch of others too, and of course there's always standard
CGI.

-D

--=20
=20
Dishonest money dwindles away,
but he who gathers money little by little makes it grow.
        Proverbs 13:11
=20
http://dman.ddts.net/~dman/


--5vNYLRcllDrimb99
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0rD40ACgkQO8l8XBKTpRQ7qQCcDtfN/jPDj1uo+/7ER6QQJAQd
VA4An0iqOiVDxkpxBScpYuxhpuT7C8WZ
=t2S0
-----END PGP SIGNATURE-----

--5vNYLRcllDrimb99--



From kemu@linuxmail.org  Tue Jul  9 17:21:53 2002
From: kemu@linuxmail.org (Jonas Geiregat)
Date: Wed, 10 Jul 2002 00:21:53 +0800
Subject: [Tutor] Comparing lists
Message-ID: <20020709162153.30927.qmail@linuxmail.org>

someting like this will work:


for i in lista:
   for x in listb:
       if x == i: 
           print x is in lista AND listb
       

----- Original Message -----
From: Ashish <asis@graffiti.net>
Date: Tue, 09 Jul 2002 20:50:18 +0545 
To: tutor@python.org
Subject: Re: [Tutor] Comparing lists


> Terje Johan Abrahamsen wrote:
> > I have two lists of different length. Actually each list can differ in 
> > lenght every time. For example lista = [12, 34, 56] & listb = [14, 16, 
> > 34, 81]. What I now need to do is to check if the lists have one or more 
> > common numbers. In this case 34 exists in each list. Then I would like 
> > the function to somehow indicate this. Does it exist a simple way to do 
> > this? I have made a somehow functioning function that does this, but it 
> > is probably about 50-60 lines. (If lista[0] == listb[0], if lista[1] == 
> > listb[0] and so forth....)
> > 
> 
> 
> may be
> common = []
> for i in lista:
>      if i in listb:
>          common.append(i)
> 
> 
> 
> -- 
> Ashish Shrestha
> Gha 2-482, Balajutar, Kathmandu, Nepal
> Phone: 977-1-350593.
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Get your free email from www.linuxmail.org 


Powered by Outblaze



From dman@dman.ddts.net  Tue Jul  9 17:38:48 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 9 Jul 2002 11:38:48 -0500
Subject: [Tutor] Re: python from shell
In-Reply-To: <B9505AE1.910A%sarmstrong13@mac.com>
References: <200207091437.22333.scot@possum.in-berlin.de> <B9505AE1.910A%sarmstrong13@mac.com>
Message-ID: <20020709163848.GB17757@dman.ddts.net>

--OwLcNYc0lM97+oe1
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 09, 2002 at 09:18:25AM -0500, SA wrote:
| On 7/9/02 7:37 AM, "Scot W. Stevenson" <scot@possum.in-berlin.de> wrote:
|=20
| >> You have to add #! and the path of your python command in the first li=
ne
| >> of your code. In my case is:
| >> #! /usr/bin/python
| >=20
| > I've been using=20
| >=20
| > #!/usr/bin/env python
| >=20
| > instead with no ill effects so far - which, if I understand correctly,
| > gives the program the environment variables, too.
|
| The only problem I've seen with this so far is when I write a cgi script.
| For some reason /usr/bin/env chokes my Apache server and spews an error. =
In
| a regular python script, this works fine for me. I just changed that line=
 to
| the direct route to python for my cgi scripts.

Here's the difference :

/usr/bin/env is a program that searches the $PATH to find the program
given as it's first argument.  Then it exec's it on the input
(script).

Using /usr/bin/env means that your script will automagically run on
any person's system *IFF* the 'python' found first in the $PATH is the
one you wanted to use.  It also means (due to limitations in
linux/bash) that you can't pass any arguments to python itself (such
as -u or -OO).

Using the full path to the interpreter ensures that you'll be using
the python you want to use.

For example, on a debian woody system, /usr/bin/python is a symlink to
/usr/bin/python2.1, and it is also possible for the user to have
/usr/bin/python2.2 as well.  On a RH 7.x system, 'python' (is it in
/usr/bin ?) is version 1.5 wherease 'python2' is version
2.<something>.  Using the env trick will yield different results on
different systems, and using the full path isn't compatible with all
systems.

Pay your money and take your choice :-) (as one of my profs likes to say)

I choose to use the absolute path and explicitly specify the version I
want.  Then again, I also use debian and for debian-packaged programs
that is also the Policy.


As for running as a CGI script in Apache, the problem is that $PATH
isn't set the same way it is in your shell.  Hence /usr/bin/env can't
find a 'python' and it fails.  Use the absolute path and it will work
as expected.

-D

--=20
=20
Religion that God our Father accepts as pure and faultless is this: to
look after orphans and widows in their distress and to keep oneself from
being polluted by the world.
        James 1:27
=20
http://dman.ddts.net/~dman/


--OwLcNYc0lM97+oe1
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0rEZgACgkQO8l8XBKTpRTUBACcCDazxQsRPc3NcneWS2CNwgmS
LqgAn0T9jQYS2NLBw/ggM9TefJyc2npC
=fU+9
-----END PGP SIGNATURE-----

--OwLcNYc0lM97+oe1--



From sarmstrong13@mac.com  Tue Jul  9 17:31:13 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 09 Jul 2002 11:31:13 -0500
Subject: [Tutor] Comparing lists
In-Reply-To: <20020709162153.30927.qmail@linuxmail.org>
Message-ID: <B9507A01.9384%sarmstrong13@mac.com>

On 7/9/02 11:21 AM, "Jonas Geiregat" <kemu@linuxmail.org> wrote:

> someting like this will work:
> 
> 
> for i in lista:
>  for x in listb:
>      if x == i: 
>          print x is in lista AND listb
>      
>

Slight correction:

For i in lista:
    for x in listb:
        if i == x:
            print i + " is in lista and listb"

I think this is what you were trying for. Sorry if I'm wrong.
Mostly semantics;)

Good Luck,
SA

-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me




From dman@dman.ddts.net  Tue Jul  9 17:44:22 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 9 Jul 2002 11:44:22 -0500
Subject: [Tutor] Re: CGI Question
In-Reply-To: <B95043D4.9101%sarmstrong13@mac.com>
References: <B94FAA17.90E2%sarmstrong13@mac.com> <B95043D4.9101%sarmstrong13@mac.com>
Message-ID: <20020709164422.GC17757@dman.ddts.net>

--GPJrCs/72TxItFYR
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 09, 2002 at 07:40:04AM -0500, SA wrote:
| I've now managed to get the script to work part way. I got rid of the ser=
ver
| error by changing:
|   #!/usr/bin/env python
| To
|   #!/sw/bin/python

That is correct.  See my post from a minute ago that explains how the
'env' trick works, and why it doesn't work in a CGI environment.

| So this fixes the server error. I then set the program to display the val=
ue
| for the key "pageID", but what I get is a blank page. This makes me wonder
| if the value is being passed to the key? Once again the href portion of t=
he
| html is:

Is the page really blank?  Use the "view source" option in your
browser to find out.  Another helpful tool is 'tcpflow', so you can
watch the HTTP-level interaction between the browser and the server.
=20
| Any ideas on what I'm doing wrong and why the script is not receiving the
| value 'testtext'?

Look in apache's error log.  If you had an exception or some other
error, it will be shown there.

Another useful tool is the 'cgitb' module.  It hooks into the
interpreter to catch any exceptions and give you a nicely formatted
stack trace in your browser.

HTH,
-D

--=20
=20
A kindhearted woman gains respect,
but ruthless men gain only wealth.
        Proverbs 11:16
=20
http://dman.ddts.net/~dman/


--GPJrCs/72TxItFYR
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0rEuYACgkQO8l8XBKTpRQXigCgpO/f2TmPJicsc57lpBPBkyVf
dTQAn2T49OURtg2htqXPXTGI1O1He41x
=23bY
-----END PGP SIGNATURE-----

--GPJrCs/72TxItFYR--



From dman@dman.ddts.net  Tue Jul  9 17:59:12 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 9 Jul 2002 11:59:12 -0500
Subject: [Tutor] Re: Comparing lists
In-Reply-To: <F13oyNW3FAcYA6aEdHy0000ada6@hotmail.com>
References: <F13oyNW3FAcYA6aEdHy0000ada6@hotmail.com>
Message-ID: <20020709165912.GD17757@dman.ddts.net>

--mSxgbZZZvrAyzONB
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 09, 2002 at 02:55:28PM +0000, Terje Johan Abrahamsen wrote:
| I am trying to find out if there is some number that exists in both lists=
.=20
| It doesn't matter if they are in the same place or not. I just want to fi=
nd=20
| if some number exists in both lists, or if all numbers differs from all=
=20
| numbers in the other list.

Several people have posted the most obvious solution (a nested loop),
but that method is O(n**2).  (read: order n squared)  As the inputs
increase in size, the execution time increases exponentially.  (IOW,
if you double the size of the input data, you *square* the execution
time)

Since python has dictionaries built-in, and your data is hashable,
I'll use it instead :

# build your lists first, however you do that
l1 =3D [data]
l2 =3D [data]

# put all the elements of the first list into the dictionary as keys
d1 =3D {}
for item in l1 :
    d1[item] =3D None

for item in l2 :
    if d1.has_key( item ) :
        print item , "is in both lists"
    else :
        print item , "is NOT in both lists"


This method is O(n).  Rather than comparing each element of l2 to each
element of l1 (nxm comparisons), I use the effectiveness of hashing to
perform one comparison for each element of l2 (n comparisons).  I've
also eliminated any duplicate items in l1.  For large inputs where
duplicate elements are expected, you would be better off doing the
same for l2 -- pack it into a dict (as a faster way of removing
duplicates than sorting) then iterate over the keys.  For small
inputs, however, that would have more overhead and hurt performance.

What it looks like you're really interested in, though, is either a
Set or a Multiset structure.  Sets are structures that don't have any
order, and equality comparisons are a matter of seeing if each has the
same elements.  I'm sure you can find a Set implementation in python
on the web somewhere, or it would be fairly easy to write one
yourself.

HTH,
-D

--=20
=20
Many are the plans in a man's heart,
but it is the Lord's purpose that prevails.
        Proverbs 19:21
=20
http://dman.ddts.net/~dman/


--mSxgbZZZvrAyzONB
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0rFl8ACgkQO8l8XBKTpRRPzACfYg9MbvThap3XP+OOQ8QolzDA
KGUAnA3NBMq3Z/9qlvuUD6E4zO8oP9Ic
=E676
-----END PGP SIGNATURE-----

--mSxgbZZZvrAyzONB--



From sarmstrong13@mac.com  Tue Jul  9 17:51:25 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 09 Jul 2002 11:51:25 -0500
Subject: [Tutor] Re: CGI Question
In-Reply-To: <20020709164422.GC17757@dman.ddts.net>
Message-ID: <B9507EBD.938F%sarmstrong13@mac.com>

On 7/9/02 11:44 AM, "Derrick 'dman' Hudson" <dman@dman.ddts.net> wrote:

> Is the page really blank?  Use the "view source" option in your
> browser to find out.  Another helpful tool is 'tcpflow', so you can
> watch the HTTP-level interaction between the browser and the server.
> 
Actually, I've made progress by 'hacking' away at the code until I got a
response. What I actually get now is:

The test file is:

['testtxt']
Finished!


What I have is about 20 text files that I would like to place on the web. I
want to use a python cgi script to get the query string, read the value from
that query string(which is the name of the text file), read that text file,
and display it in a html template between the <pre></pre> tags. So I've been
working on this little test script to see how the cgi module works on query
strings. I'm new to cgi and python and all off the python cgi documentation
I've found discusses "forms" I've found on perl/cgi document that gave me a
hint on what to do, and then I started reading the module for cgi in python.
I now have a test script that works to a certain extent( except I can not
seem to place the dictionary value from the query string into a string valu
so that I can open the file and read the contents). This is what I have so
far:

#!/sw/bin/python

import cgi
import re

QueryString = cgi.parse_qs('pageID=testtxt')

for pageID in QueryString.keys():
    QValue = QueryString[ pageID]
#    passvalue = [Qvalue]
#    body = open("QValue", "r")
#    for line in body.readlines():
    print "Content-Type: text/plain\n\n"
#        print line
    
    print "The test file is:\n"
    print QValue
#    body.close()
    
print "Finished!"

Any ideas on how to get the query string 'value' into a format that can be
manipulated by open so that I can read the contents of the file and display
them in a new web page?

Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me






From pythontutor@venix.com  Tue Jul  9 19:05:30 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 09 Jul 2002 14:05:30 -0400
Subject: [Tutor] Lisp Macros in Python
References: <OFE5D74BC9.4A2D1CB6-ON85256BF1.0058206F-85256BF1.00595315@notes.bmo.com>
Message-ID: <3D2B25EA.1040003@venix.com>

http://gnosis.cx/publish/tech_index_cp.html
Charming Python, a column by David Mertz
The functional program columns also include links for more info.  I don't
believe that Lisp macros are covered directly.

Peter Norvig (www.norvig.com) has an essay describing Python for Lisp
programmers.

There is a sourceforge project called, I think, Psycho that is attempting
to compile Python.

anthony.barker@bmo.com wrote:

> 
> I was reading the very interesting:
> 
> http://www.paulgraham.com/icad.html
> 
> 
>  Is is possible to implement something like Lisp Macros in python? Does 
> anyone have any information about this?
> 
> As an aside - Will there every be a compiled Python - Like Lisp?
> 
> Thanks,
> 
> Anthony


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From sarmstrong13@mac.com  Tue Jul  9 20:07:24 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 09 Jul 2002 14:07:24 -0500
Subject: [Tutor] Re: CGI Question
In-Reply-To: <B9507EBD.938F%sarmstrong13@mac.com>
Message-ID: <B9509E9C.93BD%sarmstrong13@mac.com>

Ok. I 'hacked' at the code for awhile and have finally figured it out. For
anyone that wants to see the results, check my test program below:

On 7/9/02 11:51 AM, "SA" <sarmstrong13@mac.com> wrote:

#!/sw/bin/python

import cgi 
import cgitb

cgitb.enable(display=0, logdir="/Users/montana/Temp")

QueryString = cgi.FieldStorage()
for pageID in QueryString.keys():
    QValue = QueryString['pageID'].value
    body = open(QValue, "r")
    for line in body.readlines():
        print "Content-Type: text/plain\n\n"
        print line
    body.close()
    
print "Finished!"

The line in the testtext file is of course "Hello World!" So clicking the
Test link on the first webpage sends the querystring (filename of the text
file) to the python cgi script, and the script translates the data and
displays the following on a new web page:

Hello World!
Finished!

So everything is groovy now and I can start developing my own website.
Thank You all for your help.

Thanks.
SA

> On 7/9/02 11:44 AM, "Derrick 'dman' Hudson" <dman@dman.ddts.net> wrote:
> 
>> Is the page really blank?  Use the "view source" option in your
>> browser to find out.  Another helpful tool is 'tcpflow', so you can
>> watch the HTTP-level interaction between the browser and the server.
>> 
> Actually, I've made progress by 'hacking' away at the code until I got a
> response. What I actually get now is:
> 
> The test file is:
> 
> ['testtxt']
> Finished!
> 
> 
> What I have is about 20 text files that I would like to place on the web. I
> want to use a python cgi script to get the query string, read the value from
> that query string(which is the name of the text file), read that text file,
> and display it in a html template between the <pre></pre> tags. So I've been
> working on this little test script to see how the cgi module works on query
> strings. I'm new to cgi and python and all off the python cgi documentation
> I've found discusses "forms" I've found on perl/cgi document that gave me a
> hint on what to do, and then I started reading the module for cgi in python.
> I now have a test script that works to a certain extent( except I can not
> seem to place the dictionary value from the query string into a string valu
> so that I can open the file and read the contents). This is what I have so
> far:
> 
> #!/sw/bin/python
> 
> import cgi
> import re
> 
> QueryString = cgi.parse_qs('pageID=testtxt')
> 
> for pageID in QueryString.keys():
>   QValue = QueryString[ pageID]
> #    passvalue = [Qvalue]
> #    body = open("QValue", "r")
> #    for line in body.readlines():
>   print "Content-Type: text/plain\n\n"
> #        print line
>   
>   print "The test file is:\n"
>   print QValue
> #    body.close()
>   
> print "Finished!"
> 
> Any ideas on how to get the query string 'value' into a format that can be
> manipulated by open so that I can read the contents of the file and display
> them in a new web page?
> 
> Thanks.
> SA
> 




From sarmstrong13@mac.com  Tue Jul  9 20:11:41 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 09 Jul 2002 14:11:41 -0500
Subject: [Tutor] New newbie question.
Message-ID: <B9509F9D.93C2%sarmstrong13@mac.com>

Can you read a pdf with Python?

I know you can read a text file with:

Inp = open("textfile", "r")

Will the same thing work on pdf files:

Inp = open("pdffile", "rb")

?

Anyone know of a module that parses pdf files in python?

Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me




From dyoo@hkn.eecs.berkeley.edu  Tue Jul  9 20:17:39 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 9 Jul 2002 12:17:39 -0700 (PDT)
Subject: [Tutor] Re: CGI Question
In-Reply-To: <B9509E9C.93BD%sarmstrong13@mac.com>
Message-ID: <Pine.LNX.4.44.0207091212450.21583-100000@hkn.eecs.berkeley.edu>


On Tue, 9 Jul 2002, SA wrote:

> Ok. I 'hacked' at the code for awhile and have finally figured it out. For
> anyone that wants to see the results, check my test program below:

Hi SA,


> #!/sw/bin/python
>
> import cgi
> import cgitb
>
> cgitb.enable(display=0, logdir="/Users/montana/Temp")
>
> QueryString = cgi.FieldStorage()
> for pageID in QueryString.keys():
>     QValue = QueryString['pageID'].value
>     body = open(QValue, "r")
>     for line in body.readlines():
>         print "Content-Type: text/plain\n\n"
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


I think you can just print out the content type of the document once; the
web browser just looks at it the first time, and then assumes that the
rest of the output is of that type.  If your body is longer than a line
(or if you have more than one query parameter), then you'll see a bunch of
'Content-type: text/plain' lines crisscrossing your output.  This will
look pretty neat, but is probably not what you mean.  *grin*

I'd recommend pulling this out of the inner loop altogether, and to
relocate it to the beginning:

###
print "Content-Type: text/plain\n\n"
for pageID in QueryString.keys():
    QValue = QueryString['pageID'].value
    body = open(QValue, "r")
###




From wesc@deirdre.org  Tue Jul  9 20:09:13 2002
From: wesc@deirdre.org (wesc@deirdre.org)
Date: Tue, 9 Jul 2002 12:09:13 -0700 (PDT)
Subject: [Tutor] ANN: BayPIGgies mtg Wed 7/10 7:30pm
Message-ID: <200207091909.g69J9Dp03231@alpha.ece.ucsb.edu>

BayPIGgies/Silicon Valley-San Francisco Bay Area Python Users Group
When:   July 10, 2002 @ 7:30pm
Agenda: Internet Programming with Python
Where:  Stanford University, Palo Alto, CA

Continuing the high-level talks for the O'Reilly OSCON 2002
conference coming up in a few weeks, I will give an introductory
talk on various forms of Internet programming using Python:

- Network Programming (client/server, socket module) 
- Internet Client Programming (FTP, NNTP, POP3, telnet) 
- CGI Programming (CGI basics, cgi module) 

The full description of the tutorial I will be presenting can be
<A href="http://conferences.oreillynet.com/cs/os2002/view/e_sess/2993">accessed
here</A>.  I will also be giving the "now"-annual intro to the
complete newbie BOF: <A href="http://conferences.oreillynet.com/pub/w/15/bof.html">What is Python?</A>

Upcoming Meetings:
8/14: looking for a guest speaker! 
9/11: Using a Model-View-Controller Architecture to Create
	a Python/XML-based Web Application Framework

We are actively seeking speakers for BayPIGgies, esp. August!
If you would like to give a talk at one of our meetings (any
Python related topic), contact us to coordinate! 

more info including directions:    http://www.baypiggies.net

hope to see some of you tomorrow evening!

-wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

"Core Python Programming", Prentice Hall PTR, © 2001
    http://starship.python.net/crew/wesc/cpp/

Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies)
    http://deirdre.org/baypiggies

wesley.j.chun :: wesc at deirdre.org
cyberweb.consulting : cyberweb at rocketmail.com
http://roadkill.com/~wesc/cyberweb/



From dyoo@hkn.eecs.berkeley.edu  Tue Jul  9 20:27:02 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 9 Jul 2002 12:27:02 -0700 (PDT)
Subject: [Tutor] New newbie question.
In-Reply-To: <B9509F9D.93C2%sarmstrong13@mac.com>
Message-ID: <Pine.LNX.4.44.0207091219050.21583-100000@hkn.eecs.berkeley.edu>

On Tue, 9 Jul 2002, SA wrote:

> Can you read a pdf with Python?
>
> I know you can read a text file with:
>
> Inp = open("textfile", "r")
>
> Will the same thing work on pdf files:
>
> Inp = open("pdffile", "rb")

Yes, we can read from pdf's in binary format.



> Anyone know of a module that parses pdf files in python?

Hmmmm... there is a program called 'pdftotext' that is included in the
standard xpdf package on Unix systems --- this utility can extract plain
text out of PDF files in many cases.  So if there isn't a strict module
for Python yet, we can build a frontend that drives 'pdftotext' for us.

In fact, pdftotext is such a nice tool that it's used in a lot of web
indicing programs; it might be worth it for someone to write a Python
module that wraps pdftotext nicely.


See:

    http://www.foolabs.com/xpdf/download.html
and

http://www.l4sb.com/Members/Eugene%20von/poweruser/page3/portalarticle_view

for more details.  Hope this helps!




From sarmstrong13@mac.com  Tue Jul  9 20:52:55 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 09 Jul 2002 14:52:55 -0500
Subject: [Tutor] New newbie question.
In-Reply-To: <Pine.LNX.4.44.0207091219050.21583-100000@hkn.eecs.berkeley.edu>
Message-ID: <B950A947.93D9%sarmstrong13@mac.com>

On 7/9/02 2:27 PM, "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> wrote:

> 
> On Tue, 9 Jul 2002, SA wrote:
> 
>> Can you read a pdf with Python?
>> 
>> I know you can read a text file with:
>> 
>> Inp = open("textfile", "r")
>> 
>> Will the same thing work on pdf files:
>> 
>> Inp = open("pdffile", "rb")
> 
> Yes, we can read from pdf's in binary format.
> 

The only problem is when I try to read a pdf file using "rb", python then
displays a lot of pdf jibberish instead of the text that is in the pdf file
on the next web page.
Is there something else I need to do to read the text lines with this
method, or do I need to just skip this and try to use pdftotxt program
instead?

Thanks.
SA




From printers@sendme.cz  Tue Jul  9 21:47:44 2002
From: printers@sendme.cz (A)
Date: Tue, 9 Jul 2002 22:47:44 +0200
Subject: [Tutor] How to grab a part of web page?
Message-ID: <3D2B6810.13895.8A3A7A@localhost>

Hi,
Is it possible to download only a part of web page?
Say I need to find out an information about a customer that starts 
at 1500 byte position and ends at 2000 byte position. If the whole 
page has about 100 kb it seems to me waste of time to load all the 
page.
What is the best, yet easy, solution?
Is it possible to use httplib or necessary socket module?
Thank you for help.
Ladislav

 




From sarmstrong13@mac.com  Tue Jul  9 22:16:51 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 09 Jul 2002 16:16:51 -0500
Subject: [Tutor] How to grab a part of web page?
In-Reply-To: <3D2B6810.13895.8A3A7A@localhost>
Message-ID: <B950BCF3.93F7%sarmstrong13@mac.com>

On 7/9/02 3:47 PM, "A" <printers@sendme.cz> wrote:

> Hi,
> Is it possible to download only a part of web page?
> Say I need to find out an information about a customer that starts
> at 1500 byte position and ends at 2000 byte position. If the whole
> page has about 100 kb it seems to me waste of time to load all the
> page.
> What is the best, yet easy, solution?
> Is it possible to use httplib or necessary socket module?
> Thank you for help.
> Ladislav


You could use the re module to search for  specific tags and then download
from there. Ther is a program called spyder.py out there that could give you
some ideas on how to write this program. It is used in Plucker to download
specific items from a website and then convert them into a portable document
format that can be read on a pda using their plucker software. The program
is open source and written entirely in python I believe. So read some of
their scripts to give you an idea how to accomplish this.

Hope this helps.
SA




From glingl@aon.at  Tue Jul  9 22:23:20 2002
From: glingl@aon.at (Gregor Lingl)
Date: Tue, 9 Jul 2002 23:23:20 +0200
Subject: [Tutor] Old friend revisited - just for fun!
References: <B950A947.93D9%sarmstrong13@mac.com>
Message-ID: <001801c2278e$d9b1e970$1615a8c0@mega>

This is a multi-part message in MIME format.

------=_NextPart_000_0015_01C2279F.9D06B120
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hi!

I've attached a simple implementation of Conway's
life game. It can use VPython if available on 
your machine.

Try, for instance: python LifeGame.py 37 [torus]

Of course it's really useless, so perhaps Rob would like
to put it on his site.

Nevertheless, critical remarks and suggestions for 
improvement are welcome.
 
Gregor

P.S. I did it to show the spirit and some advantages
of OOP. Did I succeed in your opinion?


------=_NextPart_000_0015_01C2279F.9D06B120
Content-Type: text/plain;
	name="LifeGame.py"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
	filename="LifeGame.py"

"""A toy version of Conway's life game on a torus -
- based on a version found at: http://www.pythonapocrypha.com/
Outputdevice - selectable by optional command line argument:
canvas or torus.   ---   Just for fun.
                                        version: 1.0  - 2002-07-09"""
import sys, time
from Tkinter import *
from Canvas import Rectangle
try:
    from visual import *
    novisual =3D 0
except:
    print "Modul visual not available!!!"
    novisual =3D 1

class Torus:
    def __init__(self, NX, NY):
        if novisual: sys.exit(0)
        scene.forward =3D (-1.0, -1.0, -0.5)
        R, r =3D 5.0, 2.5
        self.NX, self.NY =3D NX, NY
        dfi, dtheta =3D 2*pi/NX, 2*pi/NY
        self.grid =3D {}
        for y in range(NY):
            for x in range(NX):
                fi1,    fi2    =3D x*dfi,    (x+1)*dfi
                theta1, theta2 =3D y*dtheta, (y+1)*dtheta
                r1, r2 =3D (R+r*cos(theta1)), (R+r*cos(theta2))
                c =3D convex( pos=3D[(r1*sin(fi1), r*sin(theta1), =
r1*cos(fi1)),
                                 (r1*sin(fi2), r*sin(theta1), =
r1*cos(fi2)),
                                 (r2*sin(fi2), r*sin(theta2), =
r2*cos(fi2)),
                                 (r2*sin(fi1), r*sin(theta2), =
r2*cos(fi1))],
                                 color =3D color.green )
                self.grid[(x,y)] =3D c
    def switch(self, cells):
        RATE =3D 20
        rate(RATE)   ### DOESN'T WORK PROPERLY WITH RATE =3D 40
                     ### (tested with N=3D3 on my 400MHz machine)
        for cell in cells:
            if self.grid[cell].green=3D=3D1.0:
                self.grid[cell].color=3Dcolor.red
            else:
                self.grid[cell].color=3Dcolor.green
    def getSize(self):
        return self.NX, self.NY

class TKCanvas:
    def __init__(self, NX, NY):
        squarewidth, cellwidth =3D 8, 10
        self.NX, self.NY =3D NX, NY
        root =3D Tk()
        w,h =3D NX*cellwidth, NY*cellwidth
        self.cv =3D Canvas(root, width=3Dw+2, height=3Dh+2, bg =3D =
'yellow')
        self.cv.pack()
        self.grid =3D {}
        for y in range(NY):
            for x in range(NX):
                r =3D Rectangle(self.cv, 2+x*cellwidth+1, =
2+y*cellwidth+1,
                              =
3+x*cellwidth+squarewidth,3+y*cellwidth+squarewidth,
                              fill=3D'yellow')
                self.grid[(x,y)] =3D r
        self.cv.update()
    def switch(self, cells):
        for cell in cells:
            if self.grid[cell]['fill']=3D=3D'yellow':
                self.grid[cell]['fill']=3D'red'
            else:
                self.grid[cell]['fill']=3D'yellow'
        self.cv.update()
        self.cv.after(2)
    def getSize(self):
        return self.NX, self.NY
           =20
STEADY_STATE  =3D "Steady state"
EVERYONE_DEAD =3D "Everyone dead"

class PlayField:
    def __init__(self, outputDevice):
        self._X, self._Y =3D outputDevice.getSize()
        self.out =3D outputDevice
        self.neighbors=3D{}
        self.reset()
        self.livingCells=3D[]
        self.changedCells=3D[]
    def reset(self):
        for Y in range(self._Y):
            for X in range(self._X):
                self.neighbors[(X,Y)]=3D0
    def setAlive(self,cells):
        self.livingCells=3Dcells
        self.out.switch(cells)
    def setNeighbors(self,X,Y):
        leftColumn=3D(X-1) % self._X
        rightColumn=3D(X+1) % self._X
        upRow=3D(Y-1) % self._Y
        downRow=3D(Y+1) % self._Y
        self.neighbors[(leftColumn,upRow)]+=3D1
        self.neighbors[(X,upRow)]+=3D1
        self.neighbors[(rightColumn,upRow)]+=3D1
        self.neighbors[(leftColumn,Y)]+=3D1
        self.neighbors[(rightColumn,Y)]+=3D1
        self.neighbors[(leftColumn,downRow)]+=3D1
        self.neighbors[(X,downRow)]+=3D1
        self.neighbors[(rightColumn,downRow)]+=3D1
    def nextGeneration(self):
        newGeneration=3D[]
        self.reset()
        for (X,Y) in self.livingCells:
            self.setNeighbors(X,Y)
        for cell in self.neighbors:
                n =3D self.neighbors[cell]
                if n =3D=3D 3 or n =3D=3D 2 and cell in =
self.livingCells:
                    newGeneration.append(cell)
        if not newGeneration: raise EVERYONE_DEAD
        if self.livingCells=3D=3DnewGeneration: raise STEADY_STATE
        self.changedCells=3D([c for c in self.livingCells if c not in =
newGeneration]+
                           [c for c in newGeneration if c not in =
self.livingCells])
        self.livingCells=3DnewGeneration
    def showGenerations(self,generationCount):
        try:
            for cycle in range(generationCount):
                self.out.switch(self.changedCells)
                self.nextGeneration()
        except EVERYONE_DEAD:
            self.out.switch(self.livingCells)
            print "\nAfter %s generations: the population is now =
dead."%cycle
        except STEADY_STATE:
            print "\nAfter %s generations: the population is no longer =
changing."%cycle

usage =3D """usage: python LifeGame.py  [n [g]] [canvas|torus]
optional input arguments:
n : number of cells in a line for start generation
    default value: n =3D 0 results in a glider
g : number of generations to compute,
    default value: g =3D 116    =20
canvas: causes life to be displayed on a 'toroidal' rectangle,
       actually a Tk Canvas
torus:  causes life to be displayed on a VPython torus"""
if (__name__=3D=3D"__main__"):
    #  Set size of the world:
    FIELD_X, FIELD_Y =3D 42, 17
    C_X, C_Y, C_g =3D 60,35,2000   # gcannon case
    g =3D 90    # default number of generations
    N =3D 0     # default population: glider
    args =3D sys.argv[1:]
    mode =3D 'canvas'   # default, may be changed to 'torus'
    if 'canvas' in args:
        mode =3D 'canvas'  =20
        args.remove('canvas')
    elif 'torus' in args:
        if novisual: print "Therefore no torus mode!"
        else:
            mode =3D 'torus'
            args.remove('torus')
    elif 'help' in args:
        print usage
        sys.exit(0)
    try:
        if args:
            N =3D min(int(args[0]),FIELD_X)
            if len(args) > 1: g =3D int(args[1])
    except:
        print usage
        sys.exit(0)
    if N =3D=3D -1:
        FIELD_X, FIELD_Y, g =3D C_X, C_Y, C_g
    if mode =3D=3D 'canvas':
        world =3D TKCanvas(FIELD_X, FIELD_Y)
    else:
        world =3D Torus(FIELD_X, FIELD_Y)
    life=3DPlayField(world)
    # Initialize population
    if N > 0:         # straight line of cells
        f =3D (mode=3D=3D'canvas')
        line =3D [((i+f*(FIELD_X-N)/2)%FIELD_X,0+f*FIELD_Y/2) for i in =
range(N)]
        life.setAlive(line)
    elif N =3D=3D 0:      # glider
        life.setAlive([(0,2),(1,2),(2,2),(2,3),(1,4)])
    else:             # e.g. N=3D-1, very special case
        gcannon =3D =
[(0,24),(0,25),(1,24),(1,25),(11,23),(11,24),(11,25),(12,22),(12,26),
            =
(13,21),(13,27),(14,22),(14,26),(15,23),(15,24),(15,25),(16,23),(16,24),
            =
(16,25),(21,25),(21,26),(21,27),(22,24),(22,25),(22,27),(22,28),(23,24),
            =
(23,25),(23,27),(23,28),(24,24),(24,25),(24,26),(24,27),(24,28),(25,23),
            =
(25,24),(25,28),(25,29),(30,24),(30,25),(34,26),(34,27),(35,26),(35,27)]
        if mode=3D=3D'torus': gcannon =3D [(x,(C_Y-y-8)%C_Y) for (x,y) =
in gcannon]
        life.setAlive(gcannon)
    a=3Dtime.time()
    life.showGenerations(g)
    print "\ntime:", time.time()-a
    raw_input()

------=_NextPart_000_0015_01C2279F.9D06B120--




From dyoo@hkn.eecs.berkeley.edu  Tue Jul  9 22:32:33 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 9 Jul 2002 14:32:33 -0700 (PDT)
Subject: [Tutor] New newbie question.  [PDFs and Python]
In-Reply-To: <B950A947.93D9%sarmstrong13@mac.com>
Message-ID: <Pine.LNX.4.44.0207091342560.23785-100000@hkn.eecs.berkeley.edu>


On Tue, 9 Jul 2002, SA wrote:

> On 7/9/02 2:27 PM, "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> wrote:
>
> >
> > On Tue, 9 Jul 2002, SA wrote:
> >
> >> Can you read a pdf with Python?
> >>
> >> I know you can read a text file with:
> >>
> >> Inp =3D open("textfile", "r")
> >>
> >> Will the same thing work on pdf files:
> >>
> >> Inp =3D open("pdffile", "rb")
> >
> > Yes, we can read from pdf's in binary format.
> >
>
> The only problem is when I try to read a pdf file using "rb", python
> then displays a lot of pdf jibberish instead of the text that is in the
> pdf file on the next web page.

Yes --- this is because '.pdf' files aren't so portable without software
that knows how to interpret them.

Just as Python is an interpreter for Python programs, it might be accurate
to say that Adobe Acrobat is an interpreter for PDF "programs".  One main
difference, though, is that .PDF documents don't often come with
human-readable source code.  They are in binary format, and packaged in
this way to discourage people from looking into them independently of
Acrobat Reader.



> Is there something else I need to do to read the text lines with this
> method, or do I need to just skip this and try to use pdftotxt program
> instead?

I'd recommend using pdftotext for the moment: the program handles PDF's
pretty well, and other projects extensively use it to extract pdf text.


To make pdftotext work nicely as as a Python function, we can do something
like this:

###
def extractPDFText(pdf_filename):
    """Given an pdf file name, returns a new file object of the
    text of that PDF.  Uses the 'pdftotext' utility."""
    return os.popen("pdftotext %s -" % pdf_filename)
###


Here's a demonstration:

###
>>> f =3D extractPDFText('ortuno02.pdf')
>>> text =3D f.read()
>>> print text[:200]
EUROPHYSICS LETTERS
1 March 2002

Europhys. Lett., 57 (5), pp. 759=AD764 (2002)




Keyword detection in natural languages and DNA


###


It's not perfect, but it's a beginning.  *grin*  Hope this helps!




From sarmstrong13@mac.com  Tue Jul  9 22:48:13 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 09 Jul 2002 16:48:13 -0500
Subject: [Tutor] New newbie question.  [PDFs and Python]
In-Reply-To: <Pine.LNX.4.44.0207091342560.23785-100000@hkn.eecs.berkeley.edu>
Message-ID: <B950C44D.9411%sarmstrong13@mac.com>

On 7/9/02 4:32 PM, "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> wrote:

> 
> To make pdftotext work nicely as as a Python function, we can do something
> like this:
> 
> ###
> def extractPDFText(pdf_filename):
>   """Given an pdf file name, returns a new file object of the
>   text of that PDF.  Uses the 'pdftotext' utility."""
>   return os.popen("pdftotext %s -" % pdf_filename)
> ###
> 
> 
> Here's a demonstration:
> 
> ###
>>>> f = extractPDFText('ortuno02.pdf')
>>>> text = f.read()
>>>> print text[:200]
> EUROPHYSICS LETTERS
> 1 March 2002
> 
> Europhys. Lett., 57 (5), pp. 759


Ok I can see how it would work like this. However, if I first convert the
pdf to txt, do I not then have a pdf file and a text file? Reason I ask is
this:
1. I have a python cgi script that dynamically loads text files into a web
page between the <pre></pre> tags in the <body>.
2. I would like to also be able to use this script to dynamically display
the pdf files the same way that the text files are displayed.

So pdftotext would then make a text copy of the pdf file, so I would have
delete this file after use or clutter my harddrive up with tons of txt
files. So to fix this, I would need to convert it to text temporarily while
in use by the python cgi script and then cleanup when it is done, correct?

Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me




From dyoo@hkn.eecs.berkeley.edu  Tue Jul  9 22:53:31 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 9 Jul 2002 14:53:31 -0700 (PDT)
Subject: [Tutor] How to grab a part of web page?  [crossposting]
In-Reply-To: <3D2B6810.13895.8A3A7A@localhost>
Message-ID: <Pine.LNX.4.44.0207091434040.23785-100000@hkn.eecs.berkeley.edu>


On Tue, 9 Jul 2002, A wrote:

> Hi,
> Is it possible to download only a part of web page?
> Say I need to find out an information about a customer that starts
> at 1500 byte position and ends at 2000 byte position. If the whole
> page has about 100 kb it seems to me waste of time to load all the
> page.
> What is the best, yet easy, solution?
> Is it possible to use httplib or necessary socket module?
> Thank you for help.
> Ladislav


Hi Ladislav,


I hate doing this, but it needs to be said: Please don't crosspost to
several mailing lists at once: it's not a good idea, and it can make
people very unhappy!


Please read:

http://www.gweep.ca/~edmonds/usenet/ml-etiquette.html#SECTION00070000000000000000


You should fix your email program's address book so that, at most, 'tutor'
or 'python-help' are listed in the 'CC' carbon copy.

Your question should not be going to all four mailing lists.  Python-list
is the main Python newsgroup 'comp.lang.python', and as it is, it's
already heavily impacted.  You should especially not be sending this
question on the activepython list, since it has very little to do with
activepython.


I apologize for being rude about this, but this is important: we need to
reduce traffic so that we can effectively help people without drowning out
others.




From dyoo@hkn.eecs.berkeley.edu  Tue Jul  9 23:30:28 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 9 Jul 2002 15:30:28 -0700 (PDT)
Subject: [Tutor] New newbie question.  [PDFs and Python]
In-Reply-To: <B950C44D.9411%sarmstrong13@mac.com>
Message-ID: <Pine.LNX.4.44.0207091453590.23785-100000@hkn.eecs.berkeley.edu>


On Tue, 9 Jul 2002, SA wrote:

> On 7/9/02 4:32 PM, "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> wrote:
>
> >
> > To make pdftotext work nicely as as a Python function, we can do something
> > like this:
> >
> > ###
> > def extractPDFText(pdf_filename):
> >   """Given an pdf file name, returns a new file object of the
> >   text of that PDF.  Uses the 'pdftotext' utility."""
> >   return os.popen("pdftotext %s -" % pdf_filename)
> > ###
> >
> >
> > Here's a demonstration:
> >
> > ###
> >>>> f = extractPDFText('ortuno02.pdf')
> >>>> text = f.read()
> >>>> print text[:200]
> > EUROPHYSICS LETTERS
> > 1 March 2002
> >
> > Europhys. Lett., 57 (5), pp. 759
>
>
> Ok I can see how it would work like this. However, if I first convert
> the pdf to txt, do I not then have a pdf file and a text file?


The hyphen in the command is the key to doing this without an intermediate
'txt' file:

    return os.popen("pdftotext %s -" % pdf_filename)

The hyphen is an option that tells pdftotext not to write to disk, but to
write out to its "standard output".  popen() can capture the standard
output of an external command, and, instead of writing it out to disk, can
make it directly available to us.  It feels like a file, but it's actually
all in memory, with no intermediate disk access involved.


Hope this helps!




From charles_mantha@hotmail.com  Mon Jul  8 04:20:18 2002
From: charles_mantha@hotmail.com (Charles Mantha)
Date: Sun, 7 Jul 2002 23:20:18 -0400
Subject: [Tutor] please help debug *update*solution!?*
References: <20020707192945.0413D6D9FF@www.fastmail.fm> <OE48uv5JYvgs0LtQ5A800000e16@hotmail.com>
Message-ID: <OE358QKLathsPvGpqzr00002b08@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_001E_01C2260C.DBE24F60
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Heh, ok, I think it's working now. Well it was probably alrdy working with
my first post, but made an error testing it. I tested the sleep by changing
the sleep value from 3600 to 5seconds and it sleeps for 5 seconds. So all I
hope is that this was ur objective with this program. I attached my version
of your test.py : test2.py.

ps : I imagine your coding isn't finished yet, because I dont understand why
you have begin and begin1 variables or the repetitive excuse variables...






----- Original Message -----
From: "Charles Mantha" <charles_mantha@hotmail.com>
To: <tutor@python.org>
Sent: Sunday, July 07, 2002 8:24 PM
Subject: Re: [Tutor] please help debug


> Ok, I have taken the challenge to help you debugging this. I'm newbie too
> (discovered Python a little over a week ago ;-). I have alrdy fixed the
> first bug :
>
> This is your original version :
> import time
> time = time.strftime( "%I:%M:%S %Z", time.localtime(time.time()) )
> def hour():
>  print "The current time is %(time)s" % vars()
>
>
> Which made the following error :
> Please type your name:  Kyle
>
> Traceback (most recent call last):
>   File "C:\Python22\time.py", line 35, in ?
>     hour()
>   File "C:\Python22\time.py", line 7, in hour
>     print "The current time is %(time)s" % vars()
> KeyError: time
>
> Now here is MY version of ur code :
> from time import *
> time = strftime( "%I:%M:%S %Z", localtime(time()) )
>
> def hour():
>  print "The current time is %s" % ctime()
>
> You can notice that I changed the command <import time> to <from time
import
> *> . This way it imports all the possible commands(?) and you do not have
to
> add the time. infront of each statements(?).
>
> The result :
> Please type your name:  Kyle
>
> The current time is Sun Jul 07 20:18:30 2002
> Begin hour?  (Y/N):
>
> Ok, this is only the beginning. Ill try to do as much as I can with the
rest
> of the bugs and then post my "discoveries" (im learning as I advance in
this
> task ;-).
>
>
> *note : the (?) after the words is because I am not sure im using the
> correct words >:( .
>


------=_NextPart_000_001E_01C2260C.DBE24F60
Content-Type: text/plain;
	name="time2.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
	filename="time2.py"

#! C:\Python22\python.exe

from time import *
time = strftime( "%I:%M:%S %Z", localtime(time()) )

def hour():
	print "The current time is %s" % ctime()
	begin = raw_input( "Begin hour?  (Y/N):  " )
	
	if begin == "Y":
		sleep(3600)
	elif begin == "y":
		sleep(3600)
	elif begin == "N":
		excuse = raw_input( "Why not?  " )
	elif begin == "n":
		excuse1 = raw_input( "Why not?  " )
	else:
		begin1 = raw_input( "Begin hour?  (Y/N):  " )
		if begin1 == "Y":
			sleep(3600)
		elif begin1 == "y":
			sleep(3600)
		elif begin1 == "N":
			excuse2 = raw_input( "Why not?  " )
		elif begin1 == "n":
			excuse3 = raw_input( "Why not?  " )
		else:
			print "FAILED"

username = raw_input( "Please type your name:  " )

if username == "Kyle":
	print
	hour()
elif username == "Jason":
	print
	hour()
elif username == "Chelsea":
	print
	hour()
elif username == "John":
	print
	hour()
elif username == "Cheryl":
	print
	hour()
else:
	print "FAILED"

------=_NextPart_000_001E_01C2260C.DBE24F60--


From sarmstrong13@mac.com  Wed Jul 10 01:04:32 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 09 Jul 2002 19:04:32 -0500
Subject: [Tutor] How to grab a part of web page?
In-Reply-To: <3D2B6810.13895.8A3A7A@localhost>
Message-ID: <B950E440.9576%sarmstrong13@mac.com>

On another note:

Look at this website for details:

http://www.boddie.org.uk/python/HTML.html

Good Luck,
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me





On 7/9/02 3:47 PM, "A" <printers@sendme.cz> wrote:

> Hi,
> Is it possible to download only a part of web page?
> Say I need to find out an information about a customer that starts
> at 1500 byte position and ends at 2000 byte position. If the whole
> page has about 100 kb it seems to me waste of time to load all the
> page.
> What is the best, yet easy, solution?
> Is it possible to use httplib or necessary socket module?
> Thank you for help.
> Ladislav
> 
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




From Kyle Babich" <kb@kb5.org  Wed Jul 10 03:06:13 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Wed, 10 Jul 2002 02:06:13 +0000
Subject: [Tutor] more problems, my final questions
Message-ID: <20020710020613.69E116D9DF@www.fastmail.fm>

This is a multi-part message in MIME format.

--_----------=_1026266773240551
Content-Disposition: inline
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset="ISO-8859-1"

New problems has arisin.  I was wondering if there was way to replace:
if begin in "Yy":
        print "why is the sky blue?"

With something like:
if begin == "Y" "y":
        print "why isn't the sky green or purple?"

(only unlike the code above I need something that works of course)

I'm asking because I recently added:
else begin in "CustomcustomCUSTOM":

But I had also changed the Yy and Nn to be YyYesyesYES and NnNonoNO,
however the o in No and the o and custom are conflicting and I'm trying
to find a way to fix this.  Any ideas?

Also, my final questions regaurding this program:
Could some one point me to an example or show me how to
countdown/countup time.sleep?
And the same goes for delaying/suspending and prematurly ending
time.sleep.

Thank you, this list has been so helpful.
--
Kyle
--_----------=_1026266773240551
Content-Disposition: attachment; filename="hourtracker.py"
Content-Transfer-Encoding: base64
Content-Type: application/unknown; name="hourtracker.py"

IyEgQzpcUHl0aG9uMjJccHl0aG9uLmV4ZQ0KDQppbXBvcnQgdGltZQ0KaW1w
b3J0IHN5cw0KCQ0KZGVmIGhvdXIyKCk6DQoJY3VycnRpbWUgPSB0aW1lLnN0
cmZ0aW1lKCAiJUk6JU06JVMlcCAlWiIsIHRpbWUubG9jYWx0aW1lKHRpbWUu
dGltZSgpKSApDQoJDQoJbG9ndCA9IG9wZW4oICJsb2cuZGF0IiwgImEiICkN
Cglsb2d0LndyaXRlKCAiIFslKGN1cnJ0aW1lKXNdIiAlIHZhcnMoKSApDQoJ
bG9ndC5jbG9zZSgpDQoJDQoJcHJpbnQgIlRoZSBjdXJyZW50IHRpbWUgaXMg
JShjdXJydGltZSlzIiAlIHZhcnMoKQ0KCXdoaWxlIDE6DQoJCWJlZ2luID0g
cmF3X2lucHV0KCAiQmVnaW4gdGltZT8gIFtZL05dOiAgIiApDQoJDQoJCWlm
IGJlZ2luIGluICJZeSI6DQoJCQl0aW1lLnNsZWVwKCBzbGVlcHRpbWUqNjAg
KQ0KDQoJCQlsb2dlID0gb3BlbiggImxvZy5kYXQiLCAiYSIgKQ0KCQkJbG9n
ZS53cml0ZSggIiBbIiArIHRpbWUuc3RyZnRpbWUoICIlSTolTTolUyVwICVa
IiwgdGltZS5sb2NhbHRpbWUodGltZS50aW1lKCkpICkgKyAiXVxuIiAlIHZh
cnMoKSApDQoJCQlsb2dlLmNsb3NlKCkNCgkJCQ0KCQkJcHJpbnQNCgkJCXBy
aW50ICJUaW1lIENvbXBsZXRlIg0KCQkJdGltZS5zbGVlcCggMzAgKQ0KCQkJ
c3lzLmV4aXQoKQ0KCQllbGlmIGJlZ2luIGluICJObiI6DQoJCQlwcmludA0K
CQkJaG91cigpDQoJCWVsc2U6DQoJCQlwcmludCAiRkFJTEVEIg0KCQkJdGlt
ZS5zbGVlcCggMzAgKQ0KCQkJc3lzLmV4aXQoKQ0KDQpkZWYgaG91cigpOgkN
CgljdXJydGltZSA9IHRpbWUuc3RyZnRpbWUoICIlSTolTTolUyVwICVaIiwg
dGltZS5sb2NhbHRpbWUodGltZS50aW1lKCkpICkNCgkNCglsb2d0ID0gb3Bl
biggImxvZy5kYXQiLCAiYSIgKQ0KCWxvZ3Qud3JpdGUoICIgIFslKGN1cnJ0
aW1lKXNdIiAlIHZhcnMoKSApDQoJbG9ndC5jbG9zZSgpDQoJDQoJcHJpbnQg
IlRoZSBjdXJyZW50IHRpbWUgaXMgJShjdXJydGltZSlzIiAlIHZhcnMoKQ0K
CXdoaWxlIDE6DQoJCWJlZ2luID0gcmF3X2lucHV0KCAiQmVnaW4gaG91cj8g
IFtZL05dOiAgIiApDQoJDQoJCWlmIGJlZ2luIGluICJZeSI6DQoJCQl0aW1l
LnNsZWVwKCA1ICkNCg0KCQkJbG9nZSA9IG9wZW4oICJsb2cuZGF0IiwgImEi
ICkNCgkJCWxvZ2Uud3JpdGUoICIgWyIgKyB0aW1lLnN0cmZ0aW1lKCAiJUk6
JU06JVMlcCAlWiIsIHRpbWUubG9jYWx0aW1lKHRpbWUudGltZSgpKSApICsg
Il1cbiIgJSB2YXJzKCkgKQ0KCQkJbG9nZS5jbG9zZSgpDQoJCQkNCgkJCXBy
aW50DQoJCQlwcmludCAiSG91ciBDb21wbGV0ZSINCgkJCXRpbWUuc2xlZXAo
IDMwICkNCgkJCXN5cy5leGl0KCkNCgkJZWxpZiBiZWdpbiBpbiAiTm4iOg0K
CQkJcHJpbnQNCgkJCWhvdXIoKQ0KCQllbGlmIGJlZ2luIGluICJDdXN0b21D
VVNUT01jdXN0b20iOg0KCQkJc2xlZXB0aW1lID0gcmF3X2lucHV0KCAiUGxl
YXNlIGVudGVyIHRpbWUgdG8gc2xlZXAgaW4gbWludXRlczogICIpDQoNCgkJ
CWxvZ2N1ID0gb3BlbiggImxvZy5kYXQiLCAiYSIgKQ0KCQkJbG9nY3Uud3Jp
dGUoICIgIFslKHNsZWVwdGltZSlzXSIgJSB2YXJzKCkgKQ0KCQkJbG9nY3Uu
Y2xvc2UoKQ0KDQoJCQlob3VyMigpDQoJCWVsc2U6DQoJCQlwcmludCAiRkFJ
TEVEIg0KCQkJdGltZS5zbGVlcCggMzAgKQ0KCQkJc3lzLmV4aXQoKQ0KDQoJ
d2hpbGUgMToNCgkJY29uZmlybSA9IHJhd19pbnB1dCggIkNvbmZpcm0gIiAr
IHNsZWVwdGltZSArICIgbWludXRlcz8gIFtZL05dOiAgIiApDQoNCgkJaWYg
Y29uZmlybSBpbiAiWXlZZXN5ZXNZRVMiOg0KCQkJaG91cjIoKQ0KCQllbGlm
IGNvbmZpcm0gaW4gIk5uTm9ub05PIjoNCgkJCWN1c3RvbSgpDQoJCWVsc2U6
DQoJCQlwcmludCAiRkFJTEVEIg0KCQkJdGltZS5zbGVlcCggMzAgKQ0KCQkJ
c3lzLmV4aXQoKQ0KDQp1c2VybmFtZSA9IHJhd19pbnB1dCggIlBsZWFzZSB0
eXBlIHlvdXIgZmlyc3QgbmFtZTogICIgKQ0KDQpsb2d1ID0gb3BlbiggImxv
Zy5kYXQiLCAiYSIgKQ0KbG9ndS53cml0ZSggIiUodXNlcm5hbWUpcyIgJSB2
YXJzKCkgKQ0KbG9ndS5jbG9zZSgpDQoNCmlmIHVzZXJuYW1lLmxvd2VyKCkg
aW4gImt5bGUgamFzb24gY2hlbHNlYSBqb2huIGNoZXJ5bCIuc3BsaXQoKToN
CglwcmludA0KCWhvdXIoKQ0KZWxzZToNCglwcmludA0KCXByaW50ICJGQUlM
RUQiDQoJdGltZS5zbGVlcCggMzAgKQ0KCXN5cy5leGl0KCkNCg==

--_----------=_1026266773240551--




From Kyle Babich" <kb@kb5.org  Wed Jul 10 03:08:17 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Wed, 10 Jul 2002 02:08:17 +0000
Subject: [Tutor] more problems, my final questions
Message-ID: <20020710020817.17BF46DA24@www.fastmail.fm>

New problems has arisin.  I was wondering if there was way to replace:
if begin in "Yy":
        print "why is the sky blue?"

With something like:
if begin == "Y" "y":
        print "why isn't the sky green or purple?"

(only unlike the code above I need something that works of course)

I'm asking because I recently added:
else begin in "CustomcustomCUSTOM":

But I had also changed the Yy and Nn to be YyYesyesYES and NnNonoNO,
however the o in No and the o and custom are conflicting and I'm trying
to find a way to fix this.  Any ideas?

Also, my final questions regaurding this program:
Could some one point me to an example or show me how to
countdown/countup time.sleep?
And the same goes for delaying/suspending and prematurly ending
time.sleep.

If anyone sees any problems-waiting-to-happen in my program (attached)
please tell me.

Thank you, this list has been so helpful.
--
Kyle



From tbrauch@mindless.com  Wed Jul 10 03:44:34 2002
From: tbrauch@mindless.com (Timothy M. Brauch)
Date: Tue, 9 Jul 2002 22:44:34 -0400
Subject: [Tutor] more problems, my final questions
References: <20020710020817.17BF46DA24@www.fastmail.fm>
Message-ID: <006901c227bb$b99df660$9c21840a@tmbrau00>

One more time, hopefully this one will make it through (that is, if I send
it correctly).

----- Original Message -----
From: "Kyle Babich" <kb@kb5.org>
To: "tutor" <tutor@python.org>
Sent: Tuesday, July 09, 2002 10:08 PM
Subject: [Tutor] more problems, my final questions


> New problems has arisin.  I was wondering if there was way to replace:
> if begin in "Yy":
>         print "why is the sky blue?"
>
> With something like:
> if begin == "Y" "y":
>         print "why isn't the sky green or purple?"

You should be able to use either:
if begin in ['Y', 'y']:
        do something
        ...
or
if begin == 'Y' or begin == 'y':
        do something
        ...

I am not sure which one is preferred...
> (only unlike the code above I need something that works of course)
>
> I'm asking because I recently added:
> else begin in "CustomcustomCUSTOM":

In this case, I think it would be better to use the list:
if begin in ['Custom', 'custom', 'CUSTOM']:
        ...

> But I had also changed the Yy and Nn to be YyYesyesYES and NnNonoNO,
> however the o in No and the o and custom are conflicting and I'm trying
> to find a way to fix this.  Any ideas?

Although, a solution I just thought of that might make things even easier...
import string
...
begin = string.lower(begin)
if begin in ['y', 'yes']:
        ...

The third line converts begin to all lowercase (you could just as
arbitrarily use string.upper()) thus making the possible choices fewer.

Although, all of this is fly-by-the-seat-of-my-pants-untested code.  It
looks correct as I type it into my email...

> Also, my final questions regaurding this program:
> Could some one point me to an example or show me how to
> countdown/countup time.sleep?
> And the same goes for delaying/suspending and prematurly ending
> time.sleep.

Someone else will have to handle this.  I will admit I only listen to this
list with one ear, that is, only when I have free time, which seems to be
almost never.

> If anyone sees any problems-waiting-to-happen in my program (attached)
> please tell me.

Again, someone else...

> Thank you, this list has been so helpful.
> --
> Kyle

 - Tim




From slime@vsnl.net  Mon Jul  8 05:48:57 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Mon, 8 Jul 2002 10:18:57 +0530
Subject: [Tutor] Re:  Simple Python Question.
In-Reply-To: <B94E340C.900D%sarmstrong13@mac.com>
References: <B94E340C.900D%sarmstrong13@mac.com>
Message-ID: <20020708044857.GA985@localhost.localdomain>

Hi,

On Sun, 07 Jul 2002 SA spewed into the ether:
> What is the best way to look up all the python modules present in Python
> while in IDLE?

    This is not exactly IDLE-ic (*grin*), but why not just use the
Library Reference in the Python documentation. I usually have 2 windows
open, one for my editor (IDLE or vim), and one for the documentation - I
find this quite easy.

    HTH,

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

When I'm good, I'm great; but when I'm bad, I'm better.
		-- Mae West



From slime@vsnl.net  Mon Jul  8 18:29:30 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Mon, 8 Jul 2002 22:59:30 +0530
Subject: [Tutor] Ugly python one-liner !
Message-ID: <20020708172930.GA2666@localhost.localdomain>

Hi,

    I was again playing around with the matrix module I have been
working on recently, and I found I could write this absolutely perl-ish
one-liner to compute the one-norm of the matrix.

"""
    def one_norm (self) :
        """The sum of the elements in different rows of each column
        is computed, and the maximum of these values is said to
        be the one-norm of the Matrix.
        """
        return max([reduce(lambda x,y: x+y, \
                    [abs(self[r,c]) for r in range(self.rows)]) \
                        for c in range(self.columns)])
"""

    Between map(), reduce() and list comprehension, I have finally
succeeded in making python look scary :-)

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

Men will always be men -- no matter where they are.
		-- Harry Mudd, "Mudd's Women", stardate 1329.8



From dman@dman.ddts.net  Wed Jul 10 04:50:53 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 9 Jul 2002 22:50:53 -0500
Subject: [Tutor] Re: New newbie question.
In-Reply-To: <B950A947.93D9%sarmstrong13@mac.com>
References: <Pine.LNX.4.44.0207091219050.21583-100000@hkn.eecs.berkeley.edu> <B950A947.93D9%sarmstrong13@mac.com>
Message-ID: <20020710035053.GA27035@dman.ddts.net>

--fUYQa+Pmc3FrFX/N
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 09, 2002 at 02:52:55PM -0500, SA wrote:
| On 7/9/02 2:27 PM, "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> wrote:
| > On Tue, 9 Jul 2002, SA wrote:
| >=20
| >> Can you read a pdf with Python?
| >> I know you can read a text file with:
| >>=20
| >> Inp =3D open("textfile", "r")
| >>=20
| >> Will the same thing work on pdf files:
| >>=20
| >> Inp =3D open("pdffile", "rb")
| >=20
| > Yes, we can read from pdf's in binary format.
|
| The only problem is when I try to read a pdf file using "rb", python then
| displays a lot of pdf jibberish instead of the text that is in the pdf fi=
le
| on the next web page.

Yep.  That's the data in the file.  That's what you get when you read
it.  It's supposed to be that way.  It works like this for _any_ file,
regardless of the content.

| Is there something else I need to do to read the text lines with this
| method,

Yes -- you need to write a parser that can interpret the data (which
you called "jibberish" up above) and then transform it to the output
you want.  This is true for any file, though some formats are easier
to understand and parse than others.

| or do I need to just skip this and try to use pdftotxt program
| instead?

Depends on what you want to do.  If your goal is to rewrite acroread
or xpdf, then no.  If you just want some semblence of plain text, then
yes.  Be aware that any such program will be an approximation at best,
unless it actually uses OCR (Optical Character Recognition) techiques
on the canvas of a rendered PDF.  Finding the explanation is left for
the reader ;-).

-D

--=20
=20
Failure is not an option.  It is bundled with the software.
=20
http://dman.ddts.net/~dman/


--fUYQa+Pmc3FrFX/N
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0rrx0ACgkQO8l8XBKTpRQAZgCgjdwNC2QgYcnEwOsiTn0o6Y02
rOYAoMEP11lyFnfeJo/Kv4GwkicNXYZ4
=F8G6
-----END PGP SIGNATURE-----

--fUYQa+Pmc3FrFX/N--



From dman@dman.ddts.net  Wed Jul 10 04:54:28 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 9 Jul 2002 22:54:28 -0500
Subject: [Tutor] Re: How to grab a part of web page?
In-Reply-To: <3D2B6810.13895.8A3A7A@localhost>
References: <3D2B6810.13895.8A3A7A@localhost>
Message-ID: <20020710035428.GB27035@dman.ddts.net>

--V0207lvV8h4k8FAm
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 09, 2002 at 10:47:44PM +0200, A wrote:
| Hi,
| Is it possible to download only a part of web page?
| Say I need to find out an information about a customer that starts=20
| at 1500 byte position and ends at 2000 byte position. If the whole=20
| page has about 100 kb it seems to me waste of time to load all the=20
| page.
| What is the best, yet easy, solution?
| Is it possible to use httplib or necessary socket module?

Depending on the HTTP server at the other end, you _may_ be able to
request that the document starts at a certain byte position.  Older
servers definitely won't support that feature.  You can read up on it
in the RFCs that define HTTP/1.1.  I don't know much about it myself
other than applications will call it "resuming" a download.  Then you
could just drop the connection when you've seen as much data as you
want.

You can probably do the first part with the httplib module -- I think
it lets you specify "extra" headers to add.  I don't think you can
make it kill the connection, though.

In any case, depending on where you are and where you download the
data from, 100kb could take less than a second to transfer, and the
gain of not transfering the whole thing won't be noticeable by the
user.

-D

--=20
=20
The nice thing about windoze is - it does not just crash,
it displays a dialog box and lets you press 'ok' first.
=20
http://dman.ddts.net/~dman/


--V0207lvV8h4k8FAm
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0rr/QACgkQO8l8XBKTpRSoJQCgj4Yrl33ZIK8pOtb98TM/093R
xh8AniC5Hhv2/lj+vXvdHAHLrJPtKxND
=TJZP
-----END PGP SIGNATURE-----

--V0207lvV8h4k8FAm--



From dman@dman.ddts.net  Wed Jul 10 04:57:29 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 9 Jul 2002 22:57:29 -0500
Subject: [Tutor] Re: Ugly python one-liner !
In-Reply-To: <20020708172930.GA2666@localhost.localdomain>
References: <20020708172930.GA2666@localhost.localdomain>
Message-ID: <20020710035729.GC27035@dman.ddts.net>

--t0UkRYy7tHLRMCai
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jul 08, 2002 at 10:59:30PM +0530, Prahlad Vaidyanathan wrote:

|     I was again playing around with the matrix module I have been
| working on recently, and I found I could write this absolutely perl-ish
| one-liner to compute the one-norm of the matrix.
|

import operator

|     def one_norm (self) :
|         """The sum of the elements in different rows of each column
|         is computed, and the maximum of these values is said to
|         be the one-norm of the Matrix.
|         """
          return max([reduce(operator.add,
|                     [abs(self[r,c]) for r in range(self.rows)])
|                         for c in range(self.columns)])


|     Between map(), reduce() and list comprehension, I have finally
| succeeded in making python look scary :-)

Yep.  But you don't need that lambda in there -- the operator module
already has an add function for just that purpose :-).  You also don't
need the backslashes -- python knows to continue because you haven't
close the parenthesis.

HAND,
-D

--=20
=20
Microsoft is to operating systems & security ....
                                     .... what McDonald's is to gourmet coo=
king
=20
http://dman.ddts.net/~dman/


--t0UkRYy7tHLRMCai
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0rsKkACgkQO8l8XBKTpRQWtwCdE7o29RbGbjQBkq8BDISoCl5b
B/IAn3IpyojV1AE7jgUgwLiVojN6ep6n
=CodM
-----END PGP SIGNATURE-----

--t0UkRYy7tHLRMCai--



From dyoo@hkn.eecs.berkeley.edu  Wed Jul 10 08:27:23 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 10 Jul 2002 00:27:23 -0700 (PDT)
Subject: [Tutor] more problems, my final questions
In-Reply-To: <20020710020817.17BF46DA24@www.fastmail.fm>
Message-ID: <Pine.LNX.4.44.0207100023110.5687-100000@hkn.eecs.berkeley.edu>

Hi Kyle,


> New problems has arisin.  I was wondering if there was way to replace:
> if begin in "Yy":
>         print "why is the sky blue?"
>
> With something like:
> if begin == "Y" "y":
>         print "why isn't the sky green or purple?"

By the way, the statement above translates to:

    "if begin is equal to the string 'Yy', do this:..."

because if two literal strings are together like that, they'll stick
together.  For example:




> I'm asking because I recently added:
> else begin in "CustomcustomCUSTOM":

I think that you're trying to find if there's a substring of begin within
that "CustomcustomCUSTOM" string.  If so, there's another way of
expressing this:

###
def substring(word, sentence):
    return sentence.find(word) != -1
###


>
> But I had also changed the Yy and Nn to be YyYesyesYES and NnNonoNO,
> however the o in No and the o and custom are conflicting and I'm trying
> to find a way to fix this.  Any ideas?
>
> Also, my final questions regaurding this program:
> Could some one point me to an example or show me how to
> countdown/countup time.sleep?
> And the same goes for delaying/suspending and prematurly ending
> time.sleep.
>
> If anyone sees any problems-waiting-to-happen in my program (attached)
> please tell me.
>
> Thank you, this list has been so helpful.
> --
> Kyle
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From dyoo@hkn.eecs.berkeley.edu  Wed Jul 10 08:36:19 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 10 Jul 2002 00:36:19 -0700 (PDT)
Subject: [Tutor] more problems, my final questions
In-Reply-To: <Pine.LNX.4.44.0207100023110.5687-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0207100027490.5687-100000@hkn.eecs.berkeley.edu>

Oops, I pressed the email send key too quickly before I finished!  Sorry
about that!


> By the way, the statement above translates to:
>
>     "if begin is equal to the string 'Yy', do this:..."
>
> because if two literal strings are together like that, they'll stick
> together.  For example:

Here's that example:

###
>>> "hello" "world"
'helloworld'
###



> I think that you're trying to find if there's a substring of begin within
> that "CustomcustomCUSTOM" string.  If so, there's another way of
> expressing this:
>
> ###
> def substring(word, sentence):
>     return sentence.find(word) != -1
> ###


I'd better test this, or it's just going to bite me!

###
>>> substring('foo', "FooFOOfoo")
1
>>> substring('food', "FooFOOfoo")
0
###

Whew, it looks like it's working.  *grin*


The reason this works is because if the sentence can find() that word
anywhere within it, it'll give us the index position where that word
starts.  But if it can't find the word, find() returns the somewhat
strange value '-1', which we can use to our advantage.


Hope this helps!




From lumbricus@gmx.net  Wed Jul 10 11:35:09 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Wed, 10 Jul 2002 12:35:09 +0200 (MEST)
Subject: [Tutor] Re: python from shell
References: <20020709163848.GB17757@dman.ddts.net>
Message-ID: <2959.1026297309@www23.gmx.net>

> On Tue, Jul 09, 2002 at 09:18:25AM -0500, SA wrote:

[ snip ]

> Here's the difference :
> 
> /usr/bin/env is a program that searches the $PATH to find the program
> given as it's first argument.  Then it exec's it on the input
> (script).
> 
> Using /usr/bin/env means that your script will automagically run on
> any person's system *IFF* the 'python' found first in the $PATH is the
> one you wanted to use.  It also means (due to limitations in
                                                ^^^^^^^^^^^
what do you mean?

> linux/bash)
  ^^^^^^^^^^
now which one?

> that you can't pass any arguments to python itself (such
> as -u or -OO).

>From 'man env' on OSF1
(no matter which shell ;-)

"  env, printenv - Displays or sets the current environment, or displays the
  values of environment variables

SYNOPSIS

  Current Syntax

  env [-i] [name=value...] [command] [args...]

...

  args
      Arguments to be passed to command when it is executed.

"

It works for me.

> Using the full path to the interpreter ensures that you'll be using
> the python you want to use.

_Iff_ it is there. On my system for example python is in
/usr/local/bin. So your scripts won't run
 
> For example, on a debian woody system, /usr/bin/python is a symlink to
> /usr/bin/python2.1, and it is also possible for the user to have
> /usr/bin/python2.2 as well.  On a RH 7.x system, 'python' (is it in
> /usr/bin ?) is version 1.5 wherease 'python2' is version
> 2.<something>.  Using the env trick will yield different results on
> different systems, and using the full path isn't compatible with all
> systems.

ACK
 
> Pay your money and take your choice :-) (as one of my profs likes to say)

But env(1) has the advantage that it sets the environment as the
command (python) needs it - PYTHONPATH, PYTHONHOME or the like.
 
> I choose to use the absolute path and explicitly specify the version I
> want.  Then again, I also use debian and for debian-packaged programs
> that is also the Policy.

But this fails, if the specified version isn't there. 
I'd prefer env(1).
 
[ snip ]

HAND and Greetings,
J"o!

-- 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net




From asis@graffiti.net  Wed Jul 10 07:17:31 2002
From: asis@graffiti.net (Ashish)
Date: Wed, 10 Jul 2002 12:02:31 +0545
Subject: [Tutor] Re: Comparing lists - timings
References: <F13oyNW3FAcYA6aEdHy0000ada6@hotmail.com> <20020709165912.GD17757@dman.ddts.net>
Message-ID: <3D2BD17B.6080706@graffiti.net>

This is a multi-part message in MIME format.
--------------080802070107090108030902
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit

Derrick 'dman' Hudson wrote:
[snip]
> # build your lists first, however you do that
> l1 = [data]
> l2 = [data]
> 
> # put all the elements of the first list into the dictionary as keys
> d1 = {}
> for item in l1 :
>     d1[item] = None
> 
> for item in l2 :
>     if d1.has_key( item ) :
>         print item , "is in both lists"
>     else :
>         print item , "is NOT in both lists"
> 
[snip]

Derrick, you are just great! Nice algo!

Here's the timings on my system:
dict is Derricks algo and list is the old everybody's algo
smaller is faster

with dups
size    dict    list    results match
    100 0.001959 0.005347 1
   1000 0.022661 0.087229 1
  10000 0.223140 0.908544 1
  50000 1.114087 4.359394 1

with out dups
size    dict    list    results match
    100 0.001510 0.008115 1
   1000 0.016246 0.796433 1
   5000 0.080216 20.643879 1

and the test program is attached.

Ashish

--------------080802070107090108030902
Content-Type: text/plain;
 name="perf.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="perf.py"

import time
import random

def generateList1(listSize):
    " list can have repeated numbers"
    l = []
    while len(l) < listSize:
        l.append(random.randint(1,100))
    return l

def generateList2(listSize):
    " list has only unique numbers"
    l = []
    while len(l) < listSize:
        i = random.randint(1, 1000000L)
        if i not in l:
            l.append(i)
    return l

def duplicateDict(list1, list2):
    # while not exactly same, i believe it is similar and
    # basically follows the algo given
    d1 = {}
    result = []
    for item in list1:
        d1[item] = None
    for item in list2:
        if d1.has_key(item):
            result.append(item) # present in both list
    return result

def duplicateList(list1, list2):
    # the number of time a number appears in the resulting
    # list depends on the number of times it occurs in the
    # list we iterate over so to be same as duplicateDict
    # we iterate over list2
    return [i for i in list2 if i in list1]


def timeIt(sizes, listFunction):
    print 'size    dict    list   results match'
    for s in sizes:
        list1 = listFunction(s)
        list2 = listFunction(s)

        startTime = time.time()
        dups1 = duplicateDict(list1, list2)
        endTime = time.time()
        dictTime = endTime - startTime

        startTime = time.time()
        dups2 = duplicateList(list1, list2)
        endTime = time.time()
        listTime = endTime - startTime

        print '%6d %f %f %d' % (s, dictTime, listTime, dups1 == dups2)

print 'with dups'
timeIt([100, 1000, 10000, 50000], generateList1)
print
print 'with out dups'
timeIt([100, 1000, 5000], generateList2)

--------------080802070107090108030902--




From alex@gabuzomeu.net  Wed Jul 10 13:15:36 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Wed, 10 Jul 2002 14:15:36 +0200
Subject: [Tutor] Re: CMS written in Python
In-Reply-To: <20020709191918.5780.46189.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020710134708.033d3a90@pop3.norton.antivirus>

At 15:19 09/07/2002 -0400, you wrote:
>Date: Tue, 9 Jul 2002 11:30:05 -0500
>From: Derrick 'dman' Hudson <dman@dman.ddts.net>
>Subject: [Tutor] Re: CMS written in Python

>On Mon, Jul 08, 2002 at 07:03:18PM +0200, Alexandre Ratti wrote:
> > Are you aware of a CMS (Content Management System) written in
> > Python and available under a free-software/open-source license?

> > I am looking for a stand-alone tool I could adapt to publish a dynamic
> > Web site.
>
>zope
>quixote
>python server pages
>spyce (I think that's the name of a recent one)
>pyweblib

Yes, I'm aware of these options. I also discovered a new one yesterday 
night: CherryPy (http://www.cherrypy.org).


Cheers.

Alexandre




From pythontutor@venix.com  Wed Jul 10 13:23:46 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed, 10 Jul 2002 08:23:46 -0400
Subject: [Tutor] Re: python from shell
References: <20020709163848.GB17757@dman.ddts.net> <2959.1026297309@www23.gmx.net>
Message-ID: <3D2C2752.1070805@venix.com>

Using /usr/bin/env is generally best for people.  This discussions started
because it failed for a CGI python script.  A script that needs to run
using a server's environment may not have a "normal" path.  Much depends on
the local security policies and the sysadmin.  For those cases, if the
environment is totally outside your control, pointing directly to python
can be preferable.

lumbricus@gmx.net wrote:

>>On Tue, Jul 09, 2002 at 09:18:25AM -0500, SA wrote:
>>
> 
> [ snip ]
> 
> 
>>Here's the difference :
>>
>>/usr/bin/env is a program that searches the $PATH to find the program
>>given as it's first argument.  Then it exec's it on the input
>>(script).
>>
>>Using /usr/bin/env means that your script will automagically run on
>>any person's system *IFF* the 'python' found first in the $PATH is the
>>one you wanted to use.  It also means (due to limitations in
>>
>                                                 ^^^^^^^^^^^
> what do you mean?
> 
> 
>>linux/bash)
>>
>   ^^^^^^^^^^
> now which one?
> 
> 
>>that you can't pass any arguments to python itself (such
>>as -u or -OO).
>>
> 
>>From 'man env' on OSF1
> (no matter which shell ;-)
> 
> "  env, printenv - Displays or sets the current environment, or displays the
>   values of environment variables
> 
> SYNOPSIS
> 
>   Current Syntax
> 
>   env [-i] [name=value...] [command] [args...]
> 
> ...
> 
>   args
>       Arguments to be passed to command when it is executed.
> 
> "
> 
> It works for me.
> 
> 
>>Using the full path to the interpreter ensures that you'll be using
>>the python you want to use.
>>
> 
> _Iff_ it is there. On my system for example python is in
> /usr/local/bin. So your scripts won't run
>  
> 
>>For example, on a debian woody system, /usr/bin/python is a symlink to
>>/usr/bin/python2.1, and it is also possible for the user to have
>>/usr/bin/python2.2 as well.  On a RH 7.x system, 'python' (is it in
>>/usr/bin ?) is version 1.5 wherease 'python2' is version
>>2.<something>.  Using the env trick will yield different results on
>>different systems, and using the full path isn't compatible with all
>>systems.
>>
> 
> ACK
>  
> 
>>Pay your money and take your choice :-) (as one of my profs likes to say)
>>
> 
> But env(1) has the advantage that it sets the environment as the
> command (python) needs it - PYTHONPATH, PYTHONHOME or the like.
>  
> 
>>I choose to use the absolute path and explicitly specify the version I
>>want.  Then again, I also use debian and for debian-packaged programs
>>that is also the Policy.
>>
> 
> But this fails, if the specified version isn't there. 
> I'd prefer env(1).
>  
> [ snip ]
> 
> HAND and Greetings,
> J"o!
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From Kyle Babich" <kb@kb5.org  Wed Jul 10 14:27:44 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Wed, 10 Jul 2002 13:27:44 +0000
Subject: [Tutor] more problems, my final questions
Message-ID: <20020710132744.633876DA2F@www.fastmail.fm>

It works! :)

The only bug I have left is when trying to execute cont() I need the
sleeptime variable from custom().  How do I import it?

On Tue, 9 Jul 2002 22:35:49 -0400, "Timothy M. Brauch"
<tbrauch@mindless.com> said:
> ----- Original Message -----
> From: "Kyle Babich" <kb@kb5.org>
> To: "tutor" <tutor@python.org>
> Sent: Tuesday, July 09, 2002 10:08 PM
> Subject: [Tutor] more problems, my final questions
> 
> 
> > New problems has arisin.  I was wondering if there was way to replace:
> > if begin in "Yy":
> >         print "why is the sky blue?"
> >
> > With something like:
> > if begin == "Y" "y":
> >         print "why isn't the sky green or purple?"
> 
> You should be able to use either:
> if begin in ['Y', 'y']:
>         do something
>         ...
> or
> if begin == 'Y' or begin == 'y':
>         do something
>         ...
> 
> I am not sure which one is preferred...
> > (only unlike the code above I need something that works of course)
> >
> > I'm asking because I recently added:
> > else begin in "CustomcustomCUSTOM":
> 
> In this case, I think it would be better to use the list:
> if begin in ['Custom', 'custom', 'CUSTOM']:
>         ...
> 
> > But I had also changed the Yy and Nn to be YyYesyesYES and NnNonoNO,
> > however the o in No and the o and custom are conflicting and I'm trying
> > to find a way to fix this.  Any ideas?
> 
> Although, a solution I just thought of that might make things even
> easier...
> import string
> ...
> begin = string.lower(begin)
> if begin in ['y', 'yes']:
>         ...
> 
> The third line converts begin to all lowercase (you could just as
> arbitrarily use string.upper()) thus making the possible choices fewer.
> 
> Although, all of this is fly-by-the-seat-of-my-pants-untested code.  It
> looks correct as I type it into my email...
> 
> > Also, my final questions regaurding this program:
> > Could some one point me to an example or show me how to
> > countdown/countup time.sleep?
> > And the same goes for delaying/suspending and prematurly ending
> > time.sleep.
> 
> Someone else will have to handle this.  I will admit I only listen to
> this
> list with one ear, that is, only when I have free time, which seems to
> be
> almost never.
> 
> > If anyone sees any problems-waiting-to-happen in my program (attached)
> > please tell me.
> 
> Again, someone else...
> 
> > Thank you, this list has been so helpful.
> > --
> > Kyle
> 
>  - Tim
> 
> 
> 
> 
> 

--
Kyle



From pythontutor@venix.com  Wed Jul 10 15:37:59 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed, 10 Jul 2002 10:37:59 -0400
Subject: [Tutor] more problems, my final questions
References: <20020710132744.633876DA2F@www.fastmail.fm>
Message-ID: <3D2C46C7.7000503@venix.com>

I assume cont() is your old hour2 function.

In custom use cont( sleeptime).  This passes the sleeptime variable to
cont.  You need to change the definition of cont to something like:

def cont( sleeptime):

Now I used the same name sleeptime within both custom and cont.  This isn't
necessary, but can avoid confusion.  Also note that sleeptime is originally
set to be a StringType variable as returned by raw_input.  You will need to
convert this to a number before doing any arithmatic with it.
     sleeptime = int(sleeptime)
will do the trick so long as sleeptime is truly an integer.

You would probably be well served spending some time going through Alan Gauld's
web site:
http://www.freenetpages.co.uk/hp/alan.gauld/
Learning to program

Kyle Babich wrote:

> It works! :)
> 
> The only bug I have left is when trying to execute cont() I need the
> sleeptime variable from custom().  How do I import it?
> 
> On Tue, 9 Jul 2002 22:35:49 -0400, "Timothy M. Brauch"
> <tbrauch@mindless.com> said:
> 
>>----- Original Message -----
>>From: "Kyle Babich" <kb@kb5.org>
>>To: "tutor" <tutor@python.org>
>>Sent: Tuesday, July 09, 2002 10:08 PM
>>Subject: [Tutor] more problems, my final questions
>>
>>
>>
>>>New problems has arisin.  I was wondering if there was way to replace:
>>>if begin in "Yy":
>>>        print "why is the sky blue?"
>>>
>>>With something like:
>>>if begin == "Y" "y":
>>>        print "why isn't the sky green or purple?"
>>>
>>You should be able to use either:
>>if begin in ['Y', 'y']:
>>        do something
>>        ...
>>or
>>if begin == 'Y' or begin == 'y':
>>        do something
>>        ...
>>
>>I am not sure which one is preferred...
>>
>>>(only unlike the code above I need something that works of course)
>>>
>>>I'm asking because I recently added:
>>>else begin in "CustomcustomCUSTOM":
>>>
>>In this case, I think it would be better to use the list:
>>if begin in ['Custom', 'custom', 'CUSTOM']:
>>        ...
>>
>>
>>>But I had also changed the Yy and Nn to be YyYesyesYES and NnNonoNO,
>>>however the o in No and the o and custom are conflicting and I'm trying
>>>to find a way to fix this.  Any ideas?
>>>
>>Although, a solution I just thought of that might make things even
>>easier...
>>import string
>>...
>>begin = string.lower(begin)
>>if begin in ['y', 'yes']:
>>        ...
>>
>>The third line converts begin to all lowercase (you could just as
>>arbitrarily use string.upper()) thus making the possible choices fewer.
>>
>>Although, all of this is fly-by-the-seat-of-my-pants-untested code.  It
>>looks correct as I type it into my email...
>>
>>
>>>Also, my final questions regaurding this program:
>>>Could some one point me to an example or show me how to
>>>countdown/countup time.sleep?
>>>And the same goes for delaying/suspending and prematurly ending
>>>time.sleep.
>>>
>>Someone else will have to handle this.  I will admit I only listen to
>>this
>>list with one ear, that is, only when I have free time, which seems to
>>be
>>almost never.
>>
>>
>>>If anyone sees any problems-waiting-to-happen in my program (attached)
>>>please tell me.
>>>
>>Again, someone else...
>>
>>
>>>Thank you, this list has been so helpful.
>>>--
>>>Kyle
>>>
>> - Tim
>>
>>
>>
>>
>>
>>
> 
> --
> Kyle
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From Kyle Babich" <kb@kb5.org  Wed Jul 10 17:39:29 2002
From: Kyle Babich" <kb@kb5.org (Kyle Babich)
Date: Wed, 10 Jul 2002 16:39:29 +0000
Subject: [Tutor] more problems, my final questions
Message-ID: <20020710163930.0CB346DA84@www.fastmail.fm>

Yes, I've read that tutorial before.  It was nice, but the one that
taught me the most by far was:
http://blacksun.box.sk/tutorials/python.htm

Anyway, I came up with a work around where I write sleeptime to a
temporary file and extract it later.  I have narrowed my last problem
down to this:

logret = open( "custom.dat", "r" )
slptm = logret.read()
logret.close()
			
time.sleep( slptm * 60 )

Why can't I do that?

I tried in IDLE and I can do similar things like:

>>> slptm = 10
>>> import time
>>> time.sleep( slptm * 1 )

So what went wrong and how would I fix this?

Thank you again,
Kyle

On Wed, 10 Jul 2002 10:37:59 -0400, "Lloyd Kvam"
<pythontutor@venix.com> said:
> I assume cont() is your old hour2 function.
> 
> In custom use cont( sleeptime).  This passes the sleeptime variable to
> cont.  You need to change the definition of cont to something like:
> 
> def cont( sleeptime):
> 
> Now I used the same name sleeptime within both custom and cont.  This
> isn't
> necessary, but can avoid confusion.  Also note that sleeptime is
> originally
> set to be a StringType variable as returned by raw_input.  You will
> need to
> convert this to a number before doing any arithmatic with it.
>      sleeptime = int(sleeptime)
> will do the trick so long as sleeptime is truly an integer.
> 
> You would probably be well served spending some time going through Alan
> Gauld's
> web site:
> http://www.freenetpages.co.uk/hp/alan.gauld/
> Learning to program
> 
> Kyle Babich wrote:
> 
> > It works! :)
> > 
> > The only bug I have left is when trying to execute cont() I need the
> > sleeptime variable from custom().  How do I import it?
> > 
> > On Tue, 9 Jul 2002 22:35:49 -0400, "Timothy M. Brauch"
> > <tbrauch@mindless.com> said:
> > 
> >>----- Original Message -----
> >>From: "Kyle Babich" <kb@kb5.org>
> >>To: "tutor" <tutor@python.org>
> >>Sent: Tuesday, July 09, 2002 10:08 PM
> >>Subject: [Tutor] more problems, my final questions
> >>
> >>
> >>
> >>>New problems has arisin.  I was wondering if there was way to replace:
> >>>if begin in "Yy":
> >>>        print "why is the sky blue?"
> >>>
> >>>With something like:
> >>>if begin == "Y" "y":
> >>>        print "why isn't the sky green or purple?"
> >>>
> >>You should be able to use either:
> >>if begin in ['Y', 'y']:
> >>        do something
> >>        ...
> >>or
> >>if begin == 'Y' or begin == 'y':
> >>        do something
> >>        ...
> >>
> >>I am not sure which one is preferred...
> >>
> >>>(only unlike the code above I need something that works of course)
> >>>
> >>>I'm asking because I recently added:
> >>>else begin in "CustomcustomCUSTOM":
> >>>
> >>In this case, I think it would be better to use the list:
> >>if begin in ['Custom', 'custom', 'CUSTOM']:
> >>        ...
> >>
> >>
> >>>But I had also changed the Yy and Nn to be YyYesyesYES and NnNonoNO,
> >>>however the o in No and the o and custom are conflicting and I'm trying
> >>>to find a way to fix this.  Any ideas?
> >>>
> >>Although, a solution I just thought of that might make things even
> >>easier...
> >>import string
> >>...
> >>begin = string.lower(begin)
> >>if begin in ['y', 'yes']:
> >>        ...
> >>
> >>The third line converts begin to all lowercase (you could just as
> >>arbitrarily use string.upper()) thus making the possible choices fewer.
> >>
> >>Although, all of this is fly-by-the-seat-of-my-pants-untested code.  It
> >>looks correct as I type it into my email...
> >>
> >>
> >>>Also, my final questions regaurding this program:
> >>>Could some one point me to an example or show me how to
> >>>countdown/countup time.sleep?
> >>>And the same goes for delaying/suspending and prematurly ending
> >>>time.sleep.
> >>>
> >>Someone else will have to handle this.  I will admit I only listen to
> >>this
> >>list with one ear, that is, only when I have free time, which seems to
> >>be
> >>almost never.
> >>
> >>
> >>>If anyone sees any problems-waiting-to-happen in my program (attached)
> >>>please tell me.
> >>>
> >>Again, someone else...
> >>
> >>
> >>>Thank you, this list has been so helpful.
> >>>--
> >>>Kyle
> >>>
> >> - Tim
> >>
> >>
> >>
> >>
> >>
> >>
> > 
> > --
> > Kyle
> > 
> > 
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> > 
> 
> 
> -- 
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
> 
> voice: 
> 603-443-6155
> fax: 
> 801-459-9582
> 
> 
> 
> 
> 

--
Kyle



From ak@silmarill.org  Wed Jul 10 18:29:42 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Wed, 10 Jul 2002 13:29:42 -0400
Subject: [Tutor] more problems, my final questions
In-Reply-To: <20020710163930.0CB346DA84@www.fastmail.fm>
References: <20020710163930.0CB346DA84@www.fastmail.fm>
Message-ID: <20020710172942.GA464@ak.silmarill.org>

On Wed, Jul 10, 2002 at 04:39:29PM +0000, Kyle Babich wrote:
> Yes, I've read that tutorial before.  It was nice, but the one that
> taught me the most by far was:
> http://blacksun.box.sk/tutorials/python.htm
> 
> Anyway, I came up with a work around where I write sleeptime to a
> temporary file and extract it later.  I have narrowed my last problem
> down to this:
> 
> logret = open( "custom.dat", "r" )
> slptm = logret.read()
> logret.close()
> 			
> time.sleep( slptm * 60 )
>
It is read in as a string: "12" (for example). You have to convert it
to an integer: int("12") => 12

>>> slptm = int("12")
>>> >>> slptm
>>> >>> 12
>>> >>>
> 
> Why can't I do that?
> 
> I tried in IDLE and I can do similar things like:
> 
> >>> slptm = 10
> >>> import time
> >>> time.sleep( slptm * 1 )
> 
> So what went wrong and how would I fix this?
> 
> Thank you again,
> Kyle
> 
> On Wed, 10 Jul 2002 10:37:59 -0400, "Lloyd Kvam"
> <pythontutor@venix.com> said:
> > I assume cont() is your old hour2 function.
> > 
> > In custom use cont( sleeptime).  This passes the sleeptime variable to
> > cont.  You need to change the definition of cont to something like:
> > 
> > def cont( sleeptime):
> > 
> > Now I used the same name sleeptime within both custom and cont.  This
> > isn't
> > necessary, but can avoid confusion.  Also note that sleeptime is
> > originally
> > set to be a StringType variable as returned by raw_input.  You will
> > need to
> > convert this to a number before doing any arithmatic with it.
> >      sleeptime = int(sleeptime)
> > will do the trick so long as sleeptime is truly an integer.
> > 
> > You would probably be well served spending some time going through Alan
> > Gauld's
> > web site:
> > http://www.freenetpages.co.uk/hp/alan.gauld/
> > Learning to program
> > 
> > Kyle Babich wrote:
> > 
> > > It works! :)
> > > 
> > > The only bug I have left is when trying to execute cont() I need the
> > > sleeptime variable from custom().  How do I import it?
> > > 
> > > On Tue, 9 Jul 2002 22:35:49 -0400, "Timothy M. Brauch"
> > > <tbrauch@mindless.com> said:
> > > 
> > >>----- Original Message -----
> > >>From: "Kyle Babich" <kb@kb5.org>
> > >>To: "tutor" <tutor@python.org>
> > >>Sent: Tuesday, July 09, 2002 10:08 PM
> > >>Subject: [Tutor] more problems, my final questions
> > >>
> > >>
> > >>
> > >>>New problems has arisin.  I was wondering if there was way to replace:
> > >>>if begin in "Yy":
> > >>>        print "why is the sky blue?"
> > >>>
> > >>>With something like:
> > >>>if begin == "Y" "y":
> > >>>        print "why isn't the sky green or purple?"
> > >>>
> > >>You should be able to use either:
> > >>if begin in ['Y', 'y']:
> > >>        do something
> > >>        ...
> > >>or
> > >>if begin == 'Y' or begin == 'y':
> > >>        do something
> > >>        ...
> > >>
> > >>I am not sure which one is preferred...
> > >>
> > >>>(only unlike the code above I need something that works of course)
> > >>>
> > >>>I'm asking because I recently added:
> > >>>else begin in "CustomcustomCUSTOM":
> > >>>
> > >>In this case, I think it would be better to use the list:
> > >>if begin in ['Custom', 'custom', 'CUSTOM']:
> > >>        ...
> > >>
> > >>
> > >>>But I had also changed the Yy and Nn to be YyYesyesYES and NnNonoNO,
> > >>>however the o in No and the o and custom are conflicting and I'm trying
> > >>>to find a way to fix this.  Any ideas?
> > >>>
> > >>Although, a solution I just thought of that might make things even
> > >>easier...
> > >>import string
> > >>...
> > >>begin = string.lower(begin)
> > >>if begin in ['y', 'yes']:
> > >>        ...
> > >>
> > >>The third line converts begin to all lowercase (you could just as
> > >>arbitrarily use string.upper()) thus making the possible choices fewer.
> > >>
> > >>Although, all of this is fly-by-the-seat-of-my-pants-untested code.  It
> > >>looks correct as I type it into my email...
> > >>
> > >>
> > >>>Also, my final questions regaurding this program:
> > >>>Could some one point me to an example or show me how to
> > >>>countdown/countup time.sleep?
> > >>>And the same goes for delaying/suspending and prematurly ending
> > >>>time.sleep.
> > >>>
> > >>Someone else will have to handle this.  I will admit I only listen to
> > >>this
> > >>list with one ear, that is, only when I have free time, which seems to
> > >>be
> > >>almost never.
> > >>
> > >>
> > >>>If anyone sees any problems-waiting-to-happen in my program (attached)
> > >>>please tell me.
> > >>>
> > >>Again, someone else...
> > >>
> > >>
> > >>>Thank you, this list has been so helpful.
> > >>>--
> > >>>Kyle
> > >>>
> > >> - Tim
> > >>
> > >>
> > >>
> > >>
> > >>
> > >>
> > > 
> > > --
> > > Kyle
> > > 
> > > 
> > > _______________________________________________
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > > 
> > > 
> > 
> > 
> > -- 
> > Lloyd Kvam
> > Venix Corp.
> > 1 Court Street, Suite 378
> > Lebanon, NH 03766-1358
> > 
> > voice: 
> > 603-443-6155
> > fax: 
> > 801-459-9582
> > 
> > 
> > 
> > 
> > 
> 
> --
> Kyle
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From jeff@ccvcorp.com  Wed Jul 10 18:28:03 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed, 10 Jul 2002 10:28:03 -0700
Subject: [Tutor] more problems, my final questions
References: <20020710163930.0CB346DA84@www.fastmail.fm>
Message-ID: <3D2C6EA3.28D00128@ccvcorp.com>

Kyle Babich wrote:

> Anyway, I came up with a work around where I write sleeptime to a
> temporary file and extract it later.  I have narrowed my last problem
> down to this:
>
> logret = open( "custom.dat", "r" )
> slptm = logret.read()
> logret.close()
>
> time.sleep( slptm * 60 )
>
> Why can't I do that?

When you read something from a file, you get a string object.  Strings don't
allow arithmetic -- you need to convert the string into an integer first.

time.sleep( int(slptim) * 60 )

In your experimentations in IDLE, you were already using an integer, so you
didn't have this problem.

Btw, when something doesn't work like this, it's usually best if you can copy &
paste the exception (including the entire traceback).  That makes it easier for
us to figure out where it's failing, and why...    :)

Jeff Shannon
Technician/Programmer
Credit International







From ianb@colorstudy.com  Wed Jul 10 03:50:49 2002
From: ianb@colorstudy.com (Ian Bicking)
Date: 09 Jul 2002 21:50:49 -0500
Subject: [Tutor] Re: How to grab a part of web page?
In-Reply-To: <3D2B6810.13895.8A3A7A@localhost>
References: <3D2B6810.13895.8A3A7A@localhost>
Message-ID: <1026269450.543.33.camel@lothlorien.colorstudy.net>

I don't know if this is built in to any Python library.  You may have to
use httplib.  There are HTTP headers (which I don't remember at the
moment -- you'd have to look them up somewhere) that allow you to
request a specific byte range (though I don't believe the server has to
honor that request -- it may return the entire page).  httplib allows
(and requires) you to set all your headers.  Though it looks like you
could just use the urllib2.Request to put in your specific headers...
I'm not that familiar with that module.

You definitely don't have to use the socket module.

On Tue, 2002-07-09 at 15:47, A wrote:
> Hi,
> Is it possible to download only a part of web page?
> Say I need to find out an information about a customer that starts 
> at 1500 byte position and ends at 2000 byte position. If the whole 
> page has about 100 kb it seems to me waste of time to load all the 
> page.
> What is the best, yet easy, solution?
> Is it possible to use httplib or necessary socket module?
> Thank you for help.
> Ladislav
> 
>  
> 
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list





From trevor.newton@bt.com  Wed Jul 10 11:37:30 2002
From: trevor.newton@bt.com (trevor.newton@bt.com)
Date: Wed, 10 Jul 2002 11:37:30 +0100
Subject: [Tutor] Help in debugging some Python code.
Message-ID: <5F54BE0116BCD2118C9400606DD614ED0F377FAF@mclmsent02.lon.bt.com>

Chaps,

I was wondering if any of you could suggest a strategy for solving a small
problem that I have with a DNS utility that I downloaded from
http://www.interlink.com.au/anthony/python/dns.tar.gz after following a link
from the Vaults site. This utility comes with a number of small test
programs, but when I run them they report the following :

Traceback (most recent call last):
  File "test.py", line 12, in ?
    a=r.req()
  File "/usr/local/lib/python2.2/site-packages/DNS/Base.py", line 148, in
req
    m.addQuestion(qname, qtype, DNS.Class.IN)
  File "/usr/local/lib/python2.2/site-packages/DNS/Lib.py", line 427, in
addQuestion
    self.addname(qname)
  File "/usr/local/lib/python2.2/site-packages/DNS/Lib.py", line 105, in
addname
    index.append(keys[j], offset + len(buf))
TypeError: append() takes exactly one argument (2 given)

Now I suspect that this utility was written for a previous version of
Python, I'm using version 2.2 as you can see. I also suspect that the
reported error is not the root of the problem but being inexperienced I
don't know where to start looking for a solution. Any suggestions.

Regards,

            Trevor.



From ashish@shrestha.net.np  Wed Jul 10 06:24:51 2002
From: ashish@shrestha.net.np (Ashish Shrestha)
Date: Wed, 10 Jul 2002 11:09:51 +0545
Subject: [Tutor] Old friend revisited - just for fun!
References: <B950A947.93D9%sarmstrong13@mac.com> <001801c2278e$d9b1e970$1615a8c0@mega>
Message-ID: <3D2BC523.10702@shrestha.net.np>

nice, but needed to change a line

@line 110:
for cell in self.neighbors: -> for cell in self.neighbors.keys():




From lkvam@venix.com  Wed Jul 10 15:36:41 2002
From: lkvam@venix.com (Lloyd Kvam)
Date: Wed, 10 Jul 2002 10:36:41 -0400
Subject: [Tutor] more problems, my final questions
References: <20020710132744.633876DA2F@www.fastmail.fm>
Message-ID: <3D2C4679.4070405@venix.com>

I assume cont() is your old hour2 function.

In custom use cont( sleeptime).  This passes the sleeptime variable to
cont.  You need to change the definition of cont to something like:

def cont( sleeptime):

Now I used the same name sleeptime within both custom and cont.  This isn't
necessary, but can avoid confusion.  Also note that sleeptime is originally
set to be a StringType variable as returned by raw_input.  You will need to
convert this to a number before doing any arithmatic with it.
	sleeptime = int(sleeptime)
will do the trick so long as sleeptime is truly an integer.

You would probably be well served spending some time going through Alan Gauld's
web site:
http://www.freenetpages.co.uk/hp/alan.gauld/
Learning to program

Kyle Babich wrote:

> It works! :)
> 
> The only bug I have left is when trying to execute cont() I need the
> sleeptime variable from custom().  How do I import it?
> 
> On Tue, 9 Jul 2002 22:35:49 -0400, "Timothy M. Brauch"
> <tbrauch@mindless.com> said:
> 
>>----- Original Message -----
>>From: "Kyle Babich" <kb@kb5.org>
>>To: "tutor" <tutor@python.org>
>>Sent: Tuesday, July 09, 2002 10:08 PM
>>Subject: [Tutor] more problems, my final questions
>>
>>
>>
>>>New problems has arisin.  I was wondering if there was way to replace:
>>>if begin in "Yy":
>>>        print "why is the sky blue?"
>>>
>>>With something like:
>>>if begin == "Y" "y":
>>>        print "why isn't the sky green or purple?"
>>>
>>You should be able to use either:
>>if begin in ['Y', 'y']:
>>        do something
>>        ...
>>or
>>if begin == 'Y' or begin == 'y':
>>        do something
>>        ...
>>
>>I am not sure which one is preferred...
>>
>>>(only unlike the code above I need something that works of course)
>>>
>>>I'm asking because I recently added:
>>>else begin in "CustomcustomCUSTOM":
>>>
>>In this case, I think it would be better to use the list:
>>if begin in ['Custom', 'custom', 'CUSTOM']:
>>        ...
>>
>>
>>>But I had also changed the Yy and Nn to be YyYesyesYES and NnNonoNO,
>>>however the o in No and the o and custom are conflicting and I'm trying
>>>to find a way to fix this.  Any ideas?
>>>
>>Although, a solution I just thought of that might make things even
>>easier...
>>import string
>>...
>>begin = string.lower(begin)
>>if begin in ['y', 'yes']:
>>        ...
>>
>>The third line converts begin to all lowercase (you could just as
>>arbitrarily use string.upper()) thus making the possible choices fewer.
>>
>>Although, all of this is fly-by-the-seat-of-my-pants-untested code.  It
>>looks correct as I type it into my email...
>>
>>
>>>Also, my final questions regaurding this program:
>>>Could some one point me to an example or show me how to
>>>countdown/countup time.sleep?
>>>And the same goes for delaying/suspending and prematurly ending
>>>time.sleep.
>>>
>>Someone else will have to handle this.  I will admit I only listen to
>>this
>>list with one ear, that is, only when I have free time, which seems to
>>be
>>almost never.
>>
>>
>>>If anyone sees any problems-waiting-to-happen in my program (attached)
>>>please tell me.
>>>
>>Again, someone else...
>>
>>
>>>Thank you, this list has been so helpful.
>>>--
>>>Kyle
>>>
>> - Tim
>>
>>
>>
>>
>>
>>
> 
> --
> Kyle
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From dyoo@hkn.eecs.berkeley.edu  Wed Jul 10 19:11:58 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 10 Jul 2002 11:11:58 -0700 (PDT)
Subject: [Tutor] Re: *****SPAM***** REMOVE
In-Reply-To: <200207111528.g6BFSZ706087@striper.digitronicweb.com>
Message-ID: <Pine.LNX.4.44.0207101109350.15816-100000@hkn.eecs.berkeley.edu>


On Thu, 11 Jul 2002 leucadia@web.digitronicweb.com wrote:

> REMOVE ME your comments are flooding my mail server!!!!!! ALL DAY
> LONG!!!!

Hi Kyle,


Yikes, leucadia's pretty angry...

You can ignore that message from leucadia@webdigitronicweb.com: the Tutor
admins are handling it now.  Leucadia shouldn't have sent his complaint to
you, so don't worry about it.


Best of wishes to you!




From dyoo@hkn.eecs.berkeley.edu  Wed Jul 10 20:05:58 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 10 Jul 2002 12:05:58 -0700 (PDT)
Subject: [Tutor] Help in debugging some Python code.
In-Reply-To: <5F54BE0116BCD2118C9400606DD614ED0F377FAF@mclmsent02.lon.bt.com>
Message-ID: <Pine.LNX.4.44.0207101201440.17720-100000@hkn.eecs.berkeley.edu>


> Traceback (most recent call last):
>   File "test.py", line 12, in ?
>     a=r.req()
>   File "/usr/local/lib/python2.2/site-packages/DNS/Base.py", line 148, in
> req
>     m.addQuestion(qname, qtype, DNS.Class.IN)
>   File "/usr/local/lib/python2.2/site-packages/DNS/Lib.py", line 427, in
> addQuestion
>     self.addname(qname)
>   File "/usr/local/lib/python2.2/site-packages/DNS/Lib.py", line 105, in
> addname
>     index.append(keys[j], offset + len(buf))
> TypeError: append() takes exactly one argument (2 given)
>
> Now I suspect that this utility was written for a previous version of
> Python, I'm using version 2.2 as you can see. I also suspect that the
> reported error is not the root of the problem but being inexperienced I
> don't know where to start looking for a solution. Any suggestions.

Hi Trevor,


My initial guess iwould be to change:

    index.append(keys[j], offset + len(buf))       ## Buggy

to:

    index.append((keys[j],
                  offset + len(buf)))              ## Better


The append() method was changed between an old release of Python and the
more recent versions: the old version implicitely inserted a tuple
collection if we gave append() more arguments, but this seemed somewhat
magical and was seen as a language defect for a while.

The recent version of Python requires us to explictely say that we're
inserting that tuple, which is what that extra set of parentheses does.


Hope this helps!




From pythontutor@venix.com  Wed Jul 10 20:21:07 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed, 10 Jul 2002 15:21:07 -0400
Subject: [Tutor] leave of absence
Message-ID: <3D2C8923.60804@venix.com>

I shall be concentrating more on my software development efforts for
the next couple of months and not watching the tutor list.  It has been
a wonderful education.  Special thanks to Alan, dman, Jeff, and Danny
for their advice and work that make this list such a great resource.

Hopefully, I'll be back before too long.

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From Michael Montagne <montagne@boora.com>  Wed Jul 10 20:57:11 2002
From: Michael Montagne <montagne@boora.com> (Michael Montagne)
Date: Wed, 10 Jul 2002 12:57:11 -0700
Subject: [Tutor] Search path
Message-ID: <20020710195711.GA29897@boora.com>

I need to add to the python search path a directory that contains my
personal modules.  This way it will always be safe from upgrading and I
may easily back it up.  How do I tell python to always include this
directory in the search path?  Is this even the recommended way to
handle this issue?  Does it have something to do with .pth files?

-- 
  Michael Montagne  [montagne@boora.com]   503.226.1575 
--    



From dyoo@hkn.eecs.berkeley.edu  Wed Jul 10 21:06:39 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 10 Jul 2002 13:06:39 -0700 (PDT)
Subject: [Tutor] leave of absence
In-Reply-To: <3D2C8923.60804@venix.com>
Message-ID: <Pine.LNX.4.44.0207101305260.19399-100000@hkn.eecs.berkeley.edu>


On Wed, 10 Jul 2002, Lloyd Kvam wrote:

> I shall be concentrating more on my software development efforts for the
> next couple of months and not watching the tutor list.  It has been a
> wonderful education.  Special thanks to Alan, dman, Jeff, and Danny for
> their advice and work that make this list such a great resource.

Best of wishes to you, Lloyd!



> Hopefully, I'll be back before too long.

I've heard (or said) that before.  *cough*




From jeff@ccvcorp.com  Wed Jul 10 21:06:44 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed, 10 Jul 2002 13:06:44 -0700
Subject: [Tutor] Search path
References: <20020710195711.GA29897@boora.com>
Message-ID: <3D2C93D4.23739FE@ccvcorp.com>


Michael Montagne wrote:

> I need to add to the python search path a directory that contains my
> personal modules.  This way it will always be safe from upgrading and I
> may easily back it up.  How do I tell python to always include this
> directory in the search path?  Is this even the recommended way to
> handle this issue?  Does it have something to do with .pth files?

Yes.  You create a .pth file, with each line of the file being the name of
a directory.  On startup, Python will parse all the .pth files it finds,
and will add each listed directory to the import search path.

Jeff Shannon
Technician/Programmer
Credit International





From ak@silmarill.org  Wed Jul 10 21:40:09 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Wed, 10 Jul 2002 16:40:09 -0400
Subject: [Tutor] Search path
In-Reply-To: <20020710195711.GA29897@boora.com>
References: <20020710195711.GA29897@boora.com>
Message-ID: <20020710204009.GA1942@ak.silmarill.org>

On Wed, Jul 10, 2002 at 12:57:11PM -0700, Michael Montagne wrote:
> I need to add to the python search path a directory that contains my
> personal modules.  This way it will always be safe from upgrading and I
> may easily back it up.  How do I tell python to always include this
> directory in the search path?  Is this even the recommended way to
> handle this issue?  Does it have something to do with .pth files?
> 
> -- 
>   Michael Montagne  [montagne@boora.com]   503.226.1575 
> --    
>

Set PYTHONPATH environment variable, e.g. in .bashrc:

export PYTHONPATH=/home/ak/.python

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

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From Michael Montagne <montagne@boora.com>  Wed Jul 10 21:55:05 2002
From: Michael Montagne <montagne@boora.com> (Michael Montagne)
Date: Wed, 10 Jul 2002 13:55:05 -0700
Subject: [Tutor] Search path
In-Reply-To: <3D2C93D4.23739FE@ccvcorp.com>
References: <20020710195711.GA29897@boora.com> <3D2C93D4.23739FE@ccvcorp.com>
Message-ID: <20020710205505.GA30307@boora.com>

I added created /usr/lib/python2.1/mjm.pth that contained these paths
/home/montagne/python
/home/montagne/bin
/home/montagne/share

but it seems to have no effect.  
Setting the PYTHONPATH variable in .bashrc seemed to work tho.

I thought that .pth files were somehow connected to specific modules.

>On 10/07/02, from the brain of Jeff Shannon tumbled:

> 
> 
> Michael Montagne wrote:
> 
> > I need to add to the python search path a directory that contains my
> > personal modules.  This way it will always be safe from upgrading and I
> > may easily back it up.  How do I tell python to always include this
> > directory in the search path?  Is this even the recommended way to
> > handle this issue?  Does it have something to do with .pth files?
> 
> Yes.  You create a .pth file, with each line of the file being the name of
> a directory.  On startup, Python will parse all the .pth files it finds,
> and will add each listed directory to the import search path.
> 
> Jeff Shannon
> Technician/Programmer
> Credit International

-- 
  Michael Montagne  [montagne@boora.com]   503.226.1575 
--    



From tbrauch@mindless.com  Wed Jul 10 22:18:18 2002
From: tbrauch@mindless.com (Timothy M. Brauch)
Date: Wed, 10 Jul 2002 17:18:18 -0400
Subject: [Tutor] import pwd?
Message-ID: <000501c22857$506a3a40$9c21840a@tmbrau00>

I have a problem.  The program runs on a windows computer and generates a
log of anyone who logins.  I have a script that uses getpass, specifically,
getpass.getuser().  However, since I (re)installed Python 2.2 and VPython, I
receive the following error:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in ?
    import logger
  File "c:\python22\programs\logger.pyw", line 35, in ?
    user = getpass.getuser()
  File "C:\PYTHON22\lib\getpass.py", line 101, in getuser
    import pwd
ImportError: No module named pwd

So, where is pwd?

I have test_pwd.py and module-pwd.html in my Python directory, but no pwd.
 - Tim




From tbrauch@mindless.com  Thu Jul 11 00:01:25 2002
From: tbrauch@mindless.com (Timothy M. Brauch)
Date: Wed, 10 Jul 2002 19:01:25 -0400
Subject: [Tutor] Verifying a data...
Message-ID: <000701c22865$b7f09340$9c21840a@tmbrau00>

I've run into a snag in one of my programs.  I am attempting to write a
program for matrices, from scratch no less.  In part to help me learn python
and in part so that features are not available that I do not want students
to have.

So far, I can do many matrix manipulations; however, the part that is
causing problems is verifying that what was entered was an actual valid
matrix.  I want the matrix to be able to be a single row of integers (or
floats now that I think about it), or a list of lists of integers.  Of
course, I need all the rows to be the same length.  As long as it is a valid
matrix, all my other operations work as expected.

What I have so far to verifiy, but does not work correctly, is:

def verify_matrix(mtrx):
## check if first item is integer
    if type(mtrx[0]) == type(1):
        ## if integer, all must integers
        for r in mtrx:
            if type(r) != type(1):
                return __dimensionError__('dimension mismatch in creation')
            else: return mtrx
    ## if first item not integer, must be a list
    elif type(mtrx[0]) == type([]):
    ## all lists must be same length
    ##I should probably check that list is made up of only ints as well
(later)
        length = len(mtrx[0])
        for r in mtrx:
            if len(r) != length:
                return __dimentionError__('dimension mismatch in creation')
            else: return mtrx
    else:
        print 'Invalid matrix'
        return None

I tried running this, and got:

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> import matrix
>>> M = matrix
>>> m = M.matrix([[1,2],[3,4]])
>>> m
[[1, 2], [3, 4]]
>>> M.display_matrix(m)
[1, 2]
[3, 4]
>>> a = M.matrix([1, 2, [3, 4]])
>>> M.display_matrix(a)
1
2
[3, 4]
>>>

Shouldn't I get a dimensionError when I create 'a'?

I really thought I was understanding this.. aargh.

 - Tim




From dyoo@hkn.eecs.berkeley.edu  Thu Jul 11 01:18:18 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 10 Jul 2002 17:18:18 -0700 (PDT)
Subject: [Tutor] Verifying a data...
In-Reply-To: <000701c22865$b7f09340$9c21840a@tmbrau00>
Message-ID: <Pine.LNX.4.44.0207101701310.25611-100000@hkn.eecs.berkeley.edu>


On Wed, 10 Jul 2002, Timothy M. Brauch wrote:

> I've run into a snag in one of my programs.  I am attempting to write a
> program for matrices, from scratch no less.  In part to help me learn python
> and in part so that features are not available that I do not want students
> to have.
>
> So far, I can do many matrix manipulations; however, the part that is
> causing problems is verifying that what was entered was an actual valid
> matrix.  I want the matrix to be able to be a single row of integers (or
> floats now that I think about it), or a list of lists of integers.  Of
> course, I need all the rows to be the same length.  As long as it is a valid
> matrix, all my other operations work as expected.
>
> What I have so far to verifiy, but does not work correctly, is:
>
> def verify_matrix(mtrx):
> ## check if first item is integer
>     if type(mtrx[0]) == type(1):
>         ## if integer, all must integers
>         for r in mtrx:
>             if type(r) != type(1):
>                 return __dimensionError__('dimension mismatch in creation')
>             else: return mtrx
              ^^^^^^^^^^^^^^^^^
Hi Timothy,

The last line here causes the bug: it's returning too quickly, convinced
that the matrix is good, even though it doesn't look through the whole
array.  It's a subtle bug, and all too easy to make, so don't worry too
much about it.


To correct this, pull the 'return mtrx' step out of the for loop: if we
get up to the return statement, that means that all of the other matrix
elements checked out fine:

###
# Within the verifymatrix() definition:

    for r in mtrx:
        if type(r) != type(1):
            return __dimensionError__('dimension mismatch in creation')
    return mtrx

###



Because it's easy to get caught by this bug, it might be better to use a
little functional programming to make the code clearer.  Here's one way to
rewrite that code:

###
def any(boolean_function, sequence):
    """Returns true if any element within our sequences satisfies our
boolean_function"""
    for s in sequence:
        if boolean_function(s):
            return 1
    return 0
###


This 'any()' function works across any sequence type.  Here are some
examples of how it works:

###
>>> def isEven(x): return x % 2 == 0
...
>>> any(isEven, [1, 3, 5, 6, 9])
1
>>> any(isEven, [1, 3, 5, 7, 9])
0
###

Here, it makes it easy to ask "Are there any elements in this list that
are even?"  No need to our code to use loops, since it's handled
internally by any()



Using this, now we can easily ask: "are any of the following list elements
non-integers?"

###
def isInteger(thing): return type(thing) == type(1)
def isNonInteger(thing): return not isInteger(thing)


def verify_matrix(mtrx):
## check if first item is integer
    if type(mtrx[0]) == type(1) and any(isNonInteger, mtrx):
        return __dimensionError__('dimension mismatch in creation')
    # ... [put rest of code here]
###



If you have more questions, please feel free to ask.  Hope this helps!





From tbrauch@tbrauch.com  Thu Jul 11 04:38:13 2002
From: tbrauch@tbrauch.com (Timothy M. Brauch)
Date: Wed, 10 Jul 2002 23:38:13 -0400
Subject: [Tutor] Verifying a data...
References: <Pine.LNX.4.44.0207101701310.25611-100000@hkn.eecs.berkeley.edu>
Message-ID: <000801c2288c$656d7580$9c21840a@tmbrau00>

Danny enlightened us with:
>
> On Wed, 10 Jul 2002, Timothy M. Brauch wrote:
> > I've run into a snag in one of my programs.  I am attempting to write a
> > program for matrices, from scratch no less.  In part to help me learn
python
> > and in part so that features are not available that I do not want
students
> > to have.
> >
> > So far, I can do many matrix manipulations; however, the part that is
> > causing problems is verifying that what was entered was an actual valid
> > matrix.  I want the matrix to be able to be a single row of integers (or
> > floats now that I think about it), or a list of lists of integers.  Of
> > course, I need all the rows to be the same length.  As long as it is a
valid
> > matrix, all my other operations work as expected.
> >
> > What I have so far to verifiy, but does not work correctly, is:
> >
> > def verify_matrix(mtrx):
> > ## check if first item is integer
> >     if type(mtrx[0]) == type(1):
> >         ## if integer, all must integers
> >         for r in mtrx:
> >             if type(r) != type(1):
> >                 return __dimensionError__('dimension mismatch in
creation')
> >             else: return mtrx
>               ^^^^^^^^^^^^^^^^^
> Hi Timothy,
>
> The last line here causes the bug: it's returning too quickly, convinced
> that the matrix is good, even though it doesn't look through the whole
> array.  It's a subtle bug, and all too easy to make, so don't worry too
> much about it.

Aargh, when I was programming in Java (my other, albeit less, familiar
language) indentation didn't matter as long as I closed the }.  But then
again, I got stuck in the counting braces and ended up indenting anyway.

> To correct this, pull the 'return mtrx' step out of the for loop: if we
> get up to the return statement, that means that all of the other matrix
> elements checked out fine:
>
> ###
> # Within the verifymatrix() definition:
>
>     for r in mtrx:
>         if type(r) != type(1):
>             return __dimensionError__('dimension mismatch in creation')
>     return mtrx
>
> ###
> Because it's easy to get caught by this bug, it might be better to use a
> little functional programming to make the code clearer.  Here's one way to
> rewrite that code:
>
> ###
> def any(boolean_function, sequence):
>     """Returns true if any element within our sequences satisfies our
> boolean_function"""
>     for s in sequence:
>         if boolean_function(s):
>             return 1
>     return 0
> ###
>
> This 'any()' function works across any sequence type.  Here are some
> examples of how it works:
>
> ###
> >>> def isEven(x): return x % 2 == 0
> ...
> >>> any(isEven, [1, 3, 5, 6, 9])
> 1
> >>> any(isEven, [1, 3, 5, 7, 9])
> 0
> ###
>
> Here, it makes it easy to ask "Are there any elements in this list that
> are even?"  No need to our code to use loops, since it's handled
> internally by any()
>
> Using this, now we can easily ask: "are any of the following list elements
> non-integers?"
>
> ###
> def isInteger(thing): return type(thing) == type(1)
> def isNonInteger(thing): return not isInteger(thing)
>
> def verify_matrix(mtrx):
> ## check if first item is integer
>     if type(mtrx[0]) == type(1) and any(isNonInteger, mtrx):
>         return __dimensionError__('dimension mismatch in creation')
>     # ... [put rest of code here]
> ###
> If you have more questions, please feel free to ask.  Hope this helps!

Okay, now I've got it working.  And, I'm done with all the simple matrix
operations, such as addition, scalar multiplication and matrix
multiplication.  And, I still have two months to pour over my algorithms
books and linear algebra texts to finish up some of the features.  Then to
unleash this beast on my students and pray they don't break it, too badly.

 - Tim




From slime@vsnl.net  Thu Jul 11 06:51:33 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Thu, 11 Jul 2002 11:21:33 +0530
Subject: [Tutor] Re:  Verifying a data...
In-Reply-To: <000701c22865$b7f09340$9c21840a@tmbrau00>
References: <000701c22865$b7f09340$9c21840a@tmbrau00>
Message-ID: <20020711055132.GA6449@localhost.localdomain>

Hi,

On Wed, 10 Jul 2002 Timothy M. Brauch spewed into the ether:
> I've run into a snag in one of my programs.  I am attempting to write a
> program for matrices, from scratch no less.  In part to help me learn python
> and in part so that features are not available that I do not want students
> to have.

    I have just recently written a matrix module, and I've put it up
here, in case you are interested :

    http://www.symonds.net/~prahladv/files/matrix.py

> So far, I can do many matrix manipulations; however, the part that is
> causing problems is verifying that what was entered was an actual valid
> matrix.  I want the matrix to be able to be a single row of integers (or
> floats now that I think about it), or a list of lists of integers.  Of
> course, I need all the rows to be the same length.  As long as it is a valid
> matrix, all my other operations work as expected.

    Well, Danny has pointed out the bug in your code, but I did
something which, IMHO, is a better way of verifying the matrix. In order
to verify the matrix, I've defined a __setitem__() method, like so :

"""
class Matrix :
    ...
    ...
    def __setitem__ (self, (row,column), value) :
        """Sets the value of the element.

        Note: Currently only accepts integers, floating point
              values, or complex numbers.
        """
        if type(value) not in [type(1), type(1.0), type(complex(1,1))] :
            raise TypeError, "Incorrect assignment of %s" % type(value)
        self.matrix[row][column] = value
"""

Now, this is how it works :

"""

$ python
Python 2.2 (#1, Jul 10 2002, 08:12:39)
[GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> import matrix
>>> a = matrix.Matrix() ## Initializes a 3x3 Null matrix
>>> a[1,2] = 1
>>> print a
[0, 0, 0]
[0, 0, 1]
[0, 0, 0]
>>> a[2,1] = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/home/prahlad/.python/matrix.py", line 91, in __setitem__
    raise TypeError, "Incorrect assignment of %s" % type(value)
TypeError: Incorrect assignment of <type 'str'>
>>>

"""

HTH,

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

Gold's Law:
	If the shoe fits, it's ugly.



From pydan@danshafer.com  Thu Jul 11 07:38:22 2002
From: pydan@danshafer.com (Dan Shafer)
Date: Wed, 10 Jul 2002 23:38:22 -0700
Subject: [Tutor] Tk Layout Problem
Message-ID: <5.1.0.14.0.20020710233458.00ac10e0@mail.hurrah.com>

Maybe this isn't the right list to ask this. If not, please direct me 
correctly!

I have written a Python app using PythonCard (a GUI toolkit layered on top 
of wxPython) that has a pretty simple UI. You can see what it looks like here:

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

Scroll down just a little from the top and you can see the window.

I cannot for the life of me make this same layout happen in Tk. I'm no Tk 
expert, for sure, but I have read the docs, I have worked through the 
tutorials, I do understand layout managers, and I can get close. But I 
can't get that text field in the right portion of the window to be an 
absolute size and to position itself so it's not anchored to any of the 
sides of the Frame I put it in. It appears to me that both pack and grid 
are designed to fill all available space with components. Not what I'm after.

Any suggestions?

Dan Shafer, Chief Scribe and Tablet Keeper
PythonCard Open Source Project
http://pythoncard.sourceforge.net




From dman@dman.ddts.net  Thu Jul 11 16:34:45 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Thu, 11 Jul 2002 10:34:45 -0500
Subject: [Tutor] Re: Old friend revisited - just for fun!
In-Reply-To: <3D2BC523.10702@shrestha.net.np>
References: <B950A947.93D9%sarmstrong13@mac.com> <001801c2278e$d9b1e970$1615a8c0@mega> <3D2BC523.10702@shrestha.net.np>
Message-ID: <20020711153445.GA17838@dman.ddts.net>

--uAKRQypu60I7Lcqm
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, Jul 10, 2002 at 11:09:51AM +0545, Ashish Shrestha wrote:
| nice, but needed to change a line
|=20
| @line 110:
| for cell in self.neighbors: -> for cell in self.neighbors.keys():

This is not necessary in version 2.2.  In 2.2+, dicts implement the
iterator protocol, and the for loop will try the iterator protocol
first.

-D

--=20
=20
He who belongs to God hears what God says.  The reason you do not hear
is that you do not belong to God.
        John 8:47
=20
http://dman.ddts.net/~dman/


--uAKRQypu60I7Lcqm
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0tpZUACgkQO8l8XBKTpRTJkwCeMwIzdzH/ovEVwt5YGaFrPBfh
j20AoKFM1lbDe58TVWhEPsODPTJpMLo3
=vBBK
-----END PGP SIGNATURE-----

--uAKRQypu60I7Lcqm--



From dman@dman.ddts.net  Thu Jul 11 16:43:00 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Thu, 11 Jul 2002 10:43:00 -0500
Subject: [Tutor] Re: more problems, my final questions
In-Reply-To: <3D2C6EA3.28D00128@ccvcorp.com>
References: <20020710163930.0CB346DA84@www.fastmail.fm> <3D2C6EA3.28D00128@ccvcorp.com>
Message-ID: <20020711154300.GB17838@dman.ddts.net>

--DBIVS5p969aUjpLe
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, Jul 10, 2002 at 10:28:03AM -0700, Jeff Shannon wrote:
| Kyle Babich wrote:
|=20
| > Anyway, I came up with a work around where I write sleeptime to a
| > temporary file and extract it later.

That is unnecessary.  I recommend reading some documents or tutorials
on structured programming.  (sorry, I don't have any URLs handy)  The
specific areas to study are how local variables are handled, and how
argument passing is done.

[...]
| > Why can't I do that?
|=20
| When you read something from a file, you get a string object.  Strings do=
n't
| allow arithmetic -- you need to convert the string into an integer first.

Actually, a string can be multiplied by an integer.  It is convenient
when you want the same string to be repeated multiple times since you
don't need to go through a loop to do it.

>>> print '-'*60
------------------------------------------------------------
>>>

Since python is strongly typed, the result of the '*' operator depends
on what type of objects you are multiplying.  When a string is
multiplied by an integer, it repeats itself.  The same thing is true
for a list or a tuple.  It is not automagically converted to an
integer, ignoring all errors, and then multiplied as an integer.
Another example of the polymorphism that strong typing provides is
list (or string or tuple) addition :
    >>> print [1] + [2]
    [1, 2]
    >>>
with lists (as with strings and tuples), the '+' operator means to
concatenate the two sequences.

HTH,
-D

--=20
=20
A perverse man stirs up dissension,
and a gossip separates close friends.
        Proverbs 16:28
=20
http://dman.ddts.net/~dman/


--DBIVS5p969aUjpLe
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0tp4MACgkQO8l8XBKTpRTnyQCeOyEWbqg7Ar5CBFNVEsFYQMvm
jGQAn3Oy7cyo96uRGxkVd9rpqRMsE10W
=Y0na
-----END PGP SIGNATURE-----

--DBIVS5p969aUjpLe--



From dman@dman.ddts.net  Thu Jul 11 16:55:35 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Thu, 11 Jul 2002 10:55:35 -0500
Subject: [Tutor] Re: python from shell
In-Reply-To: <2959.1026297309@www23.gmx.net>
References: <20020709163848.GB17757@dman.ddts.net> <2959.1026297309@www23.gmx.net>
Message-ID: <20020711155535.GC17838@dman.ddts.net>

--7gGkHNMELEOhSGF6
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, Jul 10, 2002 at 12:35:09PM +0200, lumbricus@gmx.net wrote:
| > On Tue, Jul 09, 2002 at 09:18:25AM -0500, SA wrote:
|=20
| [ snip ]
|=20
| > Here's the difference :
| >=20
| > /usr/bin/env is a program that searches the $PATH to find the program
| > given as it's first argument.  Then it exec's it on the input
| > (script).
| >=20
| > Using /usr/bin/env means that your script will automagically run on
| > any person's system *IFF* the 'python' found first in the $PATH is the
| > one you wanted to use.  It also means (due to limitations in
|                                                 ^^^^^^^^^^^
| what do you mean?

See below.

| > linux/bash)
|   ^^^^^^^^^^
| now which one?

I don't remember which.

| > that you can't pass any arguments to python itself (such
| > as -u or -OO).
|=20
| From 'man env' on OSF1
| (no matter which shell ;-)

Ok, same here.

=2E..
| It works for me.

$ cat env.py
#!/usr/bin/env python -OO

print "Starting"
if __debug__ :   # remember, this is false when optimization is turned on
    print "running with __debug__"
print "That's all folks."


$ ./env.py
/usr/bin/env: python -OO: No such file or directory

$

Oh, I just expected it to not pass the -OO argument.

| > Using the full path to the interpreter ensures that you'll be using
| > the python you want to use.
|=20
| _Iff_ it is there. On my system for example python is in
| /usr/local/bin. So your scripts won't run

True.  At least you won't send me a bug report saying "your script has
invalid syntax" when the real problem is you ran it with the wrong
interpreter :-).

| > For example, on a debian woody system, /usr/bin/python is a symlink to
| > /usr/bin/python2.1, and it is also possible for the user to have
| > /usr/bin/python2.2 as well.  On a RH 7.x system, 'python' (is it in
| > /usr/bin ?) is version 1.5 wherease 'python2' is version
| > 2.<something>.  Using the env trick will yield different results on
| > different systems, and using the full path isn't compatible with all
| > systems.
|=20
| ACK
| =20
| > Pay your money and take your choice :-) (as one of my profs likes to sa=
y)
|=20
| But env(1) has the advantage that it sets the environment as the
| command (python) needs it - PYTHONPATH, PYTHONHOME or the like.

It will set the environment only if it inherited the right environment
from the parent process.  Otherwise (eg when run from apache as a CGI
script) it won't.  Thus this argument doesn't have any real meaning.

| > I choose to use the absolute path and explicitly specify the version I
| > want.  Then again, I also use debian and for debian-packaged programs
| > that is also the Policy.
|=20
| But this fails, if the specified version isn't there.=20

True.

| I'd prefer env(1).

That would still fail on your system, because I would end up writing
    #!/usr/bin/env python2.2
or
    #!/usr/bin/env python2.1
so that I could control which version I ran, but your RH (or whatever)
system might only have 'python' or 'python2'; and your 'python' or
'python2' might not be the right version for my script.  (eg if your
python2 is version 2.1 but I used 2.2 features)

I prefer standardization :-).  If everyone named their python in the
same way ...

(FYI that's part of what I like about debian -- they develop a Policy
for things like this to allow the most flexibility for the end user
while eliminating variations like path-to-python that prevent people
from writing portable scripts)

-D

--=20
=20
One OS to rule them all, one OS to find them,
One OS to bring them all and in the darkness bind them,
In the Land of Redmond, where the Shadows lie.
=20
http://dman.ddts.net/~dman/


--7gGkHNMELEOhSGF6
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0tqncACgkQO8l8XBKTpRT9iACeMGoc7+rTErtzvrO7ox1ZExDy
pX0An2KgGEuxUbck/WUgAyUZjOOWebFR
=ZLI9
-----END PGP SIGNATURE-----

--7gGkHNMELEOhSGF6--



From dman@dman.ddts.net  Thu Jul 11 17:01:00 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Thu, 11 Jul 2002 11:01:00 -0500
Subject: [Tutor] Re: import pwd?
In-Reply-To: <000501c22857$506a3a40$9c21840a@tmbrau00>
References: <000501c22857$506a3a40$9c21840a@tmbrau00>
Message-ID: <20020711160100.GD17838@dman.ddts.net>

--bjuZg6miEcdLYP6q
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, Jul 10, 2002 at 05:18:18PM -0400, Timothy M. Brauch wrote:
| I have a problem.  The program runs on a windows computer and generates a
| log of anyone who logins.  I have a script that uses getpass, specificall=
y,
| getpass.getuser().  However, since I (re)installed Python 2.2 and VPython=
, I
| receive the following error:
|=20
| Traceback (most recent call last):
|   File "<pyshell#1>", line 1, in ?
|     import logger
|   File "c:\python22\programs\logger.pyw", line 35, in ?
|     user =3D getpass.getuser()
|   File "C:\PYTHON22\lib\getpass.py", line 101, in getuser
|     import pwd
| ImportError: No module named pwd
|=20
| So, where is pwd?

in POSIX ...

Microsoft operating systems originally didn't have the concept of
"multi-user".  Thus there was no 'pwd' module and no passwords.  More
recent incarnations have a semblance of multi-user, but are still
almost wholly incompatible with POSIX systems.

$ python2.2
>>> import pwd
>>> pwd.__file__
'/usr/lib/python2.2/lib-dynload/pwd.so'
>>>

You don't have 'pwd.so' on windows, and it wouldn't do you any good if
I sent it to you.

-D

PS. Ironically enough, POSIX stands for
    *Portable* Operating System Interface

--=20
=20
All a man's ways seem innocent to him,
but motives are weighed by the Lord.
        Proverbs 16:2
=20
http://dman.ddts.net/~dman/


--bjuZg6miEcdLYP6q
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0tq7wACgkQO8l8XBKTpRSoTgCeMKI+brTQGbs2KqsgQTTxBpHn
66gAoKbE9kCNj1QPTNJgQNreTH2/c2R3
=iSA2
-----END PGP SIGNATURE-----

--bjuZg6miEcdLYP6q--



From dman@dman.ddts.net  Thu Jul 11 17:37:06 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Thu, 11 Jul 2002 11:37:06 -0500
Subject: [Tutor] Re: Re: small program in Python and in C++
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C707@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C707@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020711163706.GE17838@dman.ddts.net>

--KuLpqunXa7jZSBt+
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, Jul 04, 2002 at 06:06:21PM +0100, alan.gauld@bt.com wrote:
| > | That's a recipe for disaster! If you write more than a few=20
| > | hundered lines of code finding your definitions will be murder.=20
| >=20
| > A function that large (usually) needs to be refactored anyways.
|=20
| Not so. If a function consists of say 50-60 lines of executable=20
| code then most industrial C++ code will typically contain at least=20
| as many lines of comment as there are code so you'll have 120 lines of=20
| text to wade thru'

I thought only ASM needed a line of comment per line of code ;-).
Whatever happened to self-documenting code?

| In the real world many functions contain 200 plus lines of=20
| executable code(*) which means maybe 400-500 lines of text.

I'm glad I'm not in the "real world" ;-).

| (*)If you have an object with over 100 attributes to serialize
| (not an unusual occurence in real world scenarios!) refactoring=20
| the function isn't really practical or sensible.

Yeah, I can see 100 lines of
    stream << this->foo
but that is pretty easy to jump over (eg the paragraph motions in
vim), and won't have lots of locals anyways.  I think that each
attribute should have its own self-contained serialization function,
which could be in the attribute's class itself or in a separate
FooSerilizerFormat1 class/function.

| > With a good editor (eg vim, where your hands stay on the keyboard)
| > it is quite trivial to search for variable names.  I do it all the
| > time, even though I've mostly been working with python lately.
|=20
| Yes but you have to search for the definition/declaration. You have=20
| to keep stepping past all the usage items to get there! That is=20
| time consuming and error prone. Jumping to the top of the function=20
| is a single keystroke!

Which keystroke, btw?  It would be helpful if I knew it.  I know how
to use ctags, but that's quite a few keystrokes (depending on function
names and polymorphic ussage), and I know how to jump over paragraphs
(of which a function can contain several).

| > I find it confusing, actually, to see a whole mess of types/names at
| > the top of a function when I have no idea what each one really means
| > yet. =20
|=20
| Well written variable declarations should all be commented! :-)

It shouldn't need a comment, except in the *few* (right? ;-))
not-so-obvious cases :-).

| > Limiting the scope of a variable limits the length of time=20
| > for which you must remember what it means.
|=20
| Only if reading the code sequentially, if you are jumping in=20
| at random - as is usually the case for maintenance programmers=20
| - the position of declaration is usually not an issue until=20
| they come to change it!!

THat makes sense.

| > Of course, if you are writing a 3-5 line function (or so, something
| > short) it is clearer to put the declarations at the top so they don't
| > clutter the flow of the rest of the logic.
|=20
| Hmm, not sure I follow the logic there. I'd have said declaring=20
| variables in a short function was less important since you can=20
| see whats happening whichever way you do it...

You can reduce the number of lines of text by declaring it inline with
the initialization (if the init occurs in the middle of the function
somewhere).  That style would look much like python, just with an
extra word (the type name) at the left of the line.

| > Oh, also I think it is good to initialize the variable immediately.
|=20
| I agree there.
|=20
| > Initializing it to a senseless value like NULL isn't really helpful,
|=20
| Not true. Many a NULL has caused a crash when an unitinialised=20
| variable would have kept running - with completely wrong results.=20
| A crash in those circumstances is a good thing! And NULLS help=20
| achieve it!

While I agree here, what if you got a 'NameError' exception instead of
'AttributeError: None object has no member foo' _or_ if the operation
you performed was perfectly valid with None/NULL but that was not the
value the variable should have had.

| > function, whereas if you declare the variable later you can construct
| > it properly then. =20
|=20
| OTOH If you want to use variable declared further down a function near=20
| the top you have to go hunt for the declaration and cut n paste it=20
| back up to where you need it. If its declared at the top its always=20
| available.

True, but if the variable couldn't be properly initialized before that
point, then there was no way you could overlook that and simply use
the variable before it was ready (ie while it was still NULL or
something).

| > This is also even more significant in C++ than in
| > Java or Python when working with classes.  Either you'll end up
| > wasting some resources by first constructing a default instance of the
| > class, and then later constructing the one you wanted and copying it
|=20
| I see the point of wasted resource but not sure how Java/Python=20
| helps here. If you initialize the variable to a dummy object you=20
| waste resource and in all 3 languages that resource stays wasted=20
| till you get rid of it.

Here's an example :

// C++
class Foo
{
    Foo( ... ) ;                // default ctor
    Foo( const Foo& other ) ;   // copy ctor

    // member attributes requiring a significant amount of memory
}

void func()
{
    Foo local_foo ;

    // some time later
    local_foo =3D Foo( <values> ) ;
}


Note that when you declared local_foo, it allocated memory on the
stack, and implicitly called the default constructor.  The ctor would
go through each attribute and initialize it, which requires memory
copies at the least and maybe some computations.  However, that is
just a "dummy" value until you get to the point in the function where
you really initialize it.  There you create a new instance on the
stack, set it's values, and then copy all that data into the original.
The result is creating 2 instances when you only needed one, and
performing all the memory copies 3 times.

One way to avoid it is to use a pointer, and then allocate the object
using 'new' when you need it.  Then you must remember to 'delete' it
afterwards.  Also, supposedly, the heap is slower than the stack.

The other way to avoid it is to not declare the local until the "some
time later" point, and just initialize it once.


Python and Java don't have this tradeoff to choose from because they
allocate all objects on the heap (thus "pointers" are transparent
rather than explicit) _and_ they automatically delete all objects when
they are done, in a similar manner as stack variables in C/C++.

(I also like python's ability to get rid of a local ('del') after
you're done with it.  It helps prevent you from erroneously re-using
the old data later on -- which I've done before!)

| > It probably depends on whether the "regular" C++'ers started with C or
| > not.
|=20
| Nope, It probably depends more on how many months or years they've=20
| spent debugging other peoples code :-)
|
| > C required all locals to be declared at the start of a block.  I think
| > that's due to the early implementations, but I'm just hypothesizing
| > here.
|=20
| Its good software engineering practice as taught at the time=20
| - Pascal for example requires variables to be declared in a=20
| var section of the code, as does ADA and Modula (and even COBOL!)
|
| > Java has the same rules as C++, and all the code I've written and read
| > seems to follow the "don't declare it until you actually need it"
| > style.
|=20
| Yes, and maintenance programmers the world over are learning=20
| to hate it! Our Java style guides at work have recently been=20
| ammended to insist that all variables be declared at the top=20
| of scope - previously it was just a recommendation...)

:-).  That is probably true (all 3 points).  I can see how a
maintenance programmer would get quite a bit of experience and develop
strong opinions as to the best style.

| > Of course, much of this is just a matter of style with little
| > technical merit either way, so do as you please :-).
|=20
| If it hits the time to fix faults its more than just style.
| When an operational fault has to be fixed in lkess than 4 hours=20
| say, you really don't have time to cast about looking for variables.
| It becomes a matter of real bottom line accounting.

Surely if you can actually and accurately quantize the effect, then
you can make a better argument than aesthetics.  Otherwise, aesthetics
end up being the best quantization ... at least for the original
coder.  And then you want to have a consistent style that all
coders and maintainers will use so that at least they agree on those
quantizations.


Alan,

I understand your points, but they truly are hard to quantize.
Quantization is needed so that we can (objectively) compare the
benefits of each method and choose the best one.  Since quantization
isn't a viable option, experience is the next best decider.  I don't
really have enough experience yet to say whether your points are valid
enough to change all existing code.  However, I will keep your points
in mind when I get to the point where I am performing serious
maintenance on some project.

My comments here aren't intended as arguments, just clarification of
what I had said before and of the "other" perspective.  (and some of
it is meant to be a bit humorous)

-D

--=20
=20
[Perl] combines all the worst aspects of C and Lisp: a billion different
    sublanguages in one monolithic executable.
It combines the power of C with the readability of PostScript.
        -- Jamie Zawinski
=20
http://dman.ddts.net/~dman/


--KuLpqunXa7jZSBt+
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0ttDIACgkQO8l8XBKTpRR8YgCfUeHth8hy3323wpfIvA5nzTaR
dyoAoKBd4rx/FFTR21Q2xfp4W7BHONP/
=w9sE
-----END PGP SIGNATURE-----

--KuLpqunXa7jZSBt+--



From joel@prettyhipprogramming.com  Thu Jul 11 17:48:53 2002
From: joel@prettyhipprogramming.com (Joel Ricker)
Date: Thu, 11 Jul 2002 12:48:53 -0400
Subject: [Tutor] Looking for peer review
Message-ID: <002101c228fa$d8077e60$e1e03942@joeltklrijxxms>

This is a multi-part message in MIME format.

------=_NextPart_000_001E_01C228D9.50324040
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Below is a program that I've been working on that reports changes in =
ipaddresses.  I work in a retail store and we have two other stores =
about an hour drive away.  Once a week the owner comes down and makes =
backups of our inventory and gives us copies of inventories from the =
other two stores.  The owner decided to set us all up with a broadband =
connection and use PCAnywhere to connect and make changes to the system.

Of course the problem is that the ip addresses of all the connections =
will change at least once a day.  When he complained about having to =
call us for the ip address whenever he wanted to login, I knew Python =
would do the trick :)

The purpose of this program is to check the ip address periodically and =
if it changes, connect to an smtp server and send an e-mail reporting =
the change.  That way, he should always have the current ip address of =
our system.

I'd like for everyone to critique my program and give me any pointers on =
making it better and helping me become a better python programmer.  This =
is my first "real" python program -- something that's not throw away =
code and that will be used by someone else.=20

## ipwatch.py
import socket, getopt, sys, time, smtplib

def usage(evalue):
    ''' Show instructions and pass exit evalue '''
   =20
    print
    print "ipwatch by Joel Ricker (joel@prettyhipprogramming.com)"
    print "Monitors current machines IP address and reports any changes =
by e-mail."
    print   =20
    print "Usage:python ipwatch.py --help | --to <to address> --from =
<from address> "
    print "[--smtp <smtp address>] [--port <port>] [--user <username>] =
[--pass <password>] [--wait <minutes>]"   =20
    print
    print "Options:"
    print "\t--help\tShows this help message."
    print "\t--to\tE-mail address to send reports to."
    print "\t--from\tE-mail address to set as reply to."
    print "\t--smtp\tAddress of smtp server to send mail through."
    print "\t\tDefaults to localhost."
    print "\t--port\tPort address of smtp server. Defaults to 25"
    print "\t--user\tIf smtp server requires authorization, the username =
to login as."
    print "\t--pass\tIf smtp server requires authorization, the password =
to login as."
    print "\t--wait\tTime in minutes to wait between ip address checks."
   =20
    sys.exit(evalue)   =20
   =20

def get_addy():
    try:
        addy =3D socket.gethostbyname(socket.getfqdn())
    except:
        sys.stderr.write("Socket Error: Couldn't aquire address of this =
machine.")
        sys.exit(2)
    else:
        return addy
       =20
def main():     =20

    # Load the file that holds the current ip address of this machine    =

    try:
        f =3D file("ipwatch.dat", "r")
        addy =3D f.readline()
        f.close()
    except:
        f =3D file("ipwatch.dat", "w")
        addy =3D get_addy()       =20
        f.write(addy)
        f.close()       =20
   =20
    # Load command line options
    try:
        opts, args =3D getopt.getopt(sys.argv[1:], "hs:p:t:f:u:p:w:",
                                     ["help", "smtp=3D", "port=3D", =
"to=3D", "from=3D", "user=3D", "pass=3D", "wait=3D"])
    except getopt.GetoptError:
        # print help information and exit:
        usage(2)       =20
    else:
        if not len(opts):
            usage(2)           =20

    smtpaddy =3D 'localhost'
    port =3D 25
    fromwho =3D None
    towho =3D None
    user =3D None
    password =3D None
    wait =3D None

    print opts
    print args
    # Process options
    for o, a in opts:
       =20
        # Help - prints out the instructions for use
        if o in ("-h", "--help"):
            usage(0)           =20
           =20
        # SMTP - the address of the smtp server to send the e-mail =
through
        if o in ("-s", "--smtp"):
            smtpaddy =3D a

        # Port - port
        if o in ("-p", "--port"):
            port =3D a

        # To - the address to send the e-mail to
        if o in ("-t", "--to"):
            towho =3D a

        # From - the reply address
        if o in ("-f", "--from"):
            fromwho =3D a
           =20
        # Username - the username to login as if required
        if o in ("-u", "--user"):
            user =3D a
           =20
        # Password - the password of the smtp server if required
        if o in ("-p", "--pass"):
            password =3D a

        # Time - amount of time in minutes to wait
        if o in ("-w", "--wait"):           =20
            wait =3D int(a) * 60     =20

    # Check for required and valid command-line options
    if towho is None:
        sys.stderr.write("To address required.")
        usage(2)       =20
    if fromwho is None:
        sys.stderr.write("From address required.")
        usage(2)   =20
    if wait < 300:
        sys.stderr.write("Invalid wait value.")
        usage(2)
       =20
       =20
   =20
    # Now we loop, checking the current address of the machine against =
the address stored
    # in the file.  If we have a new address, we store that address in =
the file and report
    # the new address by e-mail.  We're depending on Window's shutdown =
signal to stop
    # properly
    while (1):
        newaddy =3D get_addy()
        if addy !=3D newaddy:
            print "New addy: ", newaddy
            f =3D open("ipwatch.dat", "w")
            f.write(newaddy)
            f.close()
              =20
            try:
                s =3D smtplib.connect(smtpaddy, port)
                if user is not None:                   =20
                    try:
                        s.login(user, password)
                    except SMTPAuthenticationError:
                        sys.stderr.write("Error logging into SMTP =
server.  Check username and password and re-attempt")
                s.sendmail(towho, fromwho, newaddy)
                s.quit()
               =20

            except SMTPException, reason:
                sys.stderr.write("SMTP Error: %s", (reason))
            addy =3D newaddy
        print "The current address is", addy
        time.sleep(wait)  =20
       =20
   =20

if __name__ =3D=3D "__main__":
    main()
   =20
Thanks
Joel

------=_NextPart_000_001E_01C228D9.50324040
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2479.6" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Below is a program that I've been =
working on that=20
reports changes in ipaddresses.&nbsp; I work in a retail store and we =
have two=20
other stores about an hour drive away.&nbsp; Once a week the owner comes =
down=20
and makes backups of our inventory and gives us copies of inventories =
from the=20
other two stores.&nbsp; The owner decided to set us all up with a =
broadband=20
connection and use PCAnywhere to connect and make changes to the=20
system.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Of course the problem is that the ip =
addresses of=20
all the connections will change at least once a day.&nbsp; When he =
complained=20
about having to call us for the ip address whenever he wanted to login, =
I knew=20
Python would do the trick :)</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>The purpose of this program is to check =
the ip=20
address periodically and if it changes, connect to an smtp server and =
send an=20
e-mail reporting the change.&nbsp; That way, he should always have the =
current=20
ip address of our system.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I'd like for everyone to critique my =
program and=20
give me any pointers on making it better and helping me become a better =
python=20
programmer.&nbsp; This is my first "real" python program -- something =
that's not=20
throw away code and that will be used by someone =
else.&nbsp;</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>## ipwatch.py</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>import socket, getopt, sys, time,=20
smtplib</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>def =
usage(evalue):<BR>&nbsp;&nbsp;&nbsp; ''' Show=20
instructions and pass exit evalue '''<BR>&nbsp;&nbsp;&nbsp;=20
<BR>&nbsp;&nbsp;&nbsp; print<BR>&nbsp;&nbsp;&nbsp; print "ipwatch by =
Joel Ricker=20
(<A=20
href=3D"mailto:joel@prettyhipprogramming.com">joel@prettyhipprogramming.c=
om</A>)"<BR>&nbsp;&nbsp;&nbsp;=20
print "Monitors current machines IP address and reports any changes by=20
e-mail."<BR>&nbsp;&nbsp;&nbsp; print&nbsp;&nbsp;&nbsp; =
<BR>&nbsp;&nbsp;&nbsp;=20
print "Usage:python ipwatch.py --help | --to &lt;to address&gt; --from =
&lt;from=20
address&gt; "<BR>&nbsp;&nbsp;&nbsp; print "[--smtp &lt;smtp address&gt;] =
[--port=20
&lt;port&gt;] [--user &lt;username&gt;] [--pass &lt;password&gt;] =
[--wait=20
&lt;minutes&gt;]"&nbsp;&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp;=20
print<BR>&nbsp;&nbsp;&nbsp; print "Options:"<BR>&nbsp;&nbsp;&nbsp; print =

"\t--help\tShows this help message."<BR>&nbsp;&nbsp;&nbsp; print =
"\t--to\tE-mail=20
address to send reports to."<BR>&nbsp;&nbsp;&nbsp; print =
"\t--from\tE-mail=20
address to set as reply to."<BR>&nbsp;&nbsp;&nbsp; print =
"\t--smtp\tAddress of=20
smtp server to send mail through."<BR>&nbsp;&nbsp;&nbsp; print =
"\t\tDefaults to=20
localhost."<BR>&nbsp;&nbsp;&nbsp; print "\t--port\tPort address of smtp =
server.=20
Defaults to 25"<BR>&nbsp;&nbsp;&nbsp; print "\t--user\tIf smtp server =
requires=20
authorization, the username to login as."<BR>&nbsp;&nbsp;&nbsp; print=20
"\t--pass\tIf smtp server requires authorization, the password to login=20
as."<BR>&nbsp;&nbsp;&nbsp; print "\t--wait\tTime in minutes to wait =
between ip=20
address checks."<BR>&nbsp;&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp;=20
sys.exit(evalue)&nbsp;&nbsp;&nbsp;&nbsp;<BR>&nbsp;&nbsp;&nbsp; =
</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>def get_addy():<BR>&nbsp;&nbsp;&nbsp;=20
try:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; addy =3D=20
socket.gethostbyname(socket.getfqdn())<BR>&nbsp;&nbsp;&nbsp;=20
except:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
sys.stderr.write("Socket=20
Error: Couldn't aquire address of this=20
machine.")<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
sys.exit(2)<BR>&nbsp;&nbsp;&nbsp;=20
else:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return=20
addy<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <BR>def=20
main():&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; # Load the file that =
holds the=20
current ip address of this machine&nbsp;&nbsp;&nbsp; =
<BR>&nbsp;&nbsp;&nbsp;=20
try:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; f =3D =
file("ipwatch.dat",=20
"r")<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; addy =3D=20
f.readline()<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
f.close()<BR>&nbsp;&nbsp;&nbsp;=20
except:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; f =3D =
file("ipwatch.dat",=20
"w")<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; addy =3D=20
get_addy()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
f.write(addy)<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
f.close()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
<BR>&nbsp;&nbsp;&nbsp;=20
<BR>&nbsp;&nbsp;&nbsp; # Load command line options<BR>&nbsp;&nbsp;&nbsp; =

try:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; opts, args =3D=20
getopt.getopt(sys.argv[1:],=20
"hs:p:t:f:u:p:w:",<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb=
sp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;&nbsp;&nbsp;=20
["help", "smtp=3D", "port=3D", "to=3D", "from=3D", "user=3D", "pass=3D", =

"wait=3D"])<BR>&nbsp;&nbsp;&nbsp; except=20
getopt.GetoptError:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # =
print help=20
information and exit:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
usage(2)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
<BR>&nbsp;&nbsp;&nbsp;=20
else:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if not=20
len(opts):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;=20
usage(2)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;=20
</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; smtpaddy =3D=20
'localhost'<BR>&nbsp;&nbsp;&nbsp; port =3D 25<BR>&nbsp;&nbsp;&nbsp; =
fromwho =3D=20
None<BR>&nbsp;&nbsp;&nbsp; towho =3D None<BR>&nbsp;&nbsp;&nbsp; user =3D =

None<BR>&nbsp;&nbsp;&nbsp; password =3D None<BR>&nbsp;&nbsp;&nbsp; wait =
=3D=20
None</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; print =
opts<BR>&nbsp;&nbsp;&nbsp;=20
print args<BR>&nbsp;&nbsp;&nbsp; # Process options<BR>&nbsp;&nbsp;&nbsp; =
for o,=20
a in opts:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # Help - prints out the=20
instructions for use<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if o =
in=20
("-h",=20
"--help"):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;=20
usage(0)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;=20
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # SMTP - the address of =
the smtp=20
server to send the e-mail =
through<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
if o in ("-s",=20
"--smtp"):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;=20
smtpaddy =3D a</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial =
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # Port -=20
port<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if o in ("-p",=20
"--port"):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;=20
port =3D a</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial =
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # To -=20
the address to send the e-mail =
to<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
if o in ("-t",=20
"--to"):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;=20
towho =3D a</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial =
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # From -=20
the reply address<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if o in =
("-f",=20
"--from"):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;=20
fromwho =3D=20
a<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # Username - the username =
to=20
login as if required<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if o =
in=20
("-u",=20
"--user"):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;=20
user =3D =
a<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # Password - the password =
of the=20
smtp server if required<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if =
o in=20
("-p",=20
"--pass"):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;=20
password =3D a</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial =
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # Time -=20
amount of time in minutes to =
wait<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
if o in ("-w",=20
"--wait"):&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb=
sp;=20
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
wait =3D=20
int(a) * 60&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; # Check for required =
and valid=20
command-line options<BR>&nbsp;&nbsp;&nbsp; if towho is=20
None:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sys.stderr.write("To =
address=20
required.")<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
usage(2)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
<BR>&nbsp;&nbsp;&nbsp; if=20
fromwho is None:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
sys.stderr.write("From address=20
required.")<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
usage(2)&nbsp;&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp; if wait &lt;=20
300:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
sys.stderr.write("Invalid=20
wait value.")<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
usage(2)<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp;=20
<BR>&nbsp;&nbsp;&nbsp; # Now we loop, checking the current address of =
the=20
machine against the address stored<BR>&nbsp;&nbsp;&nbsp; # in the =
file.&nbsp; If=20
we have a new address, we store that address in the file and=20
report<BR>&nbsp;&nbsp;&nbsp; # the new address by e-mail.&nbsp; We're =
depending=20
on Window's shutdown signal to stop<BR>&nbsp;&nbsp;&nbsp; #=20
properly<BR>&nbsp;&nbsp;&nbsp; while=20
(1):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; newaddy =3D=20
get_addy()<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if addy !=3D=20
newaddy:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;=20
print "New addy: ",=20
newaddy<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n=
bsp; f=20
=3D open("ipwatch.dat",=20
"w")<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;=20
f.write(newaddy)<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;&nbsp;=20
f.close()<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp;&nbsp;&nbsp;=20
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
try:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;&nbsp;&nbsp;&nbsp;=20
s =3D smtplib.connect(smtpaddy,=20
port)<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;=20
if user is not=20
None:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n=
bsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb=
sp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
try:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
=20
s.login(user,=20
password)<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
except=20
SMTPAuthenticationError:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb=
sp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;=20
sys.stderr.write("Error logging into SMTP server.&nbsp; Check username =
and=20
password and=20
re-attempt")<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb=
sp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
s.sendmail(towho, fromwho,=20
newaddy)<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
s.quit()<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial=20
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p; except=20
SMTPException,=20
reason:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n=
bsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
sys.stderr.write("SMTP Error: %s",=20
(reason))<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;=20
addy =3D newaddy<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print =
"The current=20
address is", addy<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
time.sleep(wait)&nbsp;&nbsp;&nbsp;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;&nbsp;<BR>&nbsp;&nbsp;&nbsp;=20
</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>if __name__ =3D=3D =
"__main__":<BR>&nbsp;&nbsp;&nbsp;=20
main()<BR>&nbsp;&nbsp;&nbsp; </FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Thanks</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Joel</FONT></DIV></BODY></HTML>

------=_NextPart_000_001E_01C228D9.50324040--




From ak@silmarill.org  Thu Jul 11 18:03:03 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Thu, 11 Jul 2002 13:03:03 -0400
Subject: [Tutor] Looking for peer review
In-Reply-To: <002101c228fa$d8077e60$e1e03942@joeltklrijxxms>
References: <002101c228fa$d8077e60$e1e03942@joeltklrijxxms>
Message-ID: <20020711170303.GA10735@ak.silmarill.org>

I think this would be much better done with dyndns type of service.
dyndns.org.

On Thu, Jul 11, 2002 at 12:48:53PM -0400, Joel Ricker wrote:
> Below is a program that I've been working on that reports changes in ipaddresses.  I work in a retail store and we have two other stores about an hour drive away.  Once a week the owner comes down and makes backups of our inventory and gives us copies of inventories from the other two stores.  The owner decided to set us all up with a broadband connection and use PCAnywhere to connect and make changes to the system.
> 
> Of course the problem is that the ip addresses of all the connections will change at least once a day.  When he complained about having to call us for the ip address whenever he wanted to login, I knew Python would do the trick :)
> 
> The purpose of this program is to check the ip address periodically and if it changes, connect to an smtp server and send an e-mail reporting the change.  That way, he should always have the current ip address of our system.
> 
> I'd like for everyone to critique my program and give me any pointers on making it better and helping me become a better python programmer.  This is my first "real" python program -- something that's not throw away code and that will be used by someone else. 
> 
> ## ipwatch.py
> import socket, getopt, sys, time, smtplib
> 
> def usage(evalue):
>     ''' Show instructions and pass exit evalue '''
>     
>     print
>     print "ipwatch by Joel Ricker (joel@prettyhipprogramming.com)"
>     print "Monitors current machines IP address and reports any changes by e-mail."
>     print    
>     print "Usage:python ipwatch.py --help | --to <to address> --from <from address> "
>     print "[--smtp <smtp address>] [--port <port>] [--user <username>] [--pass <password>] [--wait <minutes>]"    
>     print
>     print "Options:"
>     print "\t--help\tShows this help message."
>     print "\t--to\tE-mail address to send reports to."
>     print "\t--from\tE-mail address to set as reply to."
>     print "\t--smtp\tAddress of smtp server to send mail through."
>     print "\t\tDefaults to localhost."
>     print "\t--port\tPort address of smtp server. Defaults to 25"
>     print "\t--user\tIf smtp server requires authorization, the username to login as."
>     print "\t--pass\tIf smtp server requires authorization, the password to login as."
>     print "\t--wait\tTime in minutes to wait between ip address checks."
>     
>     sys.exit(evalue)    
>     
> 
> def get_addy():
>     try:
>         addy = socket.gethostbyname(socket.getfqdn())
>     except:
>         sys.stderr.write("Socket Error: Couldn't aquire address of this machine.")
>         sys.exit(2)
>     else:
>         return addy
>         
> def main():      
> 
>     # Load the file that holds the current ip address of this machine    
>     try:
>         f = file("ipwatch.dat", "r")
>         addy = f.readline()
>         f.close()
>     except:
>         f = file("ipwatch.dat", "w")
>         addy = get_addy()        
>         f.write(addy)
>         f.close()        
>     
>     # Load command line options
>     try:
>         opts, args = getopt.getopt(sys.argv[1:], "hs:p:t:f:u:p:w:",
>                                      ["help", "smtp=", "port=", "to=", "from=", "user=", "pass=", "wait="])
>     except getopt.GetoptError:
>         # print help information and exit:
>         usage(2)        
>     else:
>         if not len(opts):
>             usage(2)            
> 
>     smtpaddy = 'localhost'
>     port = 25
>     fromwho = None
>     towho = None
>     user = None
>     password = None
>     wait = None
> 
>     print opts
>     print args
>     # Process options
>     for o, a in opts:
>         
>         # Help - prints out the instructions for use
>         if o in ("-h", "--help"):
>             usage(0)            
>             
>         # SMTP - the address of the smtp server to send the e-mail through
>         if o in ("-s", "--smtp"):
>             smtpaddy = a
> 
>         # Port - port
>         if o in ("-p", "--port"):
>             port = a
> 
>         # To - the address to send the e-mail to
>         if o in ("-t", "--to"):
>             towho = a
> 
>         # From - the reply address
>         if o in ("-f", "--from"):
>             fromwho = a
>             
>         # Username - the username to login as if required
>         if o in ("-u", "--user"):
>             user = a
>             
>         # Password - the password of the smtp server if required
>         if o in ("-p", "--pass"):
>             password = a
> 
>         # Time - amount of time in minutes to wait
>         if o in ("-w", "--wait"):            
>             wait = int(a) * 60      
> 
>     # Check for required and valid command-line options
>     if towho is None:
>         sys.stderr.write("To address required.")
>         usage(2)        
>     if fromwho is None:
>         sys.stderr.write("From address required.")
>         usage(2)    
>     if wait < 300:
>         sys.stderr.write("Invalid wait value.")
>         usage(2)
>         
>         
>     
>     # Now we loop, checking the current address of the machine against the address stored
>     # in the file.  If we have a new address, we store that address in the file and report
>     # the new address by e-mail.  We're depending on Window's shutdown signal to stop
>     # properly
>     while (1):
>         newaddy = get_addy()
>         if addy != newaddy:
>             print "New addy: ", newaddy
>             f = open("ipwatch.dat", "w")
>             f.write(newaddy)
>             f.close()
>                
>             try:
>                 s = smtplib.connect(smtpaddy, port)
>                 if user is not None:                    
>                     try:
>                         s.login(user, password)
>                     except SMTPAuthenticationError:
>                         sys.stderr.write("Error logging into SMTP server.  Check username and password and re-attempt")
>                 s.sendmail(towho, fromwho, newaddy)
>                 s.quit()
>                 
> 
>             except SMTPException, reason:
>                 sys.stderr.write("SMTP Error: %s", (reason))
>             addy = newaddy
>         print "The current address is", addy
>         time.sleep(wait)   
>         
>     
> 
> if __name__ == "__main__":
>     main()
>     
> Thanks
> Joel

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From tbrauch@mindless.com  Thu Jul 11 18:49:35 2002
From: tbrauch@mindless.com (Timothy M. Brauch)
Date: Thu, 11 Jul 2002 13:49:35 -0400
Subject: [Tutor] Re: import pwd?
References: <000501c22857$506a3a40$9c21840a@tmbrau00> <20020711160100.GD17838@dman.ddts.net>
Message-ID: <003801c22903$52778340$9c21840a@tmbrau00>

>>On Wed, Jul 10, 2002 at 05:18:18PM -0400, Timothy M. Brauch wrote:
>>| I have a problem.  The program runs on a windows computer and generates
a
>>| log of anyone who logins.  I have a script that uses getpass,
specifically,
>>| getpass.getuser().  However, since I (re)installed Python 2.2 and
VPython, I
>>| receive the following error:
>>|
>>| Traceback (most recent call last):
>>|   File "<pyshell#1>", line 1, in ?
>>|     import logger
>>|   File "c:\python22\programs\logger.pyw", line 35, in ?
>>|     user = getpass.getuser()
>>|   File "C:\PYTHON22\lib\getpass.py", line 101, in getuser
>>|     import pwd
>>| ImportError: No module named pwd
>>|
>>| So, where is pwd?
>>
>>in POSIX ...
>>
>>Microsoft operating systems originally didn't have the concept of
>>"multi-user".  Thus there was no 'pwd' module and no passwords.  More
>>recent incarnations have a semblance of multi-user, but are still
>>almost wholly incompatible with POSIX systems.
>>
>>$ python2.2
>>>>> import pwd
>>>>> pwd.__file__
>>'/usr/lib/python2.2/lib-dynload/pwd.so'
>>>>>
>>
>>You don't have 'pwd.so' on windows, and it wouldn't do you any good if
>>I sent it to you.
>>
>>-D

Yeah, I checked the docs and it said pwd was only available in *nix.  But
that just brings up two more questions... Why can I import getpass if it
doesn't work on Windows?  Okay, supposedly getpass.getpass() should work,
and it does, but with warning messages.

And, question 2, I swear I am not making this up or dreaming or anything,
but this program used to work for me, so why did it stop?  It worked when I
wrote it (I think I wrote this one on my windows 'puter, not on one of my
Linux boxes).  Then, I reformatted my 'puter because the Windows bloat was
getting to be too much.  When I installed Python 2.2 (#28, Dec 21 2001,
12:21:22), and VPython, it quit working.  I put the program on a couple
different Win98 and WinME computers and it worked for them.  Unfortunately,
it is summer break and I cannot get to the other computers I installed it
on.

The only thing I can think of is that I had a different version of Python
installed previously (but I am almost positive it was a 2.2 flavor) and
somehow it worked.  I could post the code and the output files, but I don't
think that would really be much help.

It's not all that important.  However, I thought it would have been nice to
keep a log of who was using my windows 'puters.

 - Tim




From Michael.Baker@IGT.com  Thu Jul 11 18:55:18 2002
From: Michael.Baker@IGT.com (Baker.Michael)
Date: Thu, 11 Jul 2002 10:55:18 -0700
Subject: [Tutor] logic testing
Message-ID: <5A021171E87BD411AF7700508B6940D00347C680@anchorgaming.anchorgaming.com>

i'm working with a game engine and would like a way to test "game logic"
with python.  the game engine runs as fast as it can - in the range of 30 -
100 frames per second. how can I make a python program that will run as fast
as it can and still receive keyboard input?

i cannot make loops work because attempts to capture raw_input() stall the
loop.

i have not tried the cmd module - perhaps this will work????

thanks,
michael



From marta_andrea@libero.it  Thu Jul 11 22:22:48 2002
From: marta_andrea@libero.it (Andrea Valle)
Date: Thu, 11 Jul 2002 23:22:48 +0200
Subject: [Tutor] A question on randomness
In-Reply-To: <4.3.2.7.2.20020626114154.00b83100@pop3.norton.antivirus>
Message-ID: <DNEFLBNHCGCPPIGNHGILCEAGCCAA.marta_andrea@libero.it>

Hi list,
It' a couple of year I work with random generators.

- Something like this:
rand_param=whrandom.randint((-(matr_param[param])), matr_param[param])
-

But it seems to me that the code works as it often produces looping patterns
(at least, they seem so to me): if the range is  0, 5, something like
12312354542222 etc.
I know pseudo-random generation is a complex matter. Is there a way to
"improve" it? (I mean, to obtain a "good sequence" like 1432543122140133
etc.)
 best

-a-

Andrea Valle
via Lanzo 108
10073 - Cirie (TO)
ITALIA
011/921 45 84 - 349/55 47 343





From ak@silmarill.org  Thu Jul 11 20:36:06 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Thu, 11 Jul 2002 15:36:06 -0400
Subject: [Tutor] logic testing
In-Reply-To: <5A021171E87BD411AF7700508B6940D00347C680@anchorgaming.anchorgaming.com>
References: <5A021171E87BD411AF7700508B6940D00347C680@anchorgaming.anchorgaming.com>
Message-ID: <20020711193606.GA437@ak.silmarill.org>

On Thu, Jul 11, 2002 at 10:55:18AM -0700, Baker.Michael wrote:
> i'm working with a game engine and would like a way to test "game logic"
> with python.  the game engine runs as fast as it can - in the range of 30 -
> 100 frames per second. how can I make a python program that will run as fast
> as it can and still receive keyboard input?
> 
> i cannot make loops work because attempts to capture raw_input() stall the
> loop.
> 
> i have not tried the cmd module - perhaps this will work????
>
You can use threads - one thread captures user input, the other one
shows stuff; you can also use select module but it's extremely
confusing, to me at least.

> 
> thanks,
> michael
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From paulsid@shaw.ca  Thu Jul 11 21:19:39 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Thu, 11 Jul 2002 14:19:39 -0600
Subject: [Tutor] A question on randomness
References: <DNEFLBNHCGCPPIGNHGILCEAGCCAA.marta_andrea@libero.it>
Message-ID: <3D2DE85B.EC31AE15@shaw.ca>

Andrea Valle wrote:

> But it seems to me that the code works as it often produces looping patterns
> (at least, they seem so to me): if the range is  0, 5, something like
> 12312354542222 etc.
> I know pseudo-random generation is a complex matter. Is there a way to
> "improve" it? (I mean, to obtain a "good sequence" like 1432543122140133
> etc.)

I'm not an expert by any means but I have taken some University-level
statistics, and to be quite honest I can't see any difference in those
two examples.  

>From what I can tell, you appear to be asking for avoiding long runs
(like the 4 twos in a row) and clusters of numbers (like 123123). 
However, there's nothing out of the ordinary about getting repeating
numbers or patterns of numbers.  If anything it probably means the
random number generator is doing its job.  You can't complain if you
know the dice are fair but you don't like the outcome.  :-)

Anything observed over the short term is virtually meaningless in
analysing an RNG.  Proper statistical analysis would require many, many
trials.  I'm pretty sure the Python people did all this stuff when they
first implemented the RNG, and I expect Python's generator is one of the
fairest available in a common language.

Anyhow, here are some totally unscientific tests:

Frequency-wise the RNG looks to be fair.  In a million trials the
distribution came out quite close:

>>> freqdict = {}
>>> for i in range(5):
	freqdict[i] = 0
>>> import random
>>> for i in range(1000000):
	freqdict[random.randrange(5)] += 1	
>>> freqdict
{0: 200112, 1: 200110, 2: 199790, 3: 199432, 4: 200556}

In a small sample there's nothing too out of the ordinary patternwise
that I can see.  There's only one run of 4.  The odds of any run of 4
are only 1 in 125.  Far far far more improbable things happen to all of
us every day and we don't even notice.  :-)

>>> for i in range(100):
	print random.randrange(5),

1 3 4 4 2 3 3 2 2 2 3 4 3 0 2 3 4 2 3 1 1 3 0 0 1 1 4 4 3 3 4 0 4 1 1 1
0 3 0 4 0 1 2 0 3 2 0 0 2 1 4 3 2 4 4 1 1 1 1 2 4 4 1 2 0 4 3 3 0 2 1 3
1 4 0 1 1 4 3 4 2 4 0 1 1 0 2 2 4 3 1 2 2 4 1 3 4 2 4 4

Notice that if I try to "prevent duplicates" by using a longer range, we
still get runs and clusters of numbers:

>>> for i in range(100):
	print random.randrange(1000000) % 5,
	
3 1 4 0 1 0 4 2 2 4 4 4 2 1 4 0 1 1 1 4 4 3 4 3 4 2 3 0 0 0 1 3 3 2 4 0
3 1 4 3 4 0 1 0 2 4 4 3 0 1 2 0 4 1 2 1 1 4 1 3 4 0 0 0 2 2 2 1 3 3 4 1
3 0 3 4 1 1 4 0 3 3 1 0 0 0 1 0 0 4 0 1 0 2 0 3 2 2 4 3

If you truly want to place a limit on a run length, you'll have to
manage it yourself, kind of like this:

_lastnum = -1;
_count = 0;

def myrandom():
    while 1:
        x = random.randrange(5)
        if x != _lastnum:
            _lastnum = x
            _count = 1
            break
        if _count < 2:
            _count += 1
            break

This (if it works; it's untested) will guarantee you won't get the same
number more than twice in a row.  However, I wouldn't be surprised if
this significantly affects the randomness of the generator.

I hope I've understood your problem accurately.  If not, feel free to
ask questions based on my examples.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From dominic.fox" <dominic.fox@ntlworld.com  Thu Jul 11 21:25:36 2002
From: dominic.fox" <dominic.fox@ntlworld.com (dominic.fox)
Date: Thu, 11 Jul 2002 21:25:36 +0100
Subject: [Tutor] Re: Re: small program in Python and in C++
References: <20020711164002.26690.19904.Mailman@mail.python.org>
Message-ID: <002701c22919$1df03d40$d0d5ff3e@tinypc>

Just a couple of comments on variable declarations. I used to hate having to
declare variables in C - I used to hate it enough to use it as a reason not
to learn C (I thought it was a way of artificially making things harder that
should be easier, which is the way my dad still thinks about C in its
entirety). Now when I'm programming in VB, which for my sins is what I do
all day in my day job, I declare everything up-front as a matter of course,
for no other reason than that I like to group together the bits of the code
that say what kinds of data a given method or function is going to be
dealing with. Increasingly, if I find I have a lot of disparate data types
being declared at the start of a function, I start wondering about which of
them could be moved into the header of a separate function.

Quite aside from code maintenance issues, I find it useful to make the kind
of statement about the *design* of a function that up-front variable
declarations makes. It helps me to see when there's something wrong with
that design, for instance when a function is trying to do too many different
kinds of things at once. Spreading declarations through the code mixes up
design and implementation - to me, it feels like putting pre- and
post-condifitions and invariants in the middle of a method would feel to an
Eiffel programmer...

Dominic




From dyoo@hkn.eecs.berkeley.edu  Thu Jul 11 22:19:50 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 11 Jul 2002 14:19:50 -0700 (PDT)
Subject: [Tutor] A question on randomness
In-Reply-To: <DNEFLBNHCGCPPIGNHGILCEAGCCAA.marta_andrea@libero.it>
Message-ID: <Pine.LNX.4.44.0207111320090.14753-100000@hkn.eecs.berkeley.edu>


On Thu, 11 Jul 2002, Andrea Valle wrote:

> It' a couple of year I work with random generators.
>
> - Something like this:
> rand_param=whrandom.randint((-(matr_param[param])), matr_param[param])

Hi Andrea,

(Side note: you should probably use the 'random' module directly if you're
using more recent versions of Python; I think that 'whrandom' was
deprecated a while back in favor of 'random'.)



> But it seems to me that the code works as it often produces looping
> patterns (at least, they seem so to me): if the range is 0, 5, something
> like 12312354542222 etc.

Hmmm... let's try it!

###
>>> [random.randrange(5) for i in range(10)]
[2, 3, 2, 1, 1, 2, 2, 4, 4, 4]
>>> [random.randrange(5) for i in range(10)]
[2, 1, 2, 2, 2, 3, 3, 1, 1, 2]
###

Yes, "streaks" are very possible, but that's because it's very possible to
randomly generate streaks.  Think "Rosencranz and Guildenstern are Dead".


Eliminating streaks actually reduces the randomness of our sequence, since
now we've guaranteed that long streaks can never happen.  Donald Knuth's
"The Art of Computer Programming, Volume 2", has an comprehensive
discussion of random numbers, so you might be interested in it if you want
more information on how random number generators work.




> I know pseudo-random generation is a complex matter. Is there a way to
> "improve" it? (I mean, to obtain a "good sequence" like 1432543122140133
> etc.)

Let's define a "non-streaky" random sequence as one without streaks longer
than length two.  Then we can make a generator of random numbers that just
remembers the last two entries.



Here's one way to do it, using Python 2.2's generators and iterators:

###
from __future__ import generators


def makeNonStreakySequence(seq):
    seq = iter(seq)
    x, y = seq.next(), seq.next()
    while 1:
        z = getNonStreakyValue(seq, x, y)
        yield x
        x, y = y, z


def getNonStreakyValue(seq, x, y):
    while 1:
        z = seq.next()
        if not (x == y == z): break
    return z
###


Once we have something like this, then we can say:

###
>>> def makeRandomNumberGenerator():
...     while 1:
...         yield random.randrange(5)
...
>>> random_numbers = makeRandomNumberGenerator()
>>> [random_numbers.next() for i in range(20)]
[1, 3, 2, 4, 2, 2, 4, 1, 2, 4, 2, 2, 1, 3, 3, 1, 2, 3, 3, 3]
>>> non_streaky = makeNonStreakySequence(random_numbers)
>>> [non_streaky.next() for i in range(100)]
[4, 4, 2, 1, 3, 2, 0, 2, 2, 4, 2, 1, 3, 4, 3, 2, 0, 4, 0, 3, 4, 4, 2, 3,
 3, 1, 1, 0, 3, 4, 3, 3, 4, 2, 3, 3, 0, 1, 1, 0, 1, 4, 4, 1, 2, 3, 4, 0,
 3, 0, 2, 0, 4, 2, 2, 4, 0, 1, 0, 3, 1, 1, 3, 4, 4, 0, 0, 4, 3, 1, 4, 1, 3, 2,
 0, 2, 3, 2, 3, 0, 3, 3, 4, 0, 4, 0, 2, 2, 0, 3, 0, 1, 2, 1, 1, 2, 4, 0,
 2, 3]
>>>
>>>
>>> def makeRandomBinarySequence():
...     while 1:
...         yield random.randrange(2)
...
>>> binary_seq = makeRandomBinarySequence()
>>> [binary_seq.next() for i in range(20)]
[0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0]
>>> nonstreaky_binary_seq = makeNonStreakySequence(binary_seq)
>>> [nonstreaky_binary_seq.next() for i in range(20)]
[0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1]
###


The generators aren't necessary here; we can write this without generators
if you'd like.  I'm just addicted to them because of their novelty...
*grin*

But I hope the idea makes sense: we just keep asking for random numbers,
but we keep track of the last two that the user has seen already, to
prevent streaks from occuring.



Hope this helps!




From tim@zope.com  Thu Jul 11 20:53:42 2002
From: tim@zope.com (Tim Peters)
Date: Thu, 11 Jul 2002 15:53:42 -0400
Subject: [Tutor] A question on randomness
In-Reply-To: <DNEFLBNHCGCPPIGNHGILCEAGCCAA.marta_andrea@libero.it>
Message-ID: <BIEJKCLHCIOIHAGOKOLHEEJLDGAA.tim@zope.com>

[Andrea Valle]
> It' a couple of year I work with random generators.
>
> - Something like this:
> rand_param=whrandom.randint((-(matr_param[param])), matr_param[param])
> -

Note that whrandom is deprecated.  You should import random instead.

> But it seems to me that the code works as it often produces
> looping patterns (at least, they seem so to me): if the range is
> 0, 5, something like 12312354542222 etc.
> I know pseudo-random generation is a complex matter. Is there a way to
> "improve" it? (I mean, to obtain a "good sequence" like 1432543122140133
> etc.)

It's a standard Wichmann-Hill generator, and has passed extensive tests for
statistical randomness over many years.  Note that people are notoriously
bad at judging randomness "by intuition":  if you found a generator you
thought was delivering "more random" results, it's almost certainly the case
that it would fail rigorous tests for randomness due to being *too* evenly
distributed.  Clumps, repetitions, runs, and little loops are certain to
occur in a truly random sequence with specific probabilities, and a rigorous
statistical test measures the frequency of such occurrences seen and their
deviation from what you'd expect in a truly random sequence.  The
Wichmann-Hill generator does fine on most such rigorous tests (although no
inexpensive pseudo-random generator can pass *all* polynomial-time
statistical tests).

If you have an extreme need for true randomness (which is likely not to
"look random" to human eyes!), note that various places on the web will give
you truly random bits; for example

    http://www.fourmilab.ch/hotbits/

delivers bits derived from monitoring radioactive decay in a physical
system.  BTW, it's a fun and possibly challenging project to write a little
Python program to hook up to such a service programatically.




From glingl@aon.at  Thu Jul 11 22:29:35 2002
From: glingl@aon.at (Gregor Lingl)
Date: Thu, 11 Jul 2002 23:29:35 +0200
Subject: [Tutor] A question on randomness
References: <DNEFLBNHCGCPPIGNHGILCEAGCCAA.marta_andrea@libero.it> <3D2DE85B.EC31AE15@shaw.ca>
Message-ID: <001401c22922$0e785830$1615a8c0@mega>

----- Original Message -----
From: "Paul Sidorsky" <paulsid@shaw.ca>
To: "tutor" <tutor@python.org>
Sent: Thursday, July 11, 2002 10:19 PM
Subject: Re: [Tutor] A question on randomness


> Andrea Valle wrote:
>
> > But it seems to me that the code works as it often produces looping
patterns
> > (at least, they seem so to me): if the range is  0, 5, something like
> > 12312354542222 etc.
> > I know pseudo-random generation is a complex matter. Is there a way to
> > "improve" it? (I mean, to obtain a "good sequence" like 1432543122140133
> > etc.)
>
> I'm not an expert by any means but I have taken some University-level
> statistics, and to be quite honest I can't see any difference in those
> two examples.
>
> From what I can tell, you appear to be asking for avoiding long runs
> (like the 4 twos in a row) and clusters of numbers (like 123123).
> However, there's nothing out of the ordinary about getting repeating
> numbers or patterns of numbers.  If anything it probably means the
> random number generator is doing its job.  You can't complain if you
> know the dice are fair but you don't like the outcome.  :-)
> ....
> In a small sample there's nothing too out of the ordinary patternwise
> that I can see.  There's only one run of 4.  The odds of any run of 4
> are only 1 in 125.  Far far far more improbable things happen to all of
> us every day and we don't even notice.  :-)
>

Morover you should notice, that the probability to obtain 444 is ( or
should be) exactly the same as the probability to obtain 041
(for instance), as are the probabilities to obtain 12312354542222 and
14325431221401 respectively, or - if you are generating random sequences
of letters - the probabilities for QLLYX and TOSCA.

Gregor





From shalehperry@attbi.com  Thu Jul 11 23:12:59 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Thu, 11 Jul 2002 15:12:59 -0700 (PDT)
Subject: [Tutor] A question on randomness
In-Reply-To: <BIEJKCLHCIOIHAGOKOLHEEJLDGAA.tim@zope.com>
Message-ID: <XFMail.20020711151259.shalehperry@attbi.com>

> 
> If you have an extreme need for true randomness (which is likely not to
> "look random" to human eyes!), note that various places on the web will give
> you truly random bits; for example
> 
>     http://www.fourmilab.ch/hotbits/
> 
> delivers bits derived from monitoring radioactive decay in a physical
> system.  BTW, it's a fun and possibly challenging project to write a little
> Python program to hook up to such a service programatically.
> 

At the bottom of the page is a link to some Java sources.  This package has
several psuedo random generators as well as a wrapper to retrieve the data via
the network.  Each one is a derived class from a generic parent.  It would be
most fun to reimplement this in Python.



From glingl@aon.at  Thu Jul 11 23:52:59 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 12 Jul 2002 00:52:59 +0200
Subject: [Tutor] A question on randomness
References: <XFMail.20020711151259.shalehperry@attbi.com>
Message-ID: <002a01c2292d$b42a1880$1615a8c0@mega>

----- Original Message -----
From: "Sean 'Shaleh' Perry" <shalehperry@attbi.com>
To: <tutor@python.org>
Sent: Friday, July 12, 2002 12:12 AM
Subject: RE: [Tutor] A question on randomness


> >
> > If you have an extreme need for true randomness (which is likely not to
> > "look random" to human eyes!), note that various places on the web will
give
> > you truly random bits; for example
> >
> >     http://www.fourmilab.ch/hotbits/
> >
> > delivers bits derived from monitoring radioactive decay in a physical
> > system.  BTW, it's a fun and possibly challenging project to write a
little
> > Python program to hook up to such a service programatically.
> >
>
> At the bottom of the page is a link to some Java sources.  This package
has
> several psuedo random generators as well as a wrapper to retrieve the data
via
> the network.  Each one is a derived class from a generic parent.  It would
be
> most fun to reimplement this in Python.
>

Indeed, randomness seems to be hot stuff!
But since this will not happen immediately, in the meantime one may use
this one:

import urllib
def randombytes(n=128):
    urlstr="http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?nbytes="+str(n)
    t = urllib.urlopen(urlstr).read()
    start = t.find('<pre>')+5
    end   = t.find('</pre>')
    hexes = ''.join(t[start:end].split())
    bytes=[]
    for i in range(0,len(hexes),2):
        bytes.append(int(hexes[i:i+2], 16))
    return bytes

Just in case somebody needs very urgently real randombytes. ;-)

Gregor

P.S.: Minor challenge: how does on make random dice out of these bytes?





From glingl@aon.at  Fri Jul 12 00:09:36 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 12 Jul 2002 01:09:36 +0200
Subject: [Tutor] A question on getting binary data from the net
References: <XFMail.20020711151259.shalehperry@attbi.com> <002a01c2292d$b42a1880$1615a8c0@mega>
Message-ID: <003d01c22930$06f34350$1615a8c0@mega>

> 
> import urllib
> def randombytes(n=128):
>     urlstr="http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?nbytes="+str(n)
>     t = urllib.urlopen(urlstr).read()
>     start = t.find('<pre>')+5
>     end   = t.find('</pre>')
>     hexes = ''.join(t[start:end].split())
>     bytes=[]
>     for i in range(0,len(hexes),2):
>         bytes.append(int(hexes[i:i+2], 16))
>     return bytes
> 

I think, of course, this could be done in two or three lines if
one knew how to fetch binary data from the net - using this form
of the url:

http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?nbytes=128&fmt=bin

Can somebody explain how to accomplish this in Python?

Gregor





From glingl@aon.at  Fri Jul 12 01:58:15 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 12 Jul 2002 02:58:15 +0200
Subject: [Tutor] A question on getting binary data from the net
References: <XFMail.20020711151259.shalehperry@attbi.com> <002a01c2292d$b42a1880$1615a8c0@mega> <003d01c22930$06f34350$1615a8c0@mega>
Message-ID: <000701c2293f$34770910$1615a8c0@mega>

> 
> I think, of course, this could be done in two or three lines if
> one knew how to fetch binary data from the net - using this form
> of the url:
> 
> http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?nbytes=128&fmt=bin
> 
> Can somebody explain how to accomplish this in Python?
> 
> Gregor
> 

What about this?

import urllib
def randombytes(n=128):
    if n>2048: print "Maximum of 2048 bytes returned"
    urlstr="http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?"+\
                                      "nbytes=%d&fmt=bin"%n
    return [ord(c) for c in urllib.urlopen(urlstr).read(n)]

Gregor
 
P.S. or should I use urlretrieve instead? But, then, how
do I prevent it from writing to disk?





From sarmstrong13@mac.com  Fri Jul 12 19:16:18 2002
From: sarmstrong13@mac.com (SA)
Date: Fri, 12 Jul 2002 13:16:18 -0500
Subject: [Tutor] I need help slicing.
Message-ID: <B9548722.9852%sarmstrong13@mac.com>

How do you slice a string from rear to front that is variable length?

For example:

I have two strings -
    test.html
    test.txt

I would like to compare each string individually and do a conditional
statement that says how to handle the file. In other words, I would like my
script to individually discern between the .txt file and the .html file and
handle each file differently based upon it's file extension.


Would this be better hadled with re or string slicing?


On another note, say it has a directory in front of the file, I would like
the script to look at the directory name and decide whether it is ok or not
to continue on working on this file.

These questions are both related to cgi security for a cgi script I'm
working on.

Thanks in Advance.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me




From jeff@ccvcorp.com  Fri Jul 12 19:52:54 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri, 12 Jul 2002 11:52:54 -0700
Subject: [Tutor] I need help slicing.
References: <B9548722.9852%sarmstrong13@mac.com>
Message-ID: <3D2F2585.933A19E2@ccvcorp.com>


SA wrote:

> I would like to compare each string individually and do a conditional
> statement that says how to handle the file. In other words, I would like my
> script to individually discern between the .txt file and the .html file and
> handle each file differently based upon it's file extension.
> [...]
> On another note, say it has a directory in front of the file, I would like
> the script to look at the directory name and decide whether it is ok or not
> to continue on working on this file.

If you're manipulating filenames and paths, then you should probably use the
os.path module.

>>> import os
>>> os.path.join('c:\\temp', 'subdir', 'file.txt')
'c:\\temp\\subdir\\file.txt'
>>> fname = 'c:\\temp\\textfile.txt'
>>> os.path.splitext(fname)
('c:\\temp\\textfile', '.txt')
>>> os.path.split(fname)
('c:\\temp', 'textfile.txt')
>>> os.path.dirname(fname)
'c:\\temp'
>>>

This should give you the tools you need to isolate the various parts of the
file/path names that you want to compare.

However, you can also easily do this sort of thing with negative-index string
slicing.

>>> fname
'c:\\temp\\textfile.txt'
>>> fname[-4:]
'.txt'

But, for what you're doing, the os.path functions will be a much more robust
and flexible way of doing things.

Hope this helps...

Jeff Shannon
Technician/Programmer
Credit International





From dyoo@hkn.eecs.berkeley.edu  Fri Jul 12 19:57:34 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 12 Jul 2002 11:57:34 -0700 (PDT)
Subject: [Tutor] I need help slicing.
In-Reply-To: <B9548722.9852%sarmstrong13@mac.com>
Message-ID: <Pine.LNX.4.44.0207121143020.7061-100000@hkn.eecs.berkeley.edu>


On Fri, 12 Jul 2002, SA wrote:

> How do you slice a string from rear to front that is variable length?

Hi SA,


We can slice from the end of a string like this:

###
>>> secret = "Elbereth"
>>> secret[3:]
'ereth'
>>> secret[4:]
'reth'
>>> secret[5:]
'eth'
>>> secret[5:-1]
'et'
###

So if we leave off the right endpoint of the slice, Python assumes we'll
want to include up to the end of the string.  If you want to see a few
more examples of string slicing, try:

http://www.python.org/doc/tut/node5.html#SECTION005120000000000000000

Slicing works pretty similarly between strings and the other sequences in
Python (like lists and tuples), so once we understand string slicing, we
get the others for free.  *grin*



> For example:
>
> I have two strings -
>     test.html
>     test.txt
>
> I would like to compare each string individually and do a conditional
> statement that says how to handle the file. In other words, I would like
> my script to individually discern between the .txt file and the .html
> file and handle each file differently based upon it's file extension.
>
>
> Would this be better hadled with re or string slicing?


To get that file extension, we can look for the last position of the '.'
in the string, and slice from there.  Regular expressions will work, but
this pattern is simple enough that it might just be easier to us a simple
rfind() or rindex() to get the last position of that period.

###
>>> filename = "foobar.xml"
>>> filename.rindex('.')
6
>>> filename[6:]
'.xml'
###


And to make this convenient for ourselves, we can put these pieces
together into a function:

###
>>> def file_extension(filename):
...     dot_index = filename.rindex('.')
...     return filename[dot_index :]
...
>>> file_extension('foobar.html')
'.html'
###



> On another note, say it has a directory in front of the file, I would
> like the script to look at the directory name and decide whether it is
> ok or not to continue on working on this file.

Hmmm... If we're doing a lot of path-related things, we may want to look
at the 'os.path' module, which brings a lot of path-related functions
together:

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


Hey, in fact, 'os.path' has a function called 'splitext()' which splits
the extension right out of a filename, just like the file_extension()
function above!  Very nice.  *grin*

Another advantage of using os.path is that it takes care of some
platform-specific stuff.




Best of wishes to you!




From erikprice@mac.com  Fri Jul 12 03:43:43 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 11 Jul 2002 22:43:43 -0400
Subject: [Tutor] event-based programming
Message-ID: <2E7466AE-9541-11D6-BB80-00039351FE6A@mac.com>

I was wondering if one (or more) of the helpful geniuses on this list 
could help me understand how event-based programming works.  This is 
something that I have seen in a Java program called RoboCode and also in 
JavaScript-enabled web browsers, which trigger event handlers written in 
JavaScript embedded into an HTML documents, and I'm sure that it can be 
done with a language like Python.  But what I don't understand is how 
the program knows to "watch" for the event.

Does the event have to "target" the event handler with a message, or 
does the simple act of an "event" being triggered cause the event 
handler to execute?  In other words, does the event handler watch some 
specific code for an event to happen, or does the event have to be sent 
to the event handler?  And how does one write code that "watches" for 
events in this fashion, regardless of whether it is targetted or not -- 
does that mean that event-based code must be written like a daemon, 
constantly running and waiting for messages?

I'm hoping someone can give me a very high-level, theoretical 
explanation of how this works.


TIA,


Erik




From Malmoo20@aol.com  Fri Jul 12 15:08:13 2002
From: Malmoo20@aol.com (Malmoo20@aol.com)
Date: Fri, 12 Jul 2002 10:08:13 EDT
Subject: [Tutor] Help?
Message-ID: <61.227f99a4.2a603ccd@aol.com>

--part1_61.227f99a4.2a603ccd_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

What are some ways for running a program?
Please email at extxn1@aol.com

--part1_61.227f99a4.2a603ccd_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

<HTML><FONT FACE=arial,helvetica><FONT  SIZE=2 FAMILY="SANSSERIF" FACE="Arial" LANG="0">What are some ways for running a program?<BR>
Please email at extxn1@aol.com</FONT></HTML>

--part1_61.227f99a4.2a603ccd_boundary--



From abli@freemail.hu  Fri Jul 12 20:01:45 2002
From: abli@freemail.hu (Abel Daniel)
Date: Fri, 12 Jul 2002 21:01:45 +0200
Subject: [Tutor] I need help slicing.
In-Reply-To: <B9548722.9852%sarmstrong13@mac.com>
References: <B9548722.9852%sarmstrong13@mac.com>
Message-ID: <20020712190145.GA7938@hooloovoo>

SA (sarmstrong13@mac.com) wrote:
> 
> How do you slice a string from rear to front that is variable length?
You can use negative indexes for the slices. Like:
word[-2:]    # The last two characters
read the tutorial at
http://python.org/doc/current/tut/node5.html#SECTION005120000000000000000
it also has a neat ascii-art to help better understanding.
> 
> For example:
> 
> I have two strings -
>     test.html
>     test.txt
> 
> I would like to compare each string individually and do a conditional
> statement that says how to handle the file. In other words, I would like my
> script to individually discern between the .txt file and the .html file and
> handle each file differently based upon it's file extension.
> 
> 
> Would this be better hadled with re or string slicing?
According to PEP 8 (sytle guide for python code) you should use
endswith() instead:
(from http://www.python.org/peps/pep-0008.html)
    - Avoid slicing strings when checking for prefixes or suffixes.
      Use startswith() and endswith() instead, since they are
      faster,
      cleaner and less error prone.  E.g.:
          No:  if foo[:3] == 'bar':
          Yes: if foo.startswith('bar'):

So you should do 
if string.endswith('.txt'):
	# text file
elif string.endswith('.html'):
	# html file
else:
	#other cases

abli
abli@freemail.hu



From glingl@aon.at  Fri Jul 12 19:57:51 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 12 Jul 2002 20:57:51 +0200
Subject: [Tutor] I need help slicing.
References: <B9548722.9852%sarmstrong13@mac.com>
Message-ID: <00c201c229d6$05d26590$1615a8c0@mega>

> How do you slice a string from rear to front that is variable length?
>
> For example:
>
> I have two strings -
>     test.html
>     test.txt
>
> I would like to compare each string individually and do a conditional
> statement that says how to handle the file. In other words, I would like
my
> script to individually discern between the .txt file and the .html file
and
> handle each file differently based upon it's file extension.
>
Perhaps you can use this approach:

>>> def extension(fn):
         return fn.split('.')[-1]

>>> extension('test.html')
'html'
>>> extension('test.txt')
'txt'
>>> 'root/subdir/file'.split('/')
['root', 'subdir', 'file']
>>>





From shalehperry@attbi.com  Fri Jul 12 20:22:01 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 12 Jul 2002 12:22:01 -0700 (PDT)
Subject: [Tutor] event-based programming
In-Reply-To: <2E7466AE-9541-11D6-BB80-00039351FE6A@mac.com>
Message-ID: <XFMail.20020712122201.shalehperry@attbi.com>

On 12-Jul-2002 Erik Price wrote:
> I was wondering if one (or more) of the helpful geniuses on this list 
> could help me understand how event-based programming works.  This is 
> something that I have seen in a Java program called RoboCode and also in 
> JavaScript-enabled web browsers, which trigger event handlers written in 
> JavaScript embedded into an HTML documents, and I'm sure that it can be 
> done with a language like Python.  But what I don't understand is how 
> the program knows to "watch" for the event.
> 
> Does the event have to "target" the event handler with a message, or 
> does the simple act of an "event" being triggered cause the event 
> handler to execute?  In other words, does the event handler watch some 
> specific code for an event to happen, or does the event have to be sent 
> to the event handler?  And how does one write code that "watches" for 
> events in this fashion, regardless of whether it is targetted or not -- 
> does that mean that event-based code must be written like a daemon, 
> constantly running and waiting for messages?
> 
> I'm hoping someone can give me a very high-level, theoretical 
> explanation of how this works.
> 

In general event systems work on a "subscribe/notify" basis.  The application
that wants to hear events tells the event source that is is interested in
events.  When an event occurs the source then sends the event to each subscriber
application.  You may also see this referred to as listen/send.

GUI applications also use this style of communication.

In psuedo code.

event source:

accept_subscribe message, input is who and what:
  store in listeners who, what

on event generate:
  for each who in listeners
    if what matches event
      send event to who

the subscribe application:

send_subscribe, supply identity and interest

receive event:
  call handler for event

This can be seen as any number of real world events.  Consider the home that
subscribes to news via the morning paper.

Home sends subscription notification to company
when newspaper is ready it is shipped to the Home
when the Home has time to read the paper the news is accepted

Add to this something like your monthly fee for reading the paper.  If you stop
paying the paper stops coming.  Many systems will have the event source check
that the listener is still there and stop sending events or the burden is on
the listener to periodically resubscribe.

Hope this helps.



From sarmstrong13@mac.com  Fri Jul 12 20:26:54 2002
From: sarmstrong13@mac.com (SA)
Date: Fri, 12 Jul 2002 14:26:54 -0500
Subject: [Tutor] I need help slicing.
In-Reply-To: <3D2F2585.933A19E2@ccvcorp.com>
Message-ID: <B95497AE.986B%sarmstrong13@mac.com>

On 7/12/02 1:52 PM, "Jeff Shannon" <jeff@ccvcorp.com> wrote:

> 
>>>> import os
>>>> os.path.join('c:\\temp', 'subdir', 'file.txt')
> 'c:\\temp\\subdir\\file.txt'
>>>> fname = 'c:\\temp\\textfile.txt'
>>>> os.path.splitext(fname)
> ('c:\\temp\\textfile', '.txt')
>>>> os.path.split(fname)
> ('c:\\temp', 'textfile.txt')
>>>> os.path.dirname(fname)
> 'c:\\temp'
>>>> 
> 

Yes. I thought about the os module. But all of the paths in the querystrings
will be relative. For example:

http://localhost/cgi-bin/somepython.py?filename=docs/test.txt  or
http://localhost/cgi-bin/somepython.py?filename=docs/test.html

So what I want to prevent is someone doing the following:

http://localhost/cgi-bin/somepython.py?filename=/etc/passwd

So my thought was either write the script to limit all filenames to files in
this relative directory or to use splicing to verify the file extension.
Does this sound like a secure enough method?

Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me




From sarmstrong13@mac.com  Fri Jul 12 20:25:26 2002
From: sarmstrong13@mac.com (SA)
Date: Fri, 12 Jul 2002 14:25:26 -0500
Subject: [Tutor] I need help slicing.
In-Reply-To: <Pine.LNX.4.44.0207121143020.7061-100000@hkn.eecs.berkeley.edu>
Message-ID: <B9549756.986A%sarmstrong13@mac.com>

On 7/12/02 1:57 PM, "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> wrote:
> 
> 
> To get that file extension, we can look for the last position of the '.'
> in the string, and slice from there.  Regular expressions will work, but
> this pattern is simple enough that it might just be easier to us a simple
> rfind() or rindex() to get the last position of that period.
> 
> ###
>>>> filename = "foobar.xml"
>>>> filename.rindex('.')
> 6
>>>> filename[6:]
> '.xml'
> ###
> 
> 
> And to make this convenient for ourselves, we can put these pieces
> together into a function:
> 
> ###
>>>> def file_extension(filename):
> ...     dot_index = filename.rindex('.')
> ...     return filename[dot_index :]
> ...
>>>> file_extension('foobar.html')
> '.html'
> ###
> 
> 
> 
>> On another note, say it has a directory in front of the file, I would
>> like the script to look at the directory name and decide whether it is
>> ok or not to continue on working on this file.
> 
> Hmmm... If we're doing a lot of path-related things, we may want to look
> at the 'os.path' module, which brings a lot of path-related functions
> together:
> 
>   http://www.python.org/doc/lib/module-os.path.html
> 
> 
> Hey, in fact, 'os.path' has a function called 'splitext()' which splits
> the extension right out of a filename, just like the file_extension()
> function above!  Very nice.  *grin*
> 
> Another advantage of using os.path is that it takes care of some
> platform-specific stuff.
> 
> 
> 
> 
> Best of wishes to you!
> 
> 
Yes. I thought about the os module. But all of the paths in the querystrings
will be relative. For example:

http://localhost/cgi-bin/somepython.py?filename=docs/test.txt  or
http://localhost/cgi-bin/somepython.py?filename=docs/test.html

So what I want to prevent is someone doing the following:

http://localhost/cgi-bin/somepython.py?filename=/etc/passwd

So my thought was either write the script to limit all filenames to files in
this relative directory or to use splicing to verify the file extension.
Does this sound like a secure enough method?

Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me




From sarmstrong13@mac.com  Fri Jul 12 20:30:09 2002
From: sarmstrong13@mac.com (SA)
Date: Fri, 12 Jul 2002 14:30:09 -0500
Subject: [Tutor] Help?
In-Reply-To: <61.227f99a4.2a603ccd@aol.com>
Message-ID: <B9549871.986C%sarmstrong13@mac.com>

> This message is in MIME format. Since your mail reader does not understand
this format, some or all of this message may not be legible.

--B_3109329010_1361405
Content-type: text/plain; charset="US-ASCII"
Content-transfer-encoding: 7bit

On 7/12/02 9:08 AM, "Malmoo20@aol.com" <Malmoo20@aol.com> wrote:

> What are some ways for running a program?
> Please email at extxn1@aol.com

For running a python program you could run:

python scriptname.py

In the command line.

If you are on a unix type system you could add:

#!/usr/bin/env python

To the beginning of the script and then make the script executable with:
Chmod +x sriptnamehere.py

Good Luck.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me


--B_3109329010_1361405
Content-type: text/html; charset="US-ASCII"
Content-transfer-encoding: quoted-printable

<HTML>
<HEAD>
<TITLE>Re: [Tutor] Help?</TITLE>
</HEAD>
<BODY>
<FONT FACE=3D"Verdana">On 7/12/02 9:08 AM, &quot;Malmoo20@aol.com&quot; &lt;M=
almoo20@aol.com&gt; wrote:<BR>
<BR>
</FONT><BLOCKQUOTE><FONT SIZE=3D"2"><FONT FACE=3D"Arial">What are some ways for=
 running a program?<BR>
Please email at extxn1@aol.com<BR>
</FONT></FONT></BLOCKQUOTE><FONT FACE=3D"Verdana"><BR>
For running a python program you could run:<BR>
<BR>
python scriptname.py<BR>
<BR>
In the command line.<BR>
<BR>
If you are on a unix type system you could add:<BR>
<BR>
#!/usr/bin/env python<BR>
<BR>
To the beginning of the script and then make the script executable with:<BR=
>
Chmod +x sriptnamehere.py<BR>
<BR>
Good Luck.<BR>
SA<BR>
<BR>
<BR>
-- <BR>
&quot;I can do everything on my Mac I used to on my PC. Plus a lot more ...=
&quot;<BR>
-Me<BR>
</FONT>
</BODY>
</HTML>


--B_3109329010_1361405--




From dyoo@hkn.eecs.berkeley.edu  Fri Jul 12 20:48:09 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 12 Jul 2002 12:48:09 -0700 (PDT)
Subject: [Tutor] A question on getting binary data from the net
In-Reply-To: <000701c2293f$34770910$1615a8c0@mega>
Message-ID: <Pine.LNX.4.44.0207121201440.7061-100000@hkn.eecs.berkeley.edu>


On Fri, 12 Jul 2002, Gregor Lingl wrote:

> import urllib
> def randombytes(n=128):
>     if n>2048: print "Maximum of 2048 bytes returned"
>     urlstr="http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?"+\
>                                       "nbytes=%d&fmt=bin"%n
>     return [ord(c) for c in urllib.urlopen(urlstr).read(n)]


Wow, very nice!  Let's tie this into a subclass of Random, so that we can
use this as if it were just like the 'random' module:



###
"""fermi_random.py

Danny Yoo (dyoo@hkn.eecs.berkeley.edu)

A random number generator that uses fourmilab as a source of random
bits.  See the thread started here:

    http://mail.python.org/pipermail/tutor/2002-July/015581.html

for more details.

This module should have the same interface as the 'random' module in the
standard library.


One improvement that will probably help is to increase the number of bits
used to generate a random float.  At the moment, we're taking 16 bits at a
time.  We should at least match drand48!  *grin*

"""


import random, urllib, struct

def random_ushorts(n=128):
    """Returns a random list of unsigned "shorts", taking 16 bits at a
time."""
    assert n >= 2048, "Maximum of 2048 bytes returned"
    urlstr = "http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?"+\
             "nbytes=%d&fmt=bin"%n
    return [struct.unpack("H", c)[0]
            for c in clump_by_twos(urllib.urlopen(urlstr).read())]

def clump_by_twos(sequence):
    fours = []
    for i in range(len(sequence)/2):
        fours.append(sequence[i*2 : i*2 + 2])
    return fours

BIGGEST_USHORT = 2**16-1


class FermiRandom(random.Random):
    def __init__(self):
        self._source = []
        self._refill_shortsource()

    def random(self):
        if not self._source: self._refill_shortsource()
        return float(self._source.pop()) / float(BIGGEST_USHORT)

    def _refill_shortsource(self):
        self._source.extend(random_ushorts(2048))

    ## The rest of these functions won't be useful, since our source
    ## is truly random and can't be seeded.
    def seed(self): pass
    def getstate(self): return None
    def setstate(self): pass
    def jumpahead(self): pass



## A little trick to make fermi_random look much like the random module.
_inst = FermiRandom()
seed = _inst.seed
random = _inst.random
uniform = _inst.uniform
randint = _inst.randint
choice = _inst.choice
randrange = _inst.randrange
shuffle = _inst.shuffle
normalvariate = _inst.normalvariate
lognormvariate = _inst.lognormvariate
cunifvariate = _inst.cunifvariate
expovariate = _inst.expovariate
vonmisesvariate = _inst.vonmisesvariate
gammavariate = _inst.gammavariate
stdgamma = _inst.stdgamma
gauss = _inst.gauss
betavariate = _inst.betavariate
paretovariate = _inst.paretovariate
weibullvariate = _inst.weibullvariate
getstate = _inst.getstate
setstate = _inst.setstate
jumpahead = _inst.jumpahead
whseed = _inst.whseed
###



>  P.S. or should I use urlretrieve instead? But, then, how do I prevent
> it from writing to disk?


urllib.urlretrieve() is meant to write to disk, so we might prefer
urllib.urlopen() instead.





From glingl@aon.at  Fri Jul 12 21:31:52 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 12 Jul 2002 22:31:52 +0200
Subject: [Tutor] A question on getting binary data from the net
References: <Pine.LNX.4.44.0207121201440.7061-100000@hkn.eecs.berkeley.edu>
Message-ID: <000c01c229e3$287c6070$1615a8c0@mega>

Hi Danny!

Nice this; I'm going to study it now.

Moreover I must admit, that I can't explain the name
fourmilab - perhaps I should have skimmed through the
website - but I think there must be some difference
between 'fourmi...' and the famous old guy Fermi...

Gregor


----- Original Message ----- 
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "Gregor Lingl" <glingl@aon.at>
Cc: <tutor@python.org>
Sent: Friday, July 12, 2002 9:48 PM
Subject: Re: [Tutor] A question on getting binary data from the net


> 
> class FermiRandom(random.Random):
>     def __init__(self):
>         self._source = []
>         self._refill_shortsource()
....




From dyoo@hkn.eecs.berkeley.edu  Fri Jul 12 21:53:11 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 12 Jul 2002 13:53:11 -0700 (PDT)
Subject: [Tutor] I need help slicing.
In-Reply-To: <B9549756.986A%sarmstrong13@mac.com>
Message-ID: <Pine.LNX.4.44.0207121348010.9583-100000@hkn.eecs.berkeley.edu>


> Yes. I thought about the os module. But all of the paths in the
> querystrings will be relative. For example:

No problem: there's a function in os.path called abspath() that will turn
relative urls into absolute ones, so that you can even deal with stuff
like '../../../etc/../etc/passwd':

###
>>> print os.path.abspath('../../etc/../etc/passwd')
/etc/passwd
###

If you do everything with absolute paths, that may simplify your problem.



> So my thought was either write the script to limit all filenames to
> files in this relative directory or to use splicing to verify the file
> extension. Does this sound like a secure enough method?

File extension doesn't sound too safe, but limiting access to a certain
directory sounds sorta ok.  Just make sure to use os.path.abspath(), to
pacify weird relative paths into absolute ones.


Hope this helps!




From dyoo@hkn.eecs.berkeley.edu  Fri Jul 12 21:56:33 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 12 Jul 2002 13:56:33 -0700 (PDT)
Subject: [Tutor] A question on getting binary data from the net
In-Reply-To: <000c01c229e3$287c6070$1615a8c0@mega>
Message-ID: <Pine.LNX.4.44.0207121353290.9583-100000@hkn.eecs.berkeley.edu>


On Fri, 12 Jul 2002, Gregor Lingl wrote:

> Nice this; I'm going to study it now.

One improvement we should make is to get it to consider more bits; I
expanded the range to 16 bit arithemtic, but that's probably not good
enough for real-life use.

I don't know how to do 48 bit arithmetic yet, but I'll pull out The Art of
Computer Programming and read up on it this evening.



> Moreover I must admit, that I can't explain the name fourmilab - perhaps
> I should have skimmed through the website - but I think there must be
> some difference between 'fourmi...' and the famous old guy Fermi...

Doh!  I mean to name the module and class 'fourmi', but for some reason,
my fingers typed 'fermi' every time; I guess I had Fermi on the brain.


Best of wishes!




From dyoo@hkn.eecs.berkeley.edu  Fri Jul 12 22:05:54 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 12 Jul 2002 14:05:54 -0700 (PDT)
Subject: [Tutor] A question on getting binary data from the net
In-Reply-To: <Pine.LNX.4.44.0207121201440.7061-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0207121401120.9583-100000@hkn.eecs.berkeley.edu>


>
> def random_ushorts(n=128):
>     """Returns a random list of unsigned "shorts", taking 16 bits at a
> time."""
>     assert n >= 2048, "Maximum of 2048 bytes returned"
      ^^^^^^^^^^^^^^^^

Ooops.

This assertion is testing the wrong thing: it's saying "Make sure that n
is greater than or equal to 2048", but it should have been, "Make sure
that n is less than or equal to 2048".

###
assert n <= 2048, "Maximum of 2048 bytes returned"
###

is the right way of saying that.  My apologies!




From tim.one@comcast.net  Fri Jul 12 22:20:49 2002
From: tim.one@comcast.net (Tim Peters)
Date: Fri, 12 Jul 2002 17:20:49 -0400
Subject: [Tutor] A question on getting binary data from the net
In-Reply-To: <Pine.LNX.4.44.0207121353290.9583-100000@hkn.eecs.berkeley.edu>
Message-ID: <LNBBLJKPBEHFEDALKOLCCEDOAEAB.tim.one@comcast.net>

[Danny Yoo, having too much fun <wink>]
> ...
> I don't know how to do 48 bit arithmetic yet, but I'll pull out The Art of
> Computer Programming and read up on it this evening.

Python will do million-bit arithmetic for you if you like:  don't go
reinventing this heavy wheel!  Using 53 bits would be better, since almost
all machines have doubles (Python floats) with 53 mantissa bits.  If you
have a Python long n containing no more than 53 bits, you can normalize it
into the half-open range 0.0 <= x < 1.0 (note this is random.random()'s
promise) very simply via

    math.ldexp(n, -53)

That's a trick of the trade that isn't obvious before someone tells you
about it <wink>.

Something to note here too:

    for i in range(len(sequence)/2):
        fours.append(sequence[i*2 : i*2 + 2])

Consider:

    for i in range(0, len(sequence), 2):
        fours.append(sequence[i : i+2])

instead.  Before you know it, you won't have any code left at all <wink>.




From tjenkins@devis.com  Fri Jul 12 22:30:33 2002
From: tjenkins@devis.com (Tom Jenkins)
Date: 12 Jul 2002 17:30:33 -0400
Subject: [Tutor] A question on getting binary data from the net
In-Reply-To: <LNBBLJKPBEHFEDALKOLCCEDOAEAB.tim.one@comcast.net>
References: <LNBBLJKPBEHFEDALKOLCCEDOAEAB.tim.one@comcast.net>
Message-ID: <1026509433.1529.51.camel@asimov>

On Fri, 2002-07-12 at 17:20, Tim Peters wrote:
> [Danny Yoo, having too much fun <wink>]
[snip]
> 
> Something to note here too:
> 
>     for i in range(len(sequence)/2):
>         fours.append(sequence[i*2 : i*2 + 2])
> 
> Consider:
> 
>     for i in range(0, len(sequence), 2):
>         fours.append(sequence[i : i+2])
> 
> instead.  Before you know it, you won't have any code left at all <wink>.
> 

which (naturally for 2.+) leads to:
def clump_by_twos(sequence):
	return [sequence[i : i+2] for i in range(0, len(sequence), 2)]

i think the next step would required a neurological hookup <wink>

-- 

Tom Jenkins
Development InfoStructure
http://www.devis.com





From dyoo@hkn.eecs.berkeley.edu  Fri Jul 12 23:56:11 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 12 Jul 2002 15:56:11 -0700 (PDT)
Subject: [Tutor] A question on getting binary data from the net
In-Reply-To: <LNBBLJKPBEHFEDALKOLCCEDOAEAB.tim.one@comcast.net>
Message-ID: <Pine.LNX.4.44.0207121454150.9583-100000@hkn.eecs.berkeley.edu>


On Fri, 12 Jul 2002, Tim Peters wrote:

> [Danny Yoo, having too much fun <wink>]
> > ...
> > I don't know how to do 48 bit arithmetic yet, but I'll pull out The Art of
> > Computer Programming and read up on it this evening.
>
> Python will do million-bit arithmetic for you if you like:  don't go
> reinventing this heavy wheel!  Using 53 bits would be better, since
> almost all machines have doubles (Python floats) with 53 mantissa bits.
> If you have a Python long n containing no more than 53 bits, you can
> normalize it into the half-open range 0.0 <= x < 1.0 (note this is
> random.random()'s promise) very simply via
>
>     math.ldexp(n, -53)

Oooh!  I didn't know about that function before!  Thank you.

Here is the new-and-improved version of fourmirandom.py:


###
"""fourmirandom.py --- A random number generator that returns truly
random numbers.

Danny Yoo (dyoo@hkn.eecs.berkeley.edu), with help from the kind folks
at Python-tutor:

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


See the thread started here:

    http://mail.python.org/pipermail/tutor/2002-July/015581.html

for more details on how this got started.


This module should have the same interface as the 'random' module in
the standard library:

    http://www.python.org/doc/lib/module-random.html

Just replace the word "pseudo" with "real".  *grin*


Our source of random bits comes from:

    http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits

Don't abuse this module too much, as Fourmilab does have a quota on
the number of bits one is allows to pull from it."""

## We import these, but put underscores in front of the names, just to
## prevent name confusion between the module '_random' and the
## function 'random'.

import random as _random
import urllib as _urllib
import math as _math


MAX_BITS_GIVEN_BY_FOURMI = 2048 * 8
def random_bits(n=MAX_BITS_GIVEN_BY_FOURMI):
    """Returns a list of n random bits."""
    assert n <= MAX_BITS_GIVEN_BY_FOURMI, "Maximum of 2048 bytes returned"
    urlstr = "http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?"+\
             "nbytes=%d&fmt=bin" % math.ceil(n / 8.0)
    bytes = _urllib.urlopen(urlstr).read()
    bits = []
    for b in bytes: bits.extend(byte_to_binary(ord(b)))
    return bits[:n]


def _pseudorandom_bits(n):
    """Similar to random_bits, but for offline testing.  We don't want
    to hammer Fourmilab while testing this module."""
    return [_random.randrange(2) for i in range(n)]


def clump_by_n(sequence, n):
    """Given a sequence, returns a list of grouped chunks of that
    sequence, each of length n (except, possibly, the last chunk)."""
    collection = []
    for i in range(0, len(sequence), n):
        collection.append(sequence[i : i+n])
    return collection


def byte_to_binary(byte):
    """Converts a byte into a binary stream."""
    assert 0 <= byte < 256, "byte not within range 0 <= byte < 256"
    bits = []
    for i in range(8):
        bits.append(byte % 2)
        byte = byte >> 1;
    bits.reverse()
    return bits


def binary_stream_to_long(bits):
    """Converts a list of bits to a long."""
    value = 0L
    for b in bits: value = (value * 2) + b
    return value



class FourmiRandom(_random.Random):
    """A subclass of _random.Random that supplies truly random numbers."""
    BITS_USED = 53
    SOURCE_CAPACITY = int(MAX_BITS_GIVEN_BY_FOURMI / BITS_USED)
    def __init__(self):
        self._source = []


    def random(self):
        if not self._source: self._refill_source()
        return _math.ldexp(self._source.pop(), -53)

    def _refill_source(self):
##        bits = _pseudorandom_bits(self.SOURCE_CAPACITY * self.BITS_USED)
        bits = random_bits(self.SOURCE_CAPACITY * self.BITS_USED)
        clumps = clump_by_n(bits, self.BITS_USED)
        for c in clumps: self._source.append(binary_stream_to_long(c))


    ## The rest of these functions won't be useful, since our source
    ## is truly random and can't be seeded.
    def seed(self): pass
    def getstate(self): return None
    def setstate(self): pass
    def jumpahead(self): pass



## A little trick to make fermi_random look much like the random module.
_inst = FourmiRandom()
seed = _inst.seed
random = _inst.random
uniform = _inst.uniform
randint = _inst.randint
choice = _inst.choice
randrange = _inst.randrange
shuffle = _inst.shuffle
normalvariate = _inst.normalvariate
lognormvariate = _inst.lognormvariate
cunifvariate = _inst.cunifvariate
expovariate = _inst.expovariate
vonmisesvariate = _inst.vonmisesvariate
gammavariate = _inst.gammavariate
stdgamma = _inst.stdgamma
gauss = _inst.gauss
betavariate = _inst.betavariate
paretovariate = _inst.paretovariate
weibullvariate = _inst.weibullvariate
getstate = _inst.getstate
setstate = _inst.setstate
jumpahead = _inst.jumpahead
whseed = _inst.whseed
###


How does this look?




From spacedweller@hotmail.com  Fri Jul 12 23:44:19 2002
From: spacedweller@hotmail.com (a polite punk)
Date: Fri, 12 Jul 2002 18:44:19 -0400
Subject: [Tutor] Problem with program ending
Message-ID: <F1361uqYA2feIQR3xgT0001131c@hotmail.com>

Hi,

My name is Jonathan and I am a new Python programmer!  But, I am having 
trouble with a certain practice program that I have written.  It deals with 
functions and the try and except statements.  The trouble is with ending the 
program.  I use these commands below:

                         import sys
                         sys.exit()



but when i do, it ignores it and continues with the program in the main 
function.  I think it has to do with the use of the try and except 
statements since i do not have this problem in the programs without the try 
and except statements.  Here is the source code of the program below:



#Practice program with functions
#
#

def multiplyTwoNumbers(firstNumber, secondNumber):
    answer = firstNumber * secondNumber
    print "\n\n"
    print "The answer is:  ", answer
    print "\n\n"
    try:
        quitOrContinue = int(raw_input("Press 1 to continue or 0 to quit:  
"))
        if quitOrContinue == 1:
            main()

        elif quitOrContinue == 0:
            import sys
            sys.exit()

        else:
            main()

    except:
        print "\n\nYou must enter either 1 or 0"
        print
        main()



def divideTwoNumbers(firstNumber, secondNumber):
    answer = firstNumber / secondNumber
    print "\n\n"
    print "The answer is:  ", answer
    try:
        quitOrContinue = int(raw_input("Press 1 to continue or 0 to quit:  
"))
        if quitOrContinue == 1:
            main()

        elif quitOrContinue == 0:
            import sys
            sys.exit()

        else:
            main()

    except:
        print "\n\nYou must enter either 1 or 0"
        print
        main()



def subtractTwoNumbers(firstNumber, secondNumber):
    answer = firstNumber - secondNumber
    print "\n\n"
    print "The answer is:  ", answer
    try:
        quitOrContinue = int(raw_input("Press 1 to continue  or 0 to quit:  
"))
        while quitOrContinue != 1 or quitOrContinue != 0:
            print "You must enter either 1 or 0"
            try:
                quitOrContinue = int(raw_input("Press 1 to continue or 0 to 
quit:  "))
                if quitOrContinue == 1:
                    main()

                elif quitOrContinue == 0:
                    import sys
                    sys.exit()

                else:
                    main()

            except:
                print "You must enter valid choices"

    except:
        print "\n\nYou must enter either 1 or 0"


def addTwoNumbers(firstNumber, secondNumber):
    answer = firstNumber + secondNumber
    print "\n\n"
    print "The answer is:  ", answer

def main():
    print "\n\n"
    print "Press 1 to multiply two numbers"
    print "Press 2 to divide two numbers"
    print "Press 3 to subtract two numbers"
    print "Press 4 to add two numbers"
    print "Press 0 to quit"
    print
    try:
        choice = int(raw_input("Enter your selection:  "))
        try:
            firstNumber = int(raw_input("Enter the first number:  "))
            try:
                secondNumber = int(raw_input("Enter the second number:  "))
                if choice == 1:
                    multiplyTwoNumbers(firstNumber, secondNumber)

                elif choice == 2:
                    divideTwoNumbers(firstNumber, secondNumber)

                elif choice == 3:
                    subtractTwoNumbers(firstNumber, secondNumber)

                elif choice == 4:
                    addTwoNumbers(firstNumber, secondNumber)

                elif choice == 0:
                    import sys
                    sys.exit()

                else:
                    print
                    print "Invalid entry"
                    main()

            except:
                print "\n\nYou must enter an integer only"
                print
                main()

        except:
            print "\n\You must enter an integer only"
            print
            main()

    except:
        print "\n\nYou must enter integers only"
        print
        main()

main()






_________________________________________________________________
Send and receive Hotmail on your mobile device: http://mobile.msn.com




From shecky@experimentzero.org  Sat Jul 13 00:12:49 2002
From: shecky@experimentzero.org (Britt A. Green)
Date: Fri, 12 Jul 2002 16:12:49 -0700
Subject: [Tutor] Planning out your program
Message-ID: <033001c229f9$a8c3e080$5f01000a@opentable.com.ot>

I made a very crude little text adventure in Python a few months ago.
However, as I began to add on functionality to it, it became apparent that a
lot of the underlying code wasn't capable of being improved. The original
code basically let one player walk amongst a dozen rooms and pick things up.
To get it to do much more would mean a huge rewrite of what I'd already
done.

So I'm going to have a lot of free time this summer and want to write
something a bit more complex. What would be the best way to plan out my code
before I start writing?

Britt

--
"My mom says I'm cool."




From dyoo@hkn.eecs.berkeley.edu  Sat Jul 13 00:59:54 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 12 Jul 2002 16:59:54 -0700 (PDT)
Subject: [Tutor] A question on getting binary data from the net
 [fourmirandom.py afternotes]
In-Reply-To: <Pine.LNX.4.44.0207121454150.9583-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0207121803520.14461-100000@hkn.eecs.berkeley.edu>


On Fri, 12 Jul 2002, Danny Yoo wrote:

> On Fri, 12 Jul 2002, Tim Peters wrote:
>
> > [Danny Yoo, having too much fun <wink>]
> > > ... I don't know how to do 48 bit arithmetic yet, but I'll pull out
> > > The Art of Computer Programming and read up on it this evening.
> >
> > Python will do million-bit arithmetic for you if you like:  don't go
> > reinventing this heavy wheel!  Using 53 bits would be better, since
> > almost all machines have doubles (Python floats) with 53 mantissa
> > bits. If you have a Python long n containing no more than 53 bits, you
> > can normalize it into the half-open range 0.0 <= x < 1.0 (note this is
> > random.random()'s promise) very simply via
> >
> >     math.ldexp(n, -53)
>
> Oooh!  I didn't know about that function before!  Thank you.
>
> Here is the new-and-improved version of fourmirandom.py:


I still need to do some polishing of the code (there are still references
to the misspelled "fermi" in there, and some "unit" testing would be
nice.)  But this was a fun project!


Since the source code is long, I'll put in on my web site instead.  The
future home of this module will be:

    http://hkn.eecs.berkeley.edu/~dyoo/python/fourmirandom

and I'll distutils this as soon as I get home...  *grin* Does anyone know
if it's possible to contact the maintainer of the Hotbits site?


Thanks again!




From shalehperry@attbi.com  Sat Jul 13 01:00:54 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 12 Jul 2002 17:00:54 -0700 (PDT)
Subject: [Tutor] Problem with program ending
In-Reply-To: <F1361uqYA2feIQR3xgT0001131c@hotmail.com>
Message-ID: <XFMail.20020712170054.shalehperry@attbi.com>

On 12-Jul-2002 a polite punk wrote:
> Hi,
> 
> My name is Jonathan and I am a new Python programmer!  But, I am having 
> trouble with a certain practice program that I have written.  It deals with 
> functions and the try and except statements.  The trouble is with ending the 
> program.  I use these commands below:
> 
>                          import sys
>                          sys.exit()
> 
> 
> 
> but when i do, it ignores it and continues with the program in the main 
> function.  I think it has to do with the use of the try and except 
> statements since i do not have this problem in the programs without the try 
> and except statements.  Here is the source code of the program below:
> 

>>> import sys
>>> try:
...   sys.exit(1)
... except:
...   print "caught it"
... 
caught it

you see, sys.exit() causes python to exit by raising an exception.

The problem with your code is you do not specify the type(s) of exception but
instead catch all of them.

>>> try:
...   sys.exit()
... except:
...   print sys.exc_type
... 
exceptions.SystemExit




From ak@silmarill.org  Sat Jul 13 01:06:43 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 12 Jul 2002 20:06:43 -0400
Subject: [Tutor] Problem with program ending
In-Reply-To: <F1361uqYA2feIQR3xgT0001131c@hotmail.com>
References: <F1361uqYA2feIQR3xgT0001131c@hotmail.com>
Message-ID: <20020713000643.GA11482@ak.silmarill.org>

On Fri, Jul 12, 2002 at 06:44:19PM -0400, a polite punk wrote:
> Hi,
> 
> My name is Jonathan and I am a new Python programmer!  But, I am having 
> trouble with a certain practice program that I have written.  It deals with 
> functions and the try and except statements.  The trouble is with ending 
> the program.  I use these commands below:
> 
>                         import sys
>                         sys.exit()
> 
> 
> 
> but when i do, it ignores it and continues with the program in the main 
> function.  I think it has to do with the use of the try and except 
> statements since i do not have this problem in the programs without the try 
> and except statements.  Here is the source code of the program below:
> 
> 
> 
> #Practice program with functions
> #
> #
> 
> def multiplyTwoNumbers(firstNumber, secondNumber):
>    answer = firstNumber * secondNumber
>    print "\n\n"
>    print "The answer is:  ", answer
>    print "\n\n"
>    try:
>        quitOrContinue = int(raw_input("Press 1 to continue or 0 to quit:  
> "))
>        if quitOrContinue == 1:
>            main()
> 
>        elif quitOrContinue == 0:
>            import sys
>            sys.exit()
> 
>        else:
>            main()
> 
>    except:
>        print "\n\nYou must enter either 1 or 0"
>        print
>        main()
>
sys.exit() raises a special exception for exit. do this instead:

ans = raw_input("> ")
if ans == '0':
    import sys
    sys.exit()
elif ans == '1':
    main()
else:
    print "Invalid input"


> 
> 
> 
> def divideTwoNumbers(firstNumber, secondNumber):
>    answer = firstNumber / secondNumber
>    print "\n\n"
>    print "The answer is:  ", answer
>    try:
>        quitOrContinue = int(raw_input("Press 1 to continue or 0 to quit:  
> "))
>        if quitOrContinue == 1:
>            main()
> 
>        elif quitOrContinue == 0:
>            import sys
>            sys.exit()
> 
>        else:
>            main()
> 
>    except:
>        print "\n\nYou must enter either 1 or 0"
>        print
>        main()
> 
> 
> 
> def subtractTwoNumbers(firstNumber, secondNumber):
>    answer = firstNumber - secondNumber
>    print "\n\n"
>    print "The answer is:  ", answer
>    try:
>        quitOrContinue = int(raw_input("Press 1 to continue  or 0 to quit:  
> "))
>        while quitOrContinue != 1 or quitOrContinue != 0:
>            print "You must enter either 1 or 0"
>            try:
>                quitOrContinue = int(raw_input("Press 1 to continue or 0 to 
> quit:  "))
>                if quitOrContinue == 1:
>                    main()
> 
>                elif quitOrContinue == 0:
>                    import sys
>                    sys.exit()
> 
>                else:
>                    main()
> 
>            except:
>                print "You must enter valid choices"
> 
>    except:
>        print "\n\nYou must enter either 1 or 0"
> 
> 
> def addTwoNumbers(firstNumber, secondNumber):
>    answer = firstNumber + secondNumber
>    print "\n\n"
>    print "The answer is:  ", answer
> 
> def main():
>    print "\n\n"
>    print "Press 1 to multiply two numbers"
>    print "Press 2 to divide two numbers"
>    print "Press 3 to subtract two numbers"
>    print "Press 4 to add two numbers"
>    print "Press 0 to quit"
>    print
>    try:
>        choice = int(raw_input("Enter your selection:  "))
>        try:
>            firstNumber = int(raw_input("Enter the first number:  "))
>            try:
>                secondNumber = int(raw_input("Enter the second number:  "))
>                if choice == 1:
>                    multiplyTwoNumbers(firstNumber, secondNumber)
> 
>                elif choice == 2:
>                    divideTwoNumbers(firstNumber, secondNumber)
> 
>                elif choice == 3:
>                    subtractTwoNumbers(firstNumber, secondNumber)
> 
>                elif choice == 4:
>                    addTwoNumbers(firstNumber, secondNumber)
> 
>                elif choice == 0:
>                    import sys
>                    sys.exit()
> 
>                else:
>                    print
>                    print "Invalid entry"
>                    main()
> 
>            except:
>                print "\n\nYou must enter an integer only"
>                print
>                main()
> 
>        except:
>            print "\n\You must enter an integer only"
>            print
>            main()
> 
>    except:
>        print "\n\nYou must enter integers only"
>        print
>        main()
> 
> main()
> 
> 
> 
> 
> 
> 
> _________________________________________________________________
> Send and receive Hotmail on your mobile device: http://mobile.msn.com
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From ak@silmarill.org  Sat Jul 13 01:08:22 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 12 Jul 2002 20:08:22 -0400
Subject: [Tutor] Planning out your program
In-Reply-To: <033001c229f9$a8c3e080$5f01000a@opentable.com.ot>
References: <033001c229f9$a8c3e080$5f01000a@opentable.com.ot>
Message-ID: <20020713000822.GB11482@ak.silmarill.org>

On Fri, Jul 12, 2002 at 04:12:49PM -0700, Britt A. Green wrote:
> I made a very crude little text adventure in Python a few months ago.
> However, as I began to add on functionality to it, it became apparent that a
> lot of the underlying code wasn't capable of being improved. The original
> code basically let one player walk amongst a dozen rooms and pick things up.
> To get it to do much more would mean a huge rewrite of what I'd already
> done.
> 
> So I'm going to have a lot of free time this summer and want to write
> something a bit more complex. What would be the best way to plan out my code
> before I start writing?
>
That's a rather vague question :-). What exactly made the original code
hard to improve?

There's not quick and easy answer here, I'm afraid. This sort of thing
comes with practice, trial and error.

> 
> Britt
> 
> --
> "My mom says I'm cool."
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From shalehperry@attbi.com  Sat Jul 13 01:06:12 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 12 Jul 2002 17:06:12 -0700 (PDT)
Subject: [Tutor] Planning out your program
In-Reply-To: <033001c229f9$a8c3e080$5f01000a@opentable.com.ot>
Message-ID: <XFMail.20020712170612.shalehperry@attbi.com>

On 12-Jul-2002 Britt A. Green wrote:
> I made a very crude little text adventure in Python a few months ago.
> However, as I began to add on functionality to it, it became apparent that a
> lot of the underlying code wasn't capable of being improved. The original
> code basically let one player walk amongst a dozen rooms and pick things up.
> To get it to do much more would mean a huge rewrite of what I'd already
> done.
> 
> So I'm going to have a lot of free time this summer and want to write
> something a bit more complex. What would be the best way to plan out my code
> before I start writing?
> 

There are many schools of thought and approaches.  Flow charts, UML, object
analysis, the magic eight ball, alcohol, the list goes on and on.

Many times our first draft of a program exposes a flaw in how we thought it
would work.  The key is to learn from these types of mistakes.

Go to  your local library or bookstore and wander their computer section. 
There are many, many books about the act of programming and design.  Much of
what they say is language neutral.

Afterwards, sit down, ponder the way you would like to work it out.  Code in
pieces, examine the parts, then continue.  Many programming failures come from
someone trying to do everything in one pass.

One of my favorite analogies is programming is like cooking, sure you can just
throw all of the ingredients in the pot, add heat, and cook until it is done. 
But you have no idea what it will taste like or how long it will take.



From erikprice@mac.com  Sat Jul 13 02:07:08 2002
From: erikprice@mac.com (Erik Price)
Date: Fri, 12 Jul 2002 21:07:08 -0400
Subject: [Tutor] Planning out your program
In-Reply-To: <033001c229f9$a8c3e080$5f01000a@opentable.com.ot>
Message-ID: <DA56C382-95FC-11D6-9443-00039351FE6A@mac.com>

On Friday, July 12, 2002, at 07:12  PM, Britt A. Green wrote:

> So I'm going to have a lot of free time this summer and want to write
> something a bit more complex. What would be the best way to plan out my 
> code
> before I start writing?

I have only learned a little about it, not used it very much... but UML 
provides you with a means to diagram the things that you intend for your 
program to do before you even write a line of code.  And because it uses 
visual aids, rather than code, anyone can understand it (not necessarily 
important for a personal project, but something that is useful down the 
road).

Try UML to determine what you want to be able to do, from a UML diagram 
you can map your code closely to the classes generated that way.

Just an idea.


Erik




From dman@dman.ddts.net  Sat Jul 13 03:44:23 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Fri, 12 Jul 2002 21:44:23 -0500
Subject: [Tutor] Re: import pwd?
In-Reply-To: <003801c22903$52778340$9c21840a@tmbrau00>
References: <000501c22857$506a3a40$9c21840a@tmbrau00> <20020711160100.GD17838@dman.ddts.net> <003801c22903$52778340$9c21840a@tmbrau00>
Message-ID: <20020713024423.GA22260@dman.ddts.net>

--+QahgC5+KEYLbs62
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, Jul 11, 2002 at 01:49:35PM -0400, Timothy M. Brauch wrote:
| >>On Wed, Jul 10, 2002 at 05:18:18PM -0400, Timothy M. Brauch wrote:
[...]
| >>| So, where is pwd?
[...]
| >>in POSIX ...
[...]

| Yeah, I checked the docs and it said pwd was only available in *nix.  But
| that just brings up two more questions... Why can I import getpass if it
| doesn't work on Windows?  Okay, supposedly getpass.getpass() should work,
| and it does, but with warning messages.

Did you use the cygwin build of python?  It would have (nearly)
everything you would expect to find on *nix.

| And, question 2, I swear I am not making this up or dreaming or anything,
| but this program used to work for me, so why did it stop?

I have no idea.

| It's not all that important.  However, I thought it would have been nice =
to
| keep a log of who was using my windows 'puters.

That necessitates required logins.  For win2k you can do this,
probably nt4, and there is some way you can tell win9[58] to require a
domain logon (but I don't know how).  Then you have your PDC (samba on
linux :-)) log all logins and logouts.

-D

--=20
=20
Microsoft DNS service terminates abnormally when it receives a response
to a dns query that was never made.
Fix information: run your DNS service on a different platform.
                                                            -- bugtraq
=20
http://dman.ddts.net/~dman/


--+QahgC5+KEYLbs62
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0vlAcACgkQO8l8XBKTpRSNmACZAbCSotTTGv8bg3FQKn+GQiYX
JtgAniFCBmJ3Z/0p7uJf1J3f8415+V6l
=m4sp
-----END PGP SIGNATURE-----

--+QahgC5+KEYLbs62--



From dman@dman.ddts.net  Sat Jul 13 06:22:46 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sat, 13 Jul 2002 00:22:46 -0500
Subject: [Tutor] Re: Looking for peer review
In-Reply-To: <20020711170303.GA10735@ak.silmarill.org>
References: <002101c228fa$d8077e60$e1e03942@joeltklrijxxms> <20020711170303.GA10735@ak.silmarill.org>
Message-ID: <20020713052246.GB22260@dman.ddts.net>

--TRYliJ5NKNqkz5bu
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, Jul 11, 2002 at 01:03:03PM -0400, Andrei Kulakov wrote:
| I think this would be much better done with dyndns type of service.
| dyndns.org.

Or DDT (ddts.net).  However, as of this time the ddt client tools
require a POSIX system.  I don't know if you can make them work under
cygwin or not (you'll probably have to rewrite the portion that
queries the OS for the IP of the given interface).

For any solution of this type to work, you need at least one of two
things :
    1)  A fixed host that can act as a registry of the dynamic data.
        With my ddts.net service, that fixed host is ns1.ddts.net (for
        my machine to upload it's info, and as a secondary system for
        your machine to get it from) and ns0.ddts.net.

        This isn't viable in your case because all 3 of you have
        dynamic connections.  Without a external assistance (eg from
        ddts.net or dyndns.org) you lack the central aspect.

or

    2)  A broadcast mechanism by which each of your three hosts can
        shout from the mountain top "here I am, where are you?".

        This is also not viable for you because
            1)  Your ISP and possibly other customers will likely not
                like the broadcast traffic since it only wastes their
                bandwidth and isn't helpful to them.

            2)  If the three of you aren't on the same subnet, you
                won't have the same broadcast address anyways, so you
                can't broadcast then.

                (with IP, broadcasting only works on local networks;
                this is a feature since a broadcast uses resources on
                _every_ host on the subnet; you wouldn't want to
                receive a "hi I just booted" message from a windows
                machine in another state!)

HTH,
-D

--=20
=20
If anyone would come after me, he must deny himself and take up his
cross and follow me.  For whoever wants to save his life will lose it,
but whoever loses his life for me and for the gospel will save it.  What
good is it for a man to gain the whole world, yet forfeit his soul?  Or
what can a man give in exchange for his soul?
        Mark 8:34-37
=20
http://dman.ddts.net/~dman/


--TRYliJ5NKNqkz5bu
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0vuSYACgkQO8l8XBKTpRTHfQCfT7fdCZuxC92iIThfz5HpC/wG
QOcAoK1q9tLR2V2WBavpc7y5Iu+ejoU4
=7n6N
-----END PGP SIGNATURE-----

--TRYliJ5NKNqkz5bu--



From idiot1@netzero.net  Sat Jul 13 06:10:33 2002
From: idiot1@netzero.net (Kirk Bailey)
Date: Sat, 13 Jul 2002 01:10:33 -0400
Subject: [Tutor] cookie?
Message-ID: <3D2FB649.A6293389@netzero.net>

OK, fortune cookies. Plenty of people use them on the web. Randomly
selected pictures, links, pithy sayings. 

Well, I wrote a fortune cookie engine in python.

http://www.tinylist.org/cookielisting.shtml

There's a link there to view a page with the actual working output of
the program.

You can highlight and mouse copy, then paste in to a notepad document
for a copy, in time I will do up a tarball and a zip file, but today I'm
a little busy. Sounds like a candidate for the useless python site,
what?
-- 

end

Respectfully,
             Kirk D Bailey


+---------------------"Thou Art Free." -Eris-----------------------+
| http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
| http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
+------------------Thinking| NORMAL |Thinking----------------------+
                           +--------+
-------------------------------------------
Introducing NetZero Long Distance
Unlimited Long Distance only $29.95/ month!
Sign Up Today! www.netzerolongdistance.com



From dman@dman.ddts.net  Sat Jul 13 06:24:10 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sat, 13 Jul 2002 00:24:10 -0500
Subject: [Tutor] Re: logic testing
In-Reply-To: <20020711193606.GA437@ak.silmarill.org>
References: <5A021171E87BD411AF7700508B6940D00347C680@anchorgaming.anchorgaming.com> <20020711193606.GA437@ak.silmarill.org>
Message-ID: <20020713052410.GC22260@dman.ddts.net>

--LwW0XdcUbUexiWVK
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, Jul 11, 2002 at 03:36:06PM -0400, Andrei Kulakov wrote:
| On Thu, Jul 11, 2002 at 10:55:18AM -0700, Baker.Michael wrote:
| > i'm working with a game engine and would like a way to test "game logic"
| > with python.  the game engine runs as fast as it can - in the range of =
30 -
| > 100 frames per second. how can I make a python program that will run as=
 fast
| > as it can and still receive keyboard input?
| >=20
| > i cannot make loops work because attempts to capture raw_input() stall =
the
| > loop.
| >=20
| > i have not tried the cmd module - perhaps this will work????
|
| You can use threads - one thread captures user input, the other one
| shows stuff; you can also use select module but it's extremely
| confusing, to me at least.

If you want an example of select, let me know.  It is really quite
simple, once you know what it is trying to do.  (but don't look at the
manpage too closely, the C code is _much_ uglier than the Python code!)

-D

--=20
=20
Be sure of this:  The wicked will not go unpunished,
but those who are righteous will go free.
        Proverbs 11:21
=20
http://dman.ddts.net/~dman/


--LwW0XdcUbUexiWVK
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0vuXoACgkQO8l8XBKTpRTmpgCfbwnGEcZqkDq33H6GBj9D2u/2
QqsAn0ev/n6DDlnmqGsdsCkref+uipYo
=Lkfn
-----END PGP SIGNATURE-----

--LwW0XdcUbUexiWVK--



From dman@dman.ddts.net  Sat Jul 13 06:35:03 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sat, 13 Jul 2002 00:35:03 -0500
Subject: [Tutor] Re: A question on getting binary data from the net
In-Reply-To: <003d01c22930$06f34350$1615a8c0@mega>
References: <XFMail.20020711151259.shalehperry@attbi.com> <002a01c2292d$b42a1880$1615a8c0@mega> <003d01c22930$06f34350$1615a8c0@mega>
Message-ID: <20020713053503.GD22260@dman.ddts.net>

--rz+pwK2yUstbofK6
Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Jul 12, 2002 at 01:09:36AM +0200, Gregor Lingl wrote:

| > import urllib
| > def randombytes(n=3D128):
| >     urlstr=3D"http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?nbytes=3D"+=
str(n)
| >     t =3D urllib.urlopen(urlstr).read()
| >     start =3D t.find('<pre>')+5
| >     end   =3D t.find('</pre>')
| >     hexes =3D ''.join(t[start:end].split())
| >     bytes=3D[]
| >     for i in range(0,len(hexes),2):
| >         bytes.append(int(hexes[i:i+2], 16))
| >     return bytes
| >=20
|=20
| I think, of course, this could be done in two or three lines if
| one knew how to fetch binary data from the net - using this form
| of the url:
|=20
| http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?nbytes=3D128&fmt=3Dbin
|=20
| Can somebody explain how to accomplish this in Python?

Just make a proper HTTP request.  For example :

$ echo -e 'GET /cgi-bin/uncgi/Hotbits?nbytes=3D128&fmt=3Dbin HTTP/1.0\n\n' =
| netcat www.fourmilab.ch www
HTTP/1.1 200 OK
Date: Sat, 13 Jul 2002 05:20:13 GMT
Server: Apache/2.0.39 (Unix)
Pragma: no-cache
Connection: close
Content-Type: application/octet-stream

=C2A=BA=8AcT=E6$,=A6=E9(=10q&=D2=AA7=94=AB=CF=E8H=EFU=EAr=9ED=AC=D0=D5N`=BB=
,=EE=AB0=16=BC=EFty=10=F7:e=ADZ#Q=98c=A7=8E=84=8F=FB=C7%=96=F7=9D\=01=9AA#=
=AE(xx=D1W=87=0F=FB=F4=13=DES=93=BD=04=01J=E5=F4=15=060)=A2=8AP=EC=08=DF=14=
h=B0=B1q=94=B0=C0P=18F=F2=DA=DAE=1D=E9=01=D5=C1=03e9=CB=87=9B=FB=AB%


One solution would be to open a socket directly, send that line
(followed by a blank line), read the result and skip everything up to
and including the first blank line.  The remainder will be the data.
(of course, one could also use os.popen() and the command above, but
that isn't as fun ;-))

This could also be done with httplib (or maybe urllib), but I don't
have enough experience with it to right the code without RTFMing and
testing as I go.

HTH,
-D

--=20
=20
If anyone would come after me, he must deny himself and take up his
cross and follow me.  For whoever wants to save his life will lose it,
but whoever loses his life for me and for the gospel will save it.  What
good is it for a man to gain the whole world, yet forfeit his soul?  Or
what can a man give in exchange for his soul?
        Mark 8:34-37
=20
http://dman.ddts.net/~dman/


--rz+pwK2yUstbofK6
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0vvAcACgkQO8l8XBKTpRQXFACgtxz3c+xmzsDPtPb+fRGMOxw2
orcAoI6bbdxzp46Xy8R9/UIhCrcdw1tM
=lNmR
-----END PGP SIGNATURE-----

--rz+pwK2yUstbofK6--



From dman@dman.ddts.net  Sat Jul 13 06:37:00 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sat, 13 Jul 2002 00:37:00 -0500
Subject: [Tutor] Re: A question on randomness
In-Reply-To: <DNEFLBNHCGCPPIGNHGILCEAGCCAA.marta_andrea@libero.it>
References: <4.3.2.7.2.20020626114154.00b83100@pop3.norton.antivirus> <DNEFLBNHCGCPPIGNHGILCEAGCCAA.marta_andrea@libero.it>
Message-ID: <20020713053700.GE22260@dman.ddts.net>

--a+b56+3nqLzpiR9O
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, Jul 11, 2002 at 11:22:48PM +0200, Andrea Valle wrote:

| It' a couple of year I work with random generators.

| I know pseudo-random generation is a complex matter. Is there a way to
| "improve" it?

If you don't like python's builtin pseudo-random generator, you can
use the kernel's :

rand =3D open( "/dev/random" , "r" )
data =3D rand.read( 10 ) # just 10 bytes of random data
rand.close()

This works on linux; I don't know about other unices.

-D

--=20
=20
If we confess our sins, He is faithful and just and will forgive us our
sins and purify us from all unrighteousness.
        I John 1:9
=20
http://dman.ddts.net/~dman/


--a+b56+3nqLzpiR9O
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0vvHwACgkQO8l8XBKTpRRC4gCZAQsq3lDZ0o1fh8noJUXqgd1+
+hEAnj+fECntCM0KrXnIGPizjHwIEHS6
=FMxx
-----END PGP SIGNATURE-----

--a+b56+3nqLzpiR9O--



From dman@dman.ddts.net  Sat Jul 13 07:11:33 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sat, 13 Jul 2002 01:11:33 -0500
Subject: [Tutor] Re: event-based programming
In-Reply-To: <2E7466AE-9541-11D6-BB80-00039351FE6A@mac.com>
References: <2E7466AE-9541-11D6-BB80-00039351FE6A@mac.com>
Message-ID: <20020713061133.GF22260@dman.ddts.net>

--dWYAkE0V1FpFQHQ3
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, Jul 11, 2002 at 10:43:43PM -0400, Erik Price wrote:
| I was wondering if one (or more) of the helpful geniuses on this list=20
| could help me understand how event-based programming works.

| I'm hoping someone can give me a very high-level, theoretical=20
| explanation of how this works.

At the API level, you simply write your code.  You define
functions/methods that are the "handlers" for the events you are
interested in.  Then, as Sean described, you register your even
handler with the underlying system.

Eg for a button in a GUI application :

Note - this is not real code, but it gives the idea.
It is sort of a blend of the Java/Swing and GTK+ styles of
implementaiton since those are the toolkits I've written the most code
for, though not recently.  (actually, those are the only toolkits I've
written applications for.  The two xforms labs don't really count, and
I've only glanced at wxWindows)


    import gui_system   # This is the toolkit you are using.  It could be
                        # gtk, wx, tkinter, swing, or something else.  The
                        # implementations vary, but the concept is the
                        # same.
    class MyButton( gui_system.Button ) :

        # this is the handler
        def onClick( self , event ) :
            print "I was clicked!"
            print "The event data is:", str(event)

        def __init__( self ) :
            # initialize the object, and register the handler

            # the register() method is defined by the gui system in
            # the super class 'Button'
            self.register( self.onClick , gui_system.BUTTON_CLICK_EVENT )

    # make the button
    button1 =3D MyButton()

Now the system knows that whenever the button is clicked, you want to
know about it.  It notifies you by calling the method you told it to
call.  It also provides some data about the event, such as x/y
coordinates of the mouse at the time, whether or not modifier keys (eg
Ctrl or Alt) were pressed and things like that.

Your system works because the right methods are called when an event
is "fired".  The neat thing about event-driven programming is you
don't have to worry about the low-level details.  The code you write
only has to worry about what events are relevant to what it is
supposed to do, and how to handle those events.  The events
pseudo-magically arrive and the methods are called at the right time.



The underlying system is often implmented with a main "event loop"
that polls the user interface (keyboard, mouse) for data.  When data
is recieved, it decodes it to figure out what event it corresponds to.
For example, when you click your mouse, the gui toolkit figures out
which widget is at that location on the screen.  Then it looks up the
event handlers registered for that widget and that event and calls the
methods passing it the event object.  It is this underlying even loop
which prevents the program from exiting until the "exit" button is
pressed (and the button's click handler must call the right methods to
terminate the event loop or else the only way to quit is to kill -KILL
it).



On another related note, gui applications are often multi-threaded.
If they aren't, then the event loop is effectively blocked while the
event handler is running.  That prevents any additional events from
being handled.  Either they are lost or they are queued (depends on
the system).  Have you ever seen a gui app that simply didn't respond
to anything you did and didn't repaint the screen while it was
chugging away at something?  This is why.  A common solution is to
spawn a "worker" thread to do the work while the main thread goes back
to the event loop.  This is very common in java.

This leads to another problem, though.  What if the main thread (event
loop) and the worker thread both try to update some component of the
gui at the same time?  A race condition.  Then add modal dialogs to
the picture (modal dialogs are evil anyways).  One of the bugs I fixed
at my last job (involving java/swing) was a total lockup of the gui
under certain error conditions.  The problem was just that -- a worker
thread tried to display a modal dialog.  However, it happened that
that caused a deadlock in the system (without the dialog ever
finishing painting).  The solution was quite simple -- wrap the
dialog's creation in a "Runnable" object and queue it for execution in
the main thread.  Swing has some utility functions
(eg javax.swing.SwingUtils.invokeLater()) that allow you to pass a
java.lang.Runnable object which will be added to the end of the event
queue.  Then the event loop will run() that object (call its .run()
method) in the main thread.  For a toolkit like GTK+, you will need to
make your own "main thread" and provide a queue request mechanism.
(it is quite simple to do)

An additional reason all this is necessary is because most (all?) gui
toolkits are not written to be thread-safe.  That is, they don't
provide any internal locking or synchronization; meaning that they
assume they will only be accessed from a single thread.  This is done
because locking and synchronization adds both time and memory
overhead, and for some applications it isn't necessary.  In addition,
if you follow the guidelines I outlined above (as the swing utility
functions make it fairly easy to do), you can avoid the issues
altogether and not having the speed/memory overhead is a good thing.



To summarize, event-driven programming consists of defining functions
or methods that will be called when an event occurs.  How events are
detected and handled is an implementation detail of the underlying
system.  Suffice it to be "magic" that is well documented.
Event-driven programming (at least in GUIs) tends to be seen
hand-in-hand with parallel processing, and all the synchronization
issues that entails.

HTH,
-D

--=20
=20
A mouse is a device used to point at the xterm you want to type in.
  --Kim Alm, a.s.r
=20
http://dman.ddts.net/~dman/


--dWYAkE0V1FpFQHQ3
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0vxJUACgkQO8l8XBKTpRTb4QCbB7d2dz4GN8qTZkx/mQORdzDC
VPsAoJw2tVb/uP0l7ar+MVlozdfrfd9p
=GcPg
-----END PGP SIGNATURE-----

--dWYAkE0V1FpFQHQ3--



From dman@dman.ddts.net  Sat Jul 13 07:20:48 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sat, 13 Jul 2002 01:20:48 -0500
Subject: [Tutor] Re: CGI Question
In-Reply-To: <Pine.LNX.4.44.0207091212450.21583-100000@hkn.eecs.berkeley.edu>
References: <B9509E9C.93BD%sarmstrong13@mac.com> <Pine.LNX.4.44.0207091212450.21583-100000@hkn.eecs.berkeley.edu>
Message-ID: <20020713062048.GG22260@dman.ddts.net>

--df+09Je9rNq3P+GE
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 09, 2002 at 12:17:39PM -0700, Danny Yoo wrote:
| On Tue, 9 Jul 2002, SA wrote:
|=20
| > Ok. I 'hacked' at the code for awhile and have finally figured it out. =
For
| > anyone that wants to see the results, check my test program below:

[...]

| I'd recommend pulling this out of the inner loop altogether, and to
| relocate it to the beginning:
|=20
| ###
| print "Content-Type: text/plain\n\n"
| for pageID in QueryString.keys():
|     QValue =3D QueryString['pageID'].value
|     body =3D open(QValue, "r")
| ###

I would simplify it to the following, since this is the essence of
what that code is trying to do (and adds some error handling too) :

#!/sw/bin/python

import cgi
import cgitb
import sys

cgitb.enable(display=3D0, logdir=3D"/Users/montana/Temp")

print "Content-Type: text/plain\n\n"
QueryString =3D cgi.FieldStorage()
try :
    QValue =3D QueryString['pageID'].value
except KeyError :
    print "Error -- you didn't provide a 'pageID' argument"
    sys.exit( 0 )

try :
    body =3D open(QValue, "r")
except OSError , err :
    print "Couldn't open the file:"
    print str(err)
    sys.exit( 0 )

for line in body.readlines():
    print line


What I did, other than add some exception handling, was to remove the
loop entirely.  You didn't use the loop variable at all, you simply
looked for a single parameter.  The loop would have been useful if,
for example, you wanted to display each parameter in turn.

HTH,
-D

--=20
=20
Bugs come in through open windows. Keep Windows shut!
=20
http://dman.ddts.net/~dman/


--df+09Je9rNq3P+GE
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0vxsAACgkQO8l8XBKTpRSWpwCgwJOTeHV40dJl6a5MzwHg0mCk
L68An3309B1jtM2UV02NoKY7BtNW1z4l
=grAv
-----END PGP SIGNATURE-----

--df+09Je9rNq3P+GE--



From dman@dman.ddts.net  Sat Jul 13 07:34:12 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sat, 13 Jul 2002 01:34:12 -0500
Subject: [Tutor] Re: I need help slicing.
In-Reply-To: <B95497AE.986B%sarmstrong13@mac.com>
References: <3D2F2585.933A19E2@ccvcorp.com> <B95497AE.986B%sarmstrong13@mac.com>
Message-ID: <20020713063412.GH22260@dman.ddts.net>

--fd5uyaI9j6xoeUBo
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Jul 12, 2002 at 02:26:54PM -0500, SA wrote:
=20
| Yes. I thought about the os module. But all of the paths in the
| querystrings will be relative.

The os.path module works on relative paths as well.

| For example:
|=20
| http://localhost/cgi-bin/somepython.py?filename=3Ddocs/test.txt  or
| http://localhost/cgi-bin/somepython.py?filename=3Ddocs/test.html
|=20
| So what I want to prevent is someone doing the following:
|=20
| http://localhost/cgi-bin/somepython.py?filename=3D/etc/passwd

Good thinking.

| So my thought was either write the script to limit all filenames to
| files in this relative directory or to use splicing to verify the
| file extension.  Does this sound like a secure enough method?

You can do checks like the following :

1)  ensure every path begins with 'docs/'
2)  ensure that no path has '..' in it anywhere
3)  ensure that no path has any control characters -- eg
        .^H.
    (a dot followed by a backspace followed by a dot)
    (I think that BS will be included in the filename literally, but
     why mess with that stuff anyways)

There may be other potential exploits that I haven't thought of.


Some other possible solutions :

1)  Make a static list of allowed filenames.  Check the parameter that
    is passed against that list and reject it if it isn't in there.
    This means you need to update the list if you ever
    add/remove/rename any files.

2)  Get the directory listing.  Look to see if the filename you were
    passed is in that listing.  Use absolute, normalized, paths for
    everything.  Eg if someone passes ./././/.//////docs/test.txt it
    would be qualified and normalized to
    /home/me/public/html/docs/test.txt and match the entry in the
    list.

3)  Don't use a cgi script like that.  It is precisely for reasons
    like this that SSI (server-side includes) can be a security hole.
    If you let the users of your site use SSI, they can
    "#include /etc/passwd", and you really don't want that :-).

    Alternatives include
        Static directory listings.  This may not provide the fancy
            look you were striving for.
        A Content Management Framework, such as Zope where you would
            store all the accessible content in the framework, and
            also have templates and scripts to make the content look
            nice.  The content could be stored directly in the ZODB,
            or it could be in a SQL backend (eg postgresql), or you
            could use a Product like LocalFile to create pointers from
            inside the ZODB to files on disk.

            One of the main benefits here is that it is impossible for
            a user to access data not available in the framework, such
            as /etc/passwd.  The effect is rather similar to
            alternative #1, but it leverages other software rather
            than being a roll-your-own.  While something like zope
            might be overkill now, once you know how to work with the
            framework you might get ideas on how to provide better
            dynamic content in other areas as well.


HTH,
-D

--=20
=20
Do not be afraid of those who kill the body but cannot kill the soul.
Rather be afraid of the One who can destroy both soul and body in hell.
        Matthew 10:28
=20
http://dman.ddts.net/~dman/


--fd5uyaI9j6xoeUBo
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0vyeQACgkQO8l8XBKTpRRteACgwqjad9JaCfxw9eg3UcNjUwOX
Oz8AoKchuKjrk8yIp7Y3yCpdBvjImb8u
=GY0Q
-----END PGP SIGNATURE-----

--fd5uyaI9j6xoeUBo--



From erikprice@mac.com  Sat Jul 13 15:52:17 2002
From: erikprice@mac.com (Erik Price)
Date: Sat, 13 Jul 2002 10:52:17 -0400
Subject: [Tutor] Re: event-based programming
In-Reply-To: <20020713061133.GF22260@dman.ddts.net>
Message-ID: <2030C630-9670-11D6-9443-00039351FE6A@mac.com>

Sean & dman,

Thanks very much to both of you for addressing this question.  I now 
know two things about event programming:

1) In theory, event programming works by the event handler subscribing 
to a "service" which does the work of sending events to the handler.
2) Most of the time, the details of how this happens is tucked away in 
low-level code that the average programmer doesn't have to worry about.

Although I really wanted to know "what is going on", so the first answer 
was very helpful, the second one assures me that, as with JavaScript 
event handling in a browser, the programmer doesn't have to worry -too- 
much about the mechanics of event programming.  Just write the event 
handler, register it somehow (though this seems to be done for you in 
JS), and then write the code that submits the event (also something the 
browser does for you in JS).

Of course, this leads to further questions, naturally.

On Saturday, July 13, 2002, at 02:11  AM, Derrick 'dman' Hudson wrote:

> Note - this is not real code, but it gives the idea.
> It is sort of a blend of the Java/Swing and GTK+ styles of
> implementaiton since those are the toolkits I've written the most code
> for, though not recently.  (actually, those are the only toolkits I've
> written applications for.  The two xforms labs don't really count, and
> I've only glanced at wxWindows)

I did not see a Swing library in my module directory.  Is this a 
standard offering with Python 2.2?

> This leads to another problem, though.  What if the main thread (event
> loop) and the worker thread both try to update some component of the
> gui at the same time?  A race condition.  Then add modal dialogs to
> the picture (modal dialogs are evil anyways).  One of the bugs I fixed
> at my last job (involving java/swing) was a total lockup of the gui
> under certain error conditions.  The problem was just that -- a worker
> thread tried to display a modal dialog.  However, it happened that
> that caused a deadlock in the system (without the dialog ever
> finishing painting).  The solution was quite simple -- wrap the
> dialog's creation in a "Runnable" object and queue it for execution in
> the main thread.  Swing has some utility functions
> (eg javax.swing.SwingUtils.invokeLater()) that allow you to pass a
> java.lang.Runnable object which will be added to the end of the event
> queue.  Then the event loop will run() that object (call its .run()
> method) in the main thread.

I'm sorry, but this is confusing to me.  Although I'm not sure exactly 
what a modal dialog is, I follow what you are saying -- but I don't 
understand how the modal dialog locked up the gui.  By putting the 
dialog's cretaion into a "Runnable" app, I am assuming that this means 
you coded it to be performed within a separate thread (perhaps this is 
what you were talking about by "spawning a 'worker' thread"?).  But what 
I am unsure of is what is wrong with having the dialog just come up (the 
way you had it originally).  This is very interesting to me, learning 
about this topic.

> An additional reason all this is necessary is because most (all?) gui
> toolkits are not written to be thread-safe.  That is, they don't
> provide any internal locking or synchronization; meaning that they
> assume they will only be accessed from a single thread.  This is done
> because locking and synchronization adds both time and memory
> overhead, and for some applications it isn't necessary.  In addition,
> if you follow the guidelines I outlined above (as the swing utility
> functions make it fairly easy to do), you can avoid the issues
> altogether and not having the speed/memory overhead is a good thing.

You mean by putting the code into a new "Runnable" instance?  I have not 
yet learned about the "Runnable" object yet.

> To summarize, event-driven programming consists of defining functions
> or methods that will be called when an event occurs.  How events are
> detected and handled is an implementation detail of the underlying
> system.  Suffice it to be "magic" that is well documented.
> Event-driven programming (at least in GUIs) tends to be seen
> hand-in-hand with parallel processing, and all the synchronization
> issues that entails.

That is reassuring for now, though perhaps someday I should look into 
that implementation and see how it works.  Not at this early stage, 
though.

I have one last unrelated question.  You (and many other sages on this 
list) have experience with Java.  I must admit that, while I really like 
Python, I am trying to learn Java too.  Is there an equivalent 
"tutor"-style list or forum for Java programming?  I have not found it, 
despite everywhere I look people are saying that the Java programming 
language has a large user base and support community.

Thank you very much,


Erik




From shalehperry@attbi.com  Sat Jul 13 17:58:36 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sat, 13 Jul 2002 09:58:36 -0700 (PDT)
Subject: [Tutor] Re: event-based programming
In-Reply-To: <2030C630-9670-11D6-9443-00039351FE6A@mac.com>
Message-ID: <XFMail.20020713095836.shalehperry@attbi.com>

On 13-Jul-2002 Erik Price wrote:
> 
> Sean & dman,
> 
> Thanks very much to both of you for addressing this question.  I now 
> know two things about event programming:
> 

glad to help

> Although I really wanted to know "what is going on", so the first answer 
> was very helpful, the second one assures me that, as with JavaScript 
> event handling in a browser, the programmer doesn't have to worry -too- 
> much about the mechanics of event programming.  Just write the event 
> handler, register it somehow (though this seems to be done for you in 
> JS), and then write the code that submits the event (also something the 
> browser does for you in JS).
> 
> Of course, this leads to further questions, naturally.
> 
> On Saturday, July 13, 2002, at 02:11  AM, Derrick 'dman' Hudson wrote:
> 
>> Note - this is not real code, but it gives the idea.
>> It is sort of a blend of the Java/Swing and GTK+ styles of
>> implementaiton since those are the toolkits I've written the most code
>> for, though not recently.  (actually, those are the only toolkits I've
>> written applications for.  The two xforms labs don't really count, and
>> I've only glanced at wxWindows)
> 
> I did not see a Swing library in my module directory.  Is this a 
> standard offering with Python 2.2?
> 

Swing is a GUI library for Java.

>> This leads to another problem, though.  What if the main thread (event
>> loop) and the worker thread both try to update some component of the
>> gui at the same time?  A race condition.  Then add modal dialogs to
>> the picture (modal dialogs are evil anyways).  One of the bugs I fixed
>> at my last job (involving java/swing) was a total lockup of the gui
>> under certain error conditions.  The problem was just that -- a worker
>> thread tried to display a modal dialog.  However, it happened that
>> that caused a deadlock in the system (without the dialog ever
>> finishing painting).  The solution was quite simple -- wrap the
>> dialog's creation in a "Runnable" object and queue it for execution in
>> the main thread.  Swing has some utility functions
>> (eg javax.swing.SwingUtils.invokeLater()) that allow you to pass a
>> java.lang.Runnable object which will be added to the end of the event
>> queue.  Then the event loop will run() that object (call its .run()
>> method) in the main thread.
> 
> I'm sorry, but this is confusing to me.  Although I'm not sure exactly 
> what a modal dialog is, I follow what you are saying -- but I don't 
> understand how the modal dialog locked up the gui.  By putting the 
> dialog's cretaion into a "Runnable" app, I am assuming that this means 
> you coded it to be performed within a separate thread (perhaps this is 
> what you were talking about by "spawning a 'worker' thread"?).  But what 
> I am unsure of is what is wrong with having the dialog just come up (the 
> way you had it originally).  This is very interesting to me, learning 
> about this topic.
> 

goes like this, the application has a loop:

while not time_to_exit:
  if check_for_event():
    handle_event()
  else:
    process other stimuli

when the application is in handle_event() NOTHING else is happening.  The modal
dialog dman mentions would cause this to happen.  handle_event will set the
time_to_exit flag is a close/exit event occurs or for some other condition.

And to help out, a modal window is one marked "you can do nothing else in this
application until finish with me".  Generally they are a bad idea.

>> An additional reason all this is necessary is because most (all?) gui
>> toolkits are not written to be thread-safe.  That is, they don't
>> provide any internal locking or synchronization; meaning that they
>> assume they will only be accessed from a single thread.  This is done
>> because locking and synchronization adds both time and memory
>> overhead, and for some applications it isn't necessary.  In addition,
>> if you follow the guidelines I outlined above (as the swing utility
>> functions make it fairly easy to do), you can avoid the issues
>> altogether and not having the speed/memory overhead is a good thing.
> 
> You mean by putting the code into a new "Runnable" instance?  I have not 
> yet learned about the "Runnable" object yet.
> 

dman is again babeling about Java.  As i understand it, Runnable is essentially
an object which queues itself and when the time is right a slice of the
program's time is given to it.

>> To summarize, event-driven programming consists of defining functions
>> or methods that will be called when an event occurs.  How events are
>> detected and handled is an implementation detail of the underlying
>> system.  Suffice it to be "magic" that is well documented.
>> Event-driven programming (at least in GUIs) tends to be seen
>> hand-in-hand with parallel processing, and all the synchronization
>> issues that entails.
> 
> That is reassuring for now, though perhaps someday I should look into 
> that implementation and see how it works.  Not at this early stage, 
> though.
> 

one of the pitfalls I tried to point out in my first mail is that events are
ASYNCHRONOUS and as dman points out, parallel.

You may be expecting:

expose
configure
move
resize

but get

configure
resize
move
expose

or any other combination.  You must write you code in a style which allows
paths in from various directions.  This often means using global variables or
the OO equivalent.

You also do not know WHEN the application (or sender) will get to your events
and vice versa.  How long has it been since this move event was sent?  Is this
network request still applicable?




From neutron878@cayuse.net  Sat Jul 13 18:50:36 2002
From: neutron878@cayuse.net (Ricardo Ortega)
Date: Sat, 13 Jul 2002 13:50:36 -0400
Subject: [Tutor] Printing in a windows machine
Message-ID: <000d01c22a95$cebaaf70$0101a8c0@PALAMINO>

This is a multi-part message in MIME format.

------=_NextPart_000_000A_01C22A74.43FBE5F0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hi everyone. I am writing an application that queries an MySQL database =
and returns the results. The gui is  made in QT. What I need to know is =
how to print that to a windows printer as a nicley formatted report. QT =
has QPrinter but have no idea how to use it. does anyone have any =
examples as to how to use QPrinter or any aother way of printing. Thanks =
in advance.

------=_NextPart_000_000A_01C22A74.43FBE5F0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2600.0" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hi everyone. I am writing an =
application that=20
queries an MySQL database and returns the results. The gui is &nbsp;made =
in QT.=20
What I need to know is how to print that to a windows printer as a =
nicley=20
formatted report. QT has QPrinter but have no idea how to use it. does =
anyone=20
have any examples as to how to use QPrinter or any aother way of =
printing.=20
Thanks in advance.</FONT></DIV></BODY></HTML>

------=_NextPart_000_000A_01C22A74.43FBE5F0--




From dman@dman.ddts.net  Sat Jul 13 19:58:33 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sat, 13 Jul 2002 13:58:33 -0500
Subject: [Tutor] Re: event-based programming
In-Reply-To: <XFMail.20020713095836.shalehperry@attbi.com>
References: <2030C630-9670-11D6-9443-00039351FE6A@mac.com> <XFMail.20020713095836.shalehperry@attbi.com>
Message-ID: <20020713185833.GA29597@dman.ddts.net>

--liOOAslEiF7prFVr
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable


Forewarning:
    The below text is rather heavily sprinkled with Java and also has
    some general GUI and multi-threaded programming concepts.

| On 13-Jul-2002 Erik Price wrote:
| > On Saturday, July 13, 2002, at 02:11  AM, Derrick 'dman' Hudson wrote:
| >=20
| >> Note - this is not real code, but it gives the idea.
| >> It is sort of a blend of the Java/Swing and GTK+ styles of
| >> implementaiton since those are the toolkits I've written the most code
| >> for, though not recently.  (actually, those are the only toolkits I've
| >> written applications for.  The two xforms labs don't really count, and
| >> I've only glanced at wxWindows)
| >=20
| > I did not see a Swing library in my module directory.  Is this a=20
| > standard offering with Python 2.2?
|=20
| Swing is a GUI library for Java.

If you want to use it from python, you can use the 'jython'
interpreter implementation (with all the other side-effects that has).

| >> This leads to another problem, though.  What if the main thread (event
| >> loop) and the worker thread both try to update some component of the
| >> gui at the same time?  A race condition.  Then add modal dialogs to
| >> the picture (modal dialogs are evil anyways).  One of the bugs I fixed
| >> at my last job (involving java/swing) was a total lockup of the gui
| >> under certain error conditions.  The problem was just that -- a worker
| >> thread tried to display a modal dialog.  However, it happened that
| >> that caused a deadlock in the system (without the dialog ever
| >> finishing painting).  The solution was quite simple -- wrap the
| >> dialog's creation in a "Runnable" object and queue it for execution in
| >> the main thread.  Swing has some utility functions
| >> (eg javax.swing.SwingUtils.invokeLater()) that allow you to pass a
| >> java.lang.Runnable object which will be added to the end of the event
| >> queue.  Then the event loop will run() that object (call its .run()
| >> method) in the main thread.
| >=20
| > I'm sorry, but this is confusing to me.  Although I'm not sure exactly=
=20
| > what a modal dialog is, I follow what you are saying -- but I don't=20
| > understand how the modal dialog locked up the gui.

To understand how it locked the gui you need to know what "modal"
means for a dialog.  Continue reading.

| And to help out, a modal window is one marked "you can do nothing
| else in this application until finish with me".  Generally they are
| a bad idea.

The reasons modal dialogs are bad are twofold :

1)  The user get really really (really) annoyed when he must cancel
    the unfinished operation in one dialog just to move the other
    window, or to click some other button first (because he forgot
    before opening the dialog), or to copy some information from the
    main window rather than re-typing it.

    Except in exceptional circumstances, they belong as part of the
    "UI Hall of Shame".  (not surprisingly, modal dialogs are mostly
    found in windows, and windows is quite full of modal dialogs)

    An example of an exceptional circumstance can be found in gvim.
    Suppose you have a file loaded in a buffer.  You make some changes
    in the buffer, but don't save it to disk yet.  In a separate
    window (maybe even a separate app) the file on disk is changed.
    gvim pops up a modal dialog that says "the file has changed on
    disk".  It has an "Ok" button to leave the buffer alone, and a
    "Load" button to discard the current buffer and (re)load the file
    from disk.  In this case, there really isn't anything sensible you
    can do in vim until it knows what to do about that external
    conflict.  (the curses version of vim displays the message and a
    command prompt, which must be answered before any other operations
    can be performed)

2)  It is tricky to ensure that your application doesn't create a
    deadlock for itself by attempting to display 2 (or more) modal
    dialogs at the same time (particularly alerts from long-running
    worker threads).  If you do try to display more than one, which
    one belongs on top?  Which one (should) get priority?

| > By putting the dialog's cretaion into a "Runnable" app, I am
| > assuming that this means you coded it to be performed within a
| > separate thread

Actually, the worker thread told the main event thread that it wanted
the operation to be performed.  I put the creation back in the main
thread because Swing, like all other GUI toolkits I am familiar with,
is not thread-safe.

If the dialog that was created wasn't modal, then it is possible that
the application would have continued running despite the data
corruption from not properly synchronizing the operations.  However,
since it was modal it prevented any other events from being handled.

| > But what I am unsure of is what is wrong with having the dialog
| > just come up (the way you had it originally).  This is very
| > interesting to me, learning about this topic.

Since the dialog was displayed from a worker thread, it so happened
that it corrupted some global data in the swing library (because the
lib isn't thread-safe).  Since the dialog was modal, no other events
could be processed until the user clicked "ok" in the dialog.
However, they couldn't click "ok" because the dialog hadn't been fully
painted due to race conditions and data corruption.


| > (perhaps this is what you were talking about by "spawning a
| > 'worker' thread"?).

As I (and shaleh) mentioned, the event loop is blocked while your
event handler is running.  It processes events in serial.  So suppose
your application is a web browser.  The user clicks "go" to load a
page.  Now you need to go and load the page, but that may take a long
time.  If you don't spawn a "worker" thread to handle the network,
etc, work, then the whole gui will be "locked" until the page is
loaded.  That is a very bad thing.  The user will be unable to cancel
the operation or do anything else with your application while the page
is being loaded.  In addition, if they move some other window over the
top of yours and then re-expose your app, your app will not repaint
the screen because the event loop is blocked.

The solution is to do the real work of the application outside of the
main event loop; in another thread.  Hence the term "worker thread"
since the thread does the real work while the "main" thread just
dispatches the events.  The worker thread will then die after it has
done its work.

| >> An additional reason all this is necessary is because most (all?) gui
| >> toolkits are not written to be thread-safe.  That is, they don't
| >> provide any internal locking or synchronization; meaning that they
| >> assume they will only be accessed from a single thread.  This is done
| >> because locking and synchronization adds both time and memory
| >> overhead, and for some applications it isn't necessary.  In addition,
| >> if you follow the guidelines I outlined above (as the swing utility
| >> functions make it fairly easy to do), you can avoid the issues
| >> altogether and not having the speed/memory overhead is a good thing.
| >=20
| > You mean by putting the code into a new "Runnable" instance?  I have no=
t=20
| > yet learned about the "Runnable" object yet.
|=20
| dman is again babeling about Java.

Guilty as charged, as far as the names go.

| As i understand it, Runnable is essentially an object which queues
| itself and when the time is right a slice of the program's time is
| given to it.

Have I ever mentioned that I hate Java?  :-)  Java does not consider
methods to be objects, nor does it have the concept (as in C) of a
"function pointer".  The only thing you can work with in java are
class instances.  To work around this (bad, IMO) limitation, the
standard library has an interface java.lang.Runnable.  It looks like
this :

public interface Runnable { public void run() ; }

Essentially it is the same as a function in python, or a class
instance that defines __call__.  It is merely a way of grouping a
bunch of executable statements together and passing them around as an
object.

In python (eg using jython) you would write this :

    # in your event handler
    gui_component =3D ...  # whatever you need to do to get a reference to
                         # the right component of your gui interface
    def bunch_of_statements() :
        # some operation on the component that *must* be performed from
        # the main AWTEventQueue thread
        gui_component.repaint()
    SwingUtilities.invokeLater( bunch_of_statements )

Just as the last statement seems to read, the main event thread will
invoke your function later.

In java you would write that as this :

    // in your event handler
    gui_component =3D ...  // whatever you need to do to get a reference to
                         // the right component of your gui interface

    SwingUtilities.invokeLater( new Runnable()
        {
            public void run()
            {
                // some operation on the component that *must* be
                // performed from the main AWTEventQueue thread
                gui_component.repaint() ;
            } } ) ;

Yes it is ugly.  Yes it is long-winded.  It is Java.  (I have
mentioned before that I dislike java :-))

If you don't understand this yet, glance over the docs on "anonymous
inner classes".  I created a subclass of Runnable (without naming it)
that overrides/defines the run() method.  I then created an instance
of the class (I only need one.  In fact, a simple function would
suffice, but java isn't python).  I pass that object to the util
method to be queued.

Somewhere inside the bowels of swing, there is some code that
resembles this :
    operation =3D the_queue.next() ;
    operation.run() ;  // here is where the Runnable object is run

If it was implemented in python, the second line would simply be
    run()
and use the standard built-in "callable" interface.

| I have one last unrelated question.  You (and many other sages on this
| list) have experience with Java.  I must admit that, while I really like
| Python, I am trying to learn Java too.  Is there an equivalent
| "tutor"-style list or forum for Java programming?  I have not found it,
| despite everywhere I look people are saying that the Java programming
| language has a large user base and support community.

My experience with java first comes from school.  One of the classes I
took (Design Patterns) used it as the implementation language for
demonstrating that we understood the concepts.  The next thing that
happened to me was I got a co-op job at a java shop.  I knew Eiffel
and C++ at the time (though now I know how little I actually knew of
them) and had that little experience with java.  Through my work there
I became quite familiar with many of the ins and outs of java and with
multi-threaded programming (I hadn't done multithreaded before, though
I had made a GTK-based gui app in C++).  Since then, every class I've
had has been java-based.  The CS and SE departments at my school have
really been pushing java (and dropped eiffel as the introduction
language) in the last few years.

As a result, unlike with python (which I learned from the web), I
don't know of any good resources on the web for learning java.  You
can learn the library by browsing the javadoc docs, but that won't
teach you the language.

As I've mentioned before, while Java is a significant improvement over
C++, it is still far behind Python.

As for the large user base, it is there.  However much of it is tied
up in schools, businesses and other non-Open/Free groups.  (sometimes
great OSS software comes from schools, but the rest of it is just
teaching types of projects in which the students must do all the work
on their own)

If you go job hunting, you'll find a lot more places that mention
    .   java
    .   c++
    .   windows
    .   VB
or some combination than you will places advertising python or unix
related positions.

(maybe those tools require a much larger support staff.  LOL! :-))

HTH,
-D

--=20
The fear of the Lord leads to life:
Then one rests content, untouched by trouble.
        Proverbs 19:23
=20
http://dman.ddts.net/~dman/

--liOOAslEiF7prFVr
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0weFkACgkQO8l8XBKTpRQT+gCfR3fYB7ytHhd5OIkY/R87XNAs
3pEAmQF/iRpPIMHCrHfhwFhU79Uu860n
=5e6x
-----END PGP SIGNATURE-----

--liOOAslEiF7prFVr--



From jparlar@cogeco.ca  Sat Jul 13 20:54:47 2002
From: jparlar@cogeco.ca (Jay Parlar)
Date: Sat, 13 Jul 2002 15:54:47 -0400
Subject: [Tutor] Read a dictionary from a text file
Message-ID: <FC6ZHFTPXU09IE1TTQ6Z5Y2VKGOTEC.3d308587@Enzo>

I'm currently working on some simple SNMP testing procedures from Python. One of the most 
important things is the ability to parse a MIB (If you're lost as to what these mean, don't 
worry, they don't really affect the problem.) 

Anyway, I'm using the libsmi package to parse the MIB into a python dictionary 
representation of a text file. My question is, how can I read in a text file, and have it 
converted to a string? The text file would look something like this

{
	"key1" :
		{"subkey1" : "subval1" },
	"key2" ... yadayadayada
}

So the whole file looks like a Python dictionary, but of course, I can't read it in directly 
because it will come in as a string.

Looking through Google Groups, I found a similar question from 1995, but it doesn't seem to 
work on anything too complicated. My dictionary contains multiple levels of dictionaries 
with list and strings and all sorts of fun things embedded.

Any help anyone?






From glingl@aon.at  Sat Jul 13 21:40:57 2002
From: glingl@aon.at (Gregor Lingl)
Date: Sat, 13 Jul 2002 22:40:57 +0200
Subject: [Tutor] Re: event-based programming
References: <2030C630-9670-11D6-9443-00039351FE6A@mac.com> <XFMail.20020713095836.shalehperry@attbi.com> <20020713185833.GA29597@dman.ddts.net>
Message-ID: <003101c22aad$97a3fa10$1615a8c0@mega>

----- Original Message ----- 
From: "Derrick 'dman' Hudson" <dman@dman.ddts.net>
To: <tutor@python.org>
Sent: Saturday, July 13, 2002 8:58 PM
Subject: [Tutor] Re: event-based programming

dman wrote:
...
> As a result, unlike with python (which I learned from the web), I
> don't know of any good resources on the web for learning java.  You
> can learn the library by browsing the javadoc docs, but that won't
> teach you the language.
...

Besides "How to Think Lika a Computer Scientist" - Java Version -, which 
only could serve as a first Intro, there is at least Bruce Eckels
free electronic book: Thinking in Java, 2nd edition at

http://www.mindview.net/Books/TIJ/

which certainly has to be considered a "good resource".

Gregor

( ... and there are certainly a lot more ... )


 






From idiot1@netzero.net  Sun Jul 14 04:13:37 2002
From: idiot1@netzero.net (Kirk Bailey)
Date: Sat, 13 Jul 2002 23:13:37 -0400
Subject: [Tutor] TEST
Message-ID: <3D30EC61.7F7A35D5@netzero.net>

IS THIS THING PROCESSING MESSAGES OK?

-- 

end

Respectfully,
             Kirk D Bailey


+---------------------"Thou Art Free." -Eris-----------------------+
| http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
| http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
+------------------Thinking| NORMAL |Thinking----------------------+
                           +--------+
-------------------------------------------
Introducing NetZero Long Distance
Unlimited Long Distance only $29.95/ month!
Sign Up Today! www.netzerolongdistance.com



From phil@xfr.co.uk  Sun Jul 14 10:07:29 2002
From: phil@xfr.co.uk (Philip Kilner)
Date: Sun, 14 Jul 2002 10:07:29 +0100
Subject: [Tutor] TEST
In-Reply-To: <3D30EC61.7F7A35D5@netzero.net>
References: <3D30EC61.7F7A35D5@netzero.net>
Message-ID: <VA.0000079f.095dbaa3@xfr.co.uk>

Kirk,

In article <3D30EC61.7F7A35D5@netzero.net>, Kirk Bailey wrote:
> IS THIS THING PROCESSING MESSAGES OK?
>

<delurk>

Not sure if you were looking for confirmation, but it looks like it is!

</delurk>

Regards,

PhilK






From emil@lysator.liu.se  Sun Jul 14 14:40:35 2002
From: emil@lysator.liu.se (Emil Styrke)
Date: 14 Jul 2002 15:40:35 +0200
Subject: [Tutor] Read a dictionary from a text file
In-Reply-To: <FC6ZHFTPXU09IE1TTQ6Z5Y2VKGOTEC.3d308587@Enzo>
References: <FC6ZHFTPXU09IE1TTQ6Z5Y2VKGOTEC.3d308587@Enzo>
Message-ID: <87sn2mh1gs.fsf@i110.ryd.student.liu.se>

Jay Parlar <jparlar@cogeco.ca> writes:

> I'm currently working on some simple SNMP testing procedures from Python. One of the most 
> important things is the ability to parse a MIB (If you're lost as to what these mean, don't 
> worry, they don't really affect the problem.) 
> 
> Anyway, I'm using the libsmi package to parse the MIB into a python dictionary 
> representation of a text file. My question is, how can I read in a text file, and have it 
> converted to a string? The text file would look something like this
> 
> {
> 	"key1" :
> 		{"subkey1" : "subval1" },
> 	"key2" ... yadayadayada
> }
> 
> So the whole file looks like a Python dictionary, but of course, I can't read it in directly 
> because it will come in as a string.
> 
> Looking through Google Groups, I found a similar question from 1995, but it doesn't seem to 
> work on anything too complicated. My dictionary contains multiple levels of dictionaries 
> with list and strings and all sorts of fun things embedded.
> 
> Any help anyone?

You could use eval to execute a string containing a python expression, like this:

>>> dict = eval('{"key1": {"subkey1": "subval1"}, "key2": "val2"}')
>>> dict
{'key1': {'subkey1': 'subval1'}, 'key2': 'val2'}
>>>

So, to convert your file to a dictionary, you can do:

>>> dict = eval(open("yourfile.txt").read())

However, this is a little dangerous.  If someone can change the
contents of your file, they can make the python interpreter execute
arbitrary code on your system.  For example, if yourfile.txt looks
like this:

  os.system("rm -rf ~")

then the python interpreter will execute exactly that. (At least if
the os module is loaded)

        /Emil




From Belanm@lasalle.navy.mil  Sun Jul 14 16:08:09 2002
From: Belanm@lasalle.navy.mil (Belan, Martin ET3 (AGF-3))
Date: Sun, 14 Jul 2002 17:08:09 +0200
Subject: [Tutor] Sending email in Python...
Message-ID: <FA9060A56B68D511947F00A024B2D40001952162@agf3uex01.lasalle.navy.mil>

    I was wondering how one would go about sending an email using python.  I
am currently running python 2.2 under a Windows NT OS, which utilizes a
proxy server.  If anyone out there could aid my quest until I am able to
procure some decent documentation I would be much obliged.  Thanks.
 
Martin



From dman@dman.ddts.net  Sun Jul 14 20:39:10 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sun, 14 Jul 2002 14:39:10 -0500
Subject: [Tutor] Re: Read a dictionary from a text file
In-Reply-To: <FC6ZHFTPXU09IE1TTQ6Z5Y2VKGOTEC.3d308587@Enzo>
References: <FC6ZHFTPXU09IE1TTQ6Z5Y2VKGOTEC.3d308587@Enzo>
Message-ID: <20020714193910.GA11398@dman.ddts.net>

--EeQfGwPcQSOJBaQU
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sat, Jul 13, 2002 at 03:54:47PM -0400, Jay Parlar wrote:
[persistently store data (an object) in a file]

There are several ways of going about this.  One possiblity has been
mentioned, which is to use eval() to leverage the existing python
parser to parse the text for you.  He also describes the potential it
has to cause majore problems on your system.

Another possiblity is to define (or use a existing) structure in your
file and write (or hook in an existing) parser for it.  For example,
you could use XML in the file to store the data, and use the existing
XML parsers to load it.  Then your code will convert from the DOM that
the XML parser gave you into a python dict.  This would not be very
hard, although the file would look drastically different.

Another option is to use the 'pickle' module to serialze an in-memory
python dict to a file, and then do the same thing in reverse next time
you load it.  This requires that the data initially be in the python
program, rather than using your editor to create the file.

The last thing that comes to mind right now is another way of
leveraging the python parser.  You change the file slightly to look
like
    the_data =3D { ..... }
instead of just
    { ..... }
Then you import the file, or use execfile(), to load the file using
the python interpreter.  Then just extract the named dictionary like
you would for any module.  This has the advantage of not using eval(),
but still allows someone to put
    import os
    os.system( 'rm -fr ~' )
in the file.

HTH,
-D

--=20
He who spares the rod hates his son,
but he who loves him is careful to discipline him.
        Proverbs 13:24
=20
http://dman.ddts.net/~dman/

--EeQfGwPcQSOJBaQU
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0x014ACgkQO8l8XBKTpRSy1ACgrNwXdMWWDd0UHZ0E/AE6LFqC
gzkAn2XfVQPN1Rs7S50wXTk2HZ21pwCA
=BkIT
-----END PGP SIGNATURE-----

--EeQfGwPcQSOJBaQU--



From sarmstrong13@mac.com  Sun Jul 14 23:09:01 2002
From: sarmstrong13@mac.com (SA)
Date: Sun, 14 Jul 2002 17:09:01 -0500
Subject: [Tutor] Tkinter help.
Message-ID: <B95760AD.98F2%sarmstrong13@mac.com>

I have the following python test script:

import Tkinter
from Tkconstants import *
tk = Tkinter.Tk()
frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
frame.pack(fill=BOTH,expand=1)
label = Tkinter.Label(frame, text="Hello, World")
label.pack(fill=X, expand=1)
button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
button.pack(side=BOTTOM)
tk.mainloop()

When I run it on my Mac using the Python and Tcl frameworks for MacOSX I get
the correct widget to show up, but when I click the "Exit" button freaky
stuff begins to happen. From the command line interpreter I get:

SetFrontProcess failed,-600
SetFrontProcess failed,-600
SetFrontProcess failed,-600
SetFrontProcess failed,-600
SetFrontProcess failed,-600
SetFrontProcess failed,-600

I then hit ctrl-C to interrupt and get the following:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "tktest.py", line 11, in ?
    tk.mainloop()
  File 
"/Library/Frameworks/Python.framework/Versions/2.2/lib/python2.2/lib-tk/Tkin
ter.py", line 929, in mainloop
    self.tk.mainloop(n)
KeyboardInterrupt

Now if I turn on Xdarwin and run this same program in X on the same system
using the default Python and Tcl libraries for X, everything runs OK. So I
have to assume something is wrong with the Tcl/Tk frameworks for MacOSX.

Anyone have a clue what the problem is?

Thanks.
SA





From dominic.fox" <dominic.fox@ntlworld.com  Sun Jul 14 23:36:29 2002
From: dominic.fox" <dominic.fox@ntlworld.com (dominic.fox)
Date: Sun, 14 Jul 2002 23:36:29 +0100
Subject: [Tutor] Tkinter not my friend any more
References: <20020714134401.31314.7043.Mailman@mail.python.org>
Message-ID: <000b01c22b86$e58e1060$d0d5ff3e@tinypc>

Hi all,

I'm having trouble getting Tkinter to do what I want it to do, and I think
the reason is that Tkinter just isn't designed to do that thing. Basically I
want an image buffer in a window on the screen that I can read and write to,
plotting graphics primitives or even altering its contents pixel-by-pixel.
I'd like to do something along the lines of the standard
double-buffering/animation tutorial that I've seen in more than one Java
book. However, an assumption of Tkinter is that any bitmaps you want are
going to be in a file somewhere - there doesn't seem to be a way to create a
"blank" one and then do things to its contents. PIL will let you do that,
but you have to convert the PIL Image object to an ImageTk bitmap image or
photo image which is then not dynamically rewriteable...

I'm aware that Tkinter has it's own quite groovy way of letting you draw
graphics primitives into a window, where you add to a collection of objects
which Tkinter itself takes responsibility for rendering and refreshing, but
that's no use if what you actually want to do is plot Mandelbrot sets (for
instance). Ideally I'd prefer to do things the Java way, by having a canvas
object which supplies a graphics context for use by various rendering
objects and raises events when parts of it need to be refreshed - it's more
low-level, but more powerful for just that reason. Can this absolutely not
be done in Tkinter? Can it be done at all in, say, wxWindows?

Dominic




From rob@uselesspython.com  Sun Jul 14 23:41:47 2002
From: rob@uselesspython.com (Rob)
Date: Sun, 14 Jul 2002 17:41:47 -0500
Subject: [Tutor] Tkinter not my friend any more
In-Reply-To: <000b01c22b86$e58e1060$d0d5ff3e@tinypc>
Message-ID: <MPEOIFCOPCIHEDCLBLPBKEBFCAAA.rob@uselesspython.com>

Since you like the Java way of doing this sort of thing, how about the use
of Jython/Swing or something similar?

Rob
http://uselesspython.com

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
dominic.fox
Sent: Sunday, July 14, 2002 5:36 PM
To: tutor@python.org
Subject: [Tutor] Tkinter not my friend any more


Hi all,

I'm having trouble getting Tkinter to do what I want it to do, and I think
the reason is that Tkinter just isn't designed to do that thing. Basically I
want an image buffer in a window on the screen that I can read and write to,
plotting graphics primitives or even altering its contents pixel-by-pixel.
I'd like to do something along the lines of the standard
double-buffering/animation tutorial that I've seen in more than one Java
book. However, an assumption of Tkinter is that any bitmaps you want are
going to be in a file somewhere - there doesn't seem to be a way to create a
"blank" one and then do things to its contents. PIL will let you do that,
but you have to convert the PIL Image object to an ImageTk bitmap image or
photo image which is then not dynamically rewriteable...

I'm aware that Tkinter has it's own quite groovy way of letting you draw
graphics primitives into a window, where you add to a collection of objects
which Tkinter itself takes responsibility for rendering and refreshing, but
that's no use if what you actually want to do is plot Mandelbrot sets (for
instance). Ideally I'd prefer to do things the Java way, by having a canvas
object which supplies a graphics context for use by various rendering
objects and raises events when parts of it need to be refreshed - it's more
low-level, but more powerful for just that reason. Can this absolutely not
be done in Tkinter? Can it be done at all in, say, wxWindows?

Dominic



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





From pythonpython@hotmail.com  Mon Jul 15 03:30:34 2002
From: pythonpython@hotmail.com (Hy Python)
Date: Mon, 15 Jul 2002 02:30:34 +0000
Subject: [Tutor] Convert CJK text into HEX value string
Message-ID: <F99jarXIEfeiyFlBcPP00012c0e@hotmail.com>

Does anyone know how to Convert CJK(Chinese/Japanese/Korean) text into HEX 
value string?
I need to pass CJK Text via POST/GET cgi method. I need to convert the text 
into a string of HEX values like "%BE%DF".

Thanks a lot for your help.

Hy

_________________________________________________________________
Join the world’s largest e-mail service with MSN Hotmail. 
http://www.hotmail.com




From joel@prettyhipprogramming.com  Mon Jul 15 04:23:26 2002
From: joel@prettyhipprogramming.com (Joel Ricker)
Date: Sun, 14 Jul 2002 23:23:26 -0400
Subject: [Tutor] Re: Looking for peer review
References: <002101c228fa$d8077e60$e1e03942@joeltklrijxxms> <20020711170303.GA10735@ak.silmarill.org> <20020713052246.GB22260@dman.ddts.net>
Message-ID: <006801c22bae$fc858d70$f5e03942@joeltklrijxxms>

My question isn't so much as what I'm trying to do as to whether my python
scripting is sound.  This is the first python program I've written that
wasn't throw away code and wondered if I'm on the right track as far as
writting good code goes. I'm especially interested in thoughts on how I've
used exceptions -- am I using them properly, too many, not enough?

Joel





From dyoo@hkn.eecs.berkeley.edu  Mon Jul 15 04:51:58 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 14 Jul 2002 20:51:58 -0700 (PDT)
Subject: [Tutor] Re: A question on randomness
In-Reply-To: <20020713053700.GE22260@dman.ddts.net>
Message-ID: <Pine.LNX.4.44.0207142050440.9510-100000@hkn.eecs.berkeley.edu>


On Sat, 13 Jul 2002, Derrick 'dman' Hudson wrote:

> On Thu, Jul 11, 2002 at 11:22:48PM +0200, Andrea Valle wrote:
>
> | It' a couple of year I work with random generators.
>
> | I know pseudo-random generation is a complex matter. Is there a way to
> | "improve" it?
>
> If you don't like python's builtin pseudo-random generator, you can
> use the kernel's :
>
> rand = open( "/dev/random" , "r" )
> data = rand.read( 10 ) # just 10 bytes of random data
> rand.close()


Ah, good!  Ok, I've incorporated this into the Fourmilab random module,
and have renamed the module as 'truly_random':

    http://hkn.eecs.berkeley.edu/~dyoo/python/truly_random/

I hope this helps!




From idiot1@netzero.net  Mon Jul 15 04:59:43 2002
From: idiot1@netzero.net (Kirk Bailey)
Date: Sun, 14 Jul 2002 23:59:43 -0400
Subject: [Tutor] site update notice
Message-ID: <3D3248AF.7E857D6C@netzero.net>

TinyList site is updated. 
http://www.tinylist.org/

-- 

end

Respectfully,
             Kirk D Bailey


+---------------------"Thou Art Free." -Eris-----------------------+
| http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
| http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
+------------------Thinking| NORMAL |Thinking----------------------+
                           +--------+
-------------------------------------------
Introducing NetZero Long Distance
Unlimited Long Distance only $29.95/ month!
Sign Up Today! www.netzerolongdistance.com



From kojo@hal-pc.org  Mon Jul 15 05:15:06 2002
From: kojo@hal-pc.org (Kojo Idrissa)
Date: Sun, 14 Jul 2002 23:15:06 -0500
Subject: [Tutor] Convert CJK text into HEX value string
In-Reply-To: <F99jarXIEfeiyFlBcPP00012c0e@hotmail.com>
Message-ID: <5.1.0.14.0.20020714225351.023e8c80@mail.hal-pc.org>

If this was ASCII text, the atoi() function [which I just saw has been 
depricated] from the string module would do the trick.  Convert the text to 
an integer, then into hex.

I think the CJK characters are represented as Unicode (as opposed to 
ASCII).  If that's the case, the Unicode module is able to convert those 
strings in a manner similar to the String module.  Check out the decimal(), 
digit() and numeric() functions.  I don't have any CJK data to test this 
with, or I'd try for you and see.  Here's the link to the Unicode module docs:
<http://www.python.org/doc/current/lib/module-unicodedata.html>

If I'm way off base with this, someone jump in and correct me.

I might have to test this out myself.  I just started a new job a view 
weeks ago and a lot of our clientele is in Asia.  Japan especially.  I 
might want to do some text manipulation.

At 02:30 AM 7/15/2002 +0000, Hy wrote:
>Does anyone know how to Convert CJK(Chinese/Japanese/Korean) text into HEX 
>value string?
>I need to pass CJK Text via POST/GET cgi method. I need to convert the 
>text into a string of HEX values like "%BE%DF".
>
>Thanks a lot for your help.
>
>Hy

****************************
Kojo Idrissa

kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
****************************





From dman@dman.ddts.net  Mon Jul 15 05:42:15 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sun, 14 Jul 2002 23:42:15 -0500
Subject: [Tutor] Re: Convert CJK text into HEX value string
In-Reply-To: <F99jarXIEfeiyFlBcPP00012c0e@hotmail.com>
References: <F99jarXIEfeiyFlBcPP00012c0e@hotmail.com>
Message-ID: <20020715044215.GA18336@dman.ddts.net>

--FL5UXtIhxfXey3p5
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jul 15, 2002 at 02:30:34AM +0000, Hy Python wrote:
| Does anyone know how to Convert CJK(Chinese/Japanese/Korean) text into HE=
X=20
| value string?

I know the process, but I have no experience with those particular
charsets.  Which CJK charset are you referring to?

| I need to pass CJK Text via POST/GET cgi method. I need to convert the te=
xt=20
| into a string of HEX values like "%BE%DF".
|=20
| Thanks a lot for your help.

The general method is to use the unicode() constructor to create a
unicode string object from whatever your input source is, and then use
the .encode() method to encode that in which ever encoding is
appropriate.  Then use the quote() method in the urllib module to
url encode it.  So, for example, using latin1 and utf-8 :

>>> l_str =3D '\xbe\xdf'   # raw data
>>> u_str =3D unicode( l_str , 'latin1' )  # raw data is treated as latin1
>>> print repr( u_str )
u'\xbe\xdf'
# convert the unicode characters to a utf-8 encoded stream
>>> utf_str =3D u_str.encode( 'utf-8' )
>>> print repr( utf_str )
'\xc2\xbe\xc3\x9f'
>>> import urllib
>>> print urllib.quote( utf_str )
%C2%BE%C3%9F

I think this shows the basic concepts involved, and also that the
exact steps to take depends on where you get your data from and in
what form it is in when you get it.

The file encodings/aliases.py has this note in it :

    # CJK
    #
    # The codecs for these encodings are not distributed with the
    # Python core, but are included here for reference, since the
    # locale module relies on having these aliases available.
    #
    'jis_7': 'jis_7',
    'iso_2022_jp': 'jis_7',
    'ujis': 'euc_jp',
    'ajec': 'euc_jp',
    'eucjp': 'euc_jp',
    'tis260': 'tactis',
    'sjis': 'shift_jis',

I presume you'll be using one of these encodings, and you'll need to
find a codec for them.

-D

--=20
If Microsoft would build a car...
=2E.. Occasionally your car would die on the freeway for no reason. You
would have to pull over to the side of the road, close all of the car
windows, shut it off, restart it, and reopen the windows before you
could continue. For some reason you would simply accept this.
=20
http://dman.ddts.net/~dman/

--FL5UXtIhxfXey3p5
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0yUqcACgkQO8l8XBKTpRTtkgCgwXGhJjcdgb3WpnuBNKTeaWEc
92IAoKzQg0PMYFura67nulJ8G9cE2AM/
=XFrV
-----END PGP SIGNATURE-----

--FL5UXtIhxfXey3p5--



From slime@vsnl.net  Fri Jul 12 06:27:47 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Fri, 12 Jul 2002 10:57:47 +0530
Subject: [Tutor] Re: Ugly python one-liner !
In-Reply-To: <20020710035729.GC27035@dman.ddts.net>
References: <20020708172930.GA2666@localhost.localdomain> <20020710035729.GC27035@dman.ddts.net>
Message-ID: <20020712052747.GA2626@localhost.localdomain>

--6TrnltStXW4iwmi0
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

Hi,

On Tue, 09 Jul 2002 Derrick 'dman' Hudson spewed into the ether:
> import operator
>=20
> |     def one_norm (self) :
> |         """The sum of the elements in different rows of each column
> |         is computed, and the maximum of these values is said to
> |         be the one-norm of the Matrix.
> |         """
>           return max([reduce(operator.add,
> |                     [abs(self[r,c]) for r in range(self.rows)])
> |                         for c in range(self.columns)])
>=20
>=20
> |     Between map(), reduce() and list comprehension, I have finally
> | succeeded in making python look scary :-)
>=20
> Yep.  But you don't need that lambda in there -- the operator module

    Yes, I noticed the operator module, but I thought lambda would
involve much less over-head. I've actually only recently discovered
lambda's capabilities, when I tried this :

"""
def factorial (n) :
    return reduce(lambda x,y: x*y, range(2,n+1))
"""
> already has an add function for just that purpose :-).  You also don't
> need the backslashes -- python knows to continue because you haven't
> close the parenthesis.

    Ahh ! Didn't know that - python gets cooler by the minute :-)

pv.
--=20
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

One good reason why computers can do more work than people is that they
never have to stop and answer the phone.

--6TrnltStXW4iwmi0
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.4 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE9LmjTIKhjOSElu4YRAo4cAJ4uv1dvLPOZZLqXkTMJZ3E86UhYnQCgwyb6
ret8LaO7/HPdRJW9dtjTJEU=
=ynf7
-----END PGP SIGNATURE-----

--6TrnltStXW4iwmi0--



From dyoo@hkn.eecs.berkeley.edu  Mon Jul 15 08:40:28 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 15 Jul 2002 00:40:28 -0700 (PDT)
Subject: [Tutor] Sending email in Python...
In-Reply-To: <FA9060A56B68D511947F00A024B2D40001952162@agf3uex01.lasalle.navy.mil>
Message-ID: <Pine.LNX.4.44.0207150034480.23670-100000@hkn.eecs.berkeley.edu>


On Sun, 14 Jul 2002, Belan, Martin ET3 (AGF-3) wrote:

>     I was wondering how one would go about sending an email using
> python.  I am currently running python 2.2 under a Windows NT OS, which
> utilizes a proxy server.  If anyone out there could aid my quest until I
> am able to procure some decent documentation I would be much obliged.

Hi Belan,

You may find the 'smtplib' module appropriate --- SMTP is the protocol
that computers use to send off email.

Here's the documentation for smtplib:

    http://www.python.org/doc/lib/module-smtplib.html

The docs also come with an example, so it should be enough to get you
started.  However, I'm not quite sure how it works with a proxy, so
perhaps someone else on the Tutor list can talk more about that.


If you have more questions, please feel free to ask.  Best of wishes to
you!




From abli@freemail.hu  Mon Jul 15 11:14:34 2002
From: abli@freemail.hu (Abel Daniel)
Date: Mon, 15 Jul 2002 12:14:34 +0200
Subject: [Tutor] Tkinter not my friend any more
In-Reply-To: <000b01c22b86$e58e1060$d0d5ff3e@tinypc>
References: <20020714134401.31314.7043.Mailman@mail.python.org> <000b01c22b86$e58e1060$d0d5ff3e@tinypc>
Message-ID: <20020715101434.GA714@hooloovoo>

On Sun, Jul 14, 2002 at 11:36:29PM +0100 dominic.fox (dominic.fox@ntlworld.com) wrote:
> Hi all,
> 
> I'm having trouble getting Tkinter to do what I want it to do, and I think
> the reason is that Tkinter just isn't designed to do that thing. Basically I
> want an image buffer in a window on the screen that I can read and write to,
> plotting graphics primitives or even altering its contents pixel-by-pixel.
Have you looked at the Canvas widget?
If you want pixel-by-pixel manipulation, you can simulate it by drawing
short lines. For example
w.create_line(100,100,101,101, fill='green')
creates a green dot at coordinates (100,100)
(assuming w is an instance of the Canvas widget)

I'm not saying you should use this, but it can be done

abli
abli@freemail.hu



From erikprice@mac.com  Mon Jul 15 12:47:02 2002
From: erikprice@mac.com (Erik Price)
Date: Mon, 15 Jul 2002 07:47:02 -0400
Subject: [Tutor] Re: Convert CJK text into HEX value string
In-Reply-To: <20020715044215.GA18336@dman.ddts.net>
Message-ID: <9449061E-97E8-11D6-83FA-00039351FE6A@mac.com>

On Monday, July 15, 2002, at 12:42  AM, Derrick 'dman' Hudson wrote:

> The general method is to use the unicode() constructor to create a
> unicode string object from whatever your input source is, and then use
> the .encode() method to encode that in which ever encoding is
> appropriate.  Then use the quote() method in the urllib module to
> url encode it.  So, for example, using latin1 and utf-8 :

Pardon me for jumping in on this thread, but I'm curious -- does the 
string have to be converted to unicode because that's the encoding that 
URL encodings must be taken from?  Or is there some other reason it's 
being converted to unicode first?

And, sorta off-topic... why does it need to be converted to "utf-8"... 
that's something further than unicode?

I just thought of a neat "tool" script, one that would take a string as 
input and return a URL encoding of that string... I'm sure it's been 
written dozens of times before but it's probably easier to write than it 
is to hunt down on the net.



Erik




From gjlee@seri.co.uk  Mon Jul 15 14:36:23 2002
From: gjlee@seri.co.uk (Geonjae Lee)
Date: Mon, 15 Jul 2002 14:36:23 +0100
Subject: [Tutor] I'd like to sort (symbol, address) set by address
Message-ID: <341710540F08E34498A057DEE04DAAD71A6F8A@ex1.seri.co.uk>

Hi all.
I'm new to python.
These days, I'm trying to use python for my work.
My symbol file contents are like below.

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D

C$$zinit$$Base		11da1c0
C$$zinit$$Limit		11db840
watchdog_data$$Base	1101584
watchdog_data$$Limit	11015d0

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D

What I'd like to do is to sort my symbol files by address(second item).
I think first I have to convert second item value to integer.=20
so Is there any methond that change input(hex) to integer ?=20

And second, how can I sort by second item ?=20

I'd appreciate any help. Thanks.



From ak@silmarill.org  Mon Jul 15 16:10:55 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 15 Jul 2002 11:10:55 -0400
Subject: [Tutor] I'd like to sort (symbol, address) set by address
In-Reply-To: <341710540F08E34498A057DEE04DAAD71A6F8A@ex1.seri.co.uk>
References: <341710540F08E34498A057DEE04DAAD71A6F8A@ex1.seri.co.uk>
Message-ID: <20020715151055.GA9778@ak.silmarill.org>

On Mon, Jul 15, 2002 at 02:36:23PM +0100, Geonjae Lee wrote:
> 
> Hi all.
> I'm new to python.
> These days, I'm trying to use python for my work.
> My symbol file contents are like below.
> 
> ===================================================
> 
> C$$zinit$$Base		11da1c0
> C$$zinit$$Limit		11db840
> watchdog_data$$Base	1101584
> watchdog_data$$Limit	11015d0
> 
> =====================================================
> 
> What I'd like to do is to sort my symbol files by address(second item).
> I think first I have to convert second item value to integer. 
> so Is there any methond that change input(hex) to integer ? 
> 
> And second, how can I sort by second item ? 
>
You have to create a list of tuples (2nd item, 1st item), then simply
do mylist.sort() method. 

> 
> I'd appreciate any help. Thanks.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From lumbricus@gmx.net  Mon Jul 15 16:25:02 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Mon, 15 Jul 2002 17:25:02 +0200 (MEST)
Subject: [Tutor] I'd like to sort (symbol, address) set by address
References: <341710540F08E34498A057DEE04DAAD71A6F8A@ex1.seri.co.uk>
Message-ID: <16270.1026746702@www49.gmx.net>

> 
> Hi all.

Hello!

[ snip ]

> I think first I have to convert second item value to integer. 

No

> so Is there any methond that change input(hex) to integer ? 

There is no need for that. 
$ python
 Python 1.5.1 (#1, Apr  7 1999, 08:54:31) [C] on osf1V4
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> l=[0x23,0xff,0x1]
>>> l
[35, 255, 1]
>>> l.sort()
>>> l
[1, 35, 255]
>>> ^D

> I'd appreciate any help. Thanks.

HTH,HAND J"o!

-- 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net




From DavidCraig@pia.ca.gov  Mon Jul 15 17:44:33 2002
From: DavidCraig@pia.ca.gov (DavidCraig@pia.ca.gov)
Date: Mon, 15 Jul 2002 09:44:33 -0700
Subject: [Tutor] TEST
Message-ID: <OFADE7941A.AA373406-ON88256BF7.005BF139@PIA.CA.GOV>

ABSOLUTELY!

D. H. Craig, CSM





From jimbarnettjr@alltel.net  Mon Jul 15 19:01:51 2002
From: jimbarnettjr@alltel.net (jimbarnettjr)
Date: Mon, 15 Jul 2002 13:01:51 -0500
Subject: [Tutor] unsubscribe me please
Message-ID: <000a01c22c29$b2539aa0$0200000a@alltel.net>

This is a multi-part message in MIME format.

------=_NextPart_000_0007_01C22BFF.C932CE00
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

unsubsribe me please.

 jimbarnettjr@alltel.net

thank you

  jimmy barnett jr

------=_NextPart_000_0007_01C22BFF.C932CE00
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 5.50.4134.100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>unsubsribe me please.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;<A=20
href=3D"mailto:jimbarnettjr@alltel.net">jimbarnettjr@alltel.net</A></FONT=
></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>thank you</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp; jimmy barnett =
jr</FONT></DIV></BODY></HTML>

------=_NextPart_000_0007_01C22BFF.C932CE00--




From shalehperry@attbi.com  Mon Jul 15 19:21:49 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 15 Jul 2002 11:21:49 -0700 (PDT)
Subject: [Tutor] I'd like to sort (symbol, address) set by address
In-Reply-To: <341710540F08E34498A057DEE04DAAD71A6F8A@ex1.seri.co.uk>
Message-ID: <XFMail.20020715112149.shalehperry@attbi.com>

> 
> What I'd like to do is to sort my symbol files by address(second item).
> I think first I have to convert second item value to integer. 
> so Is there any methond that change input(hex) to integer ? 
> 
> And second, how can I sort by second item ? 
> 

rather than shifting your data, just adjust the sort function.

>>> items = [('sean', 1), ('lesley', 5), ('bob', 2), ('jane', 4)]
>>> def sorter(a, b):  
...   if a[1] < b[1]:
...     return -1
...   elif a[1] == b[1]:
...     return 0
...   else:
...     return 1
... 
>>> items
[('sean', 1), ('lesley', 5), ('bob', 2), ('jane', 4)]
>>> items.sort(sorter)
>>> items
[('sean', 1), ('bob', 2), ('jane', 4), ('lesley', 5)]




From dyoo@hkn.eecs.berkeley.edu  Mon Jul 15 20:09:43 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 15 Jul 2002 12:09:43 -0700 (PDT)
Subject: [Tutor] I'd like to sort (symbol, address) set by address  [using
 cmp()]
In-Reply-To: <XFMail.20020715112149.shalehperry@attbi.com>
Message-ID: <Pine.LNX.4.44.0207151205350.2838-100000@hkn.eecs.berkeley.edu>


On Mon, 15 Jul 2002, Sean 'Shaleh' Perry wrote:

> > What I'd like to do is to sort my symbol files by address(second
> > item). I think first I have to convert second item value to integer.
> > so Is there any methond that change input(hex) to integer ?
> >
> > And second, how can I sort by second item ?
> >
>
> rather than shifting your data, just adjust the sort function.
>
> >>> items = [('sean', 1), ('lesley', 5), ('bob', 2), ('jane', 4)]
> >>> def sorter(a, b):
> ...   if a[1] < b[1]:
> ...     return -1
> ...   elif a[1] == b[1]:
> ...     return 0
> ...   else:
> ...     return 1
> ...


By the way, we can also write this sort function by taking advantage of
Python's cmp() comparison function:

###
def compare_by_second(a, b):
    return cmp(a[1], b[1])
###

which, if I didn't put any typos in there, should do the same thing as
Sean's sorter() function.


Hope this helps!




From shalehperry@attbi.com  Mon Jul 15 20:23:37 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 15 Jul 2002 12:23:37 -0700 (PDT)
Subject: [Tutor] I'd like to sort (symbol, address) set by address  [
In-Reply-To: <Pine.LNX.4.44.0207151205350.2838-100000@hkn.eecs.berkeley.edu>
Message-ID: <XFMail.20020715122337.shalehperry@attbi.com>

> 
> By the way, we can also write this sort function by taking advantage of
> Python's cmp() comparison function:
> 
>###
> def compare_by_second(a, b):
>     return cmp(a[1], b[1])
>###
> 
> which, if I didn't put any typos in there, should do the same thing as
> Sean's sorter() function.
> 

Thanks Danny.  I was trying to demonstrate how to write a sorter() style
function.  Plus I often find that a simple call to cmp() is not sufficient for
most sorting needs 'sort by 2nd then 3rd column in lower case' kind of stuff.

But might as well use it when it lets you do a one liner (-:



From anthony.barker@bmo.com  Mon Jul 15 20:32:10 2002
From: anthony.barker@bmo.com (anthony.barker@bmo.com)
Date: Mon, 15 Jul 2002 15:32:10 -0400
Subject: [Tutor] best book for intermediate developer
Message-ID: <OFF3023F26.30054BA6-ON85256BF7.006957A8-85256BF7.006C2557@notes.bmo.com>

This is a multipart message in MIME format.
--=_alternative 006C255185256BF7_=
Content-Type: text/plain; charset="us-ascii"

Hi:

I have Beazley: "Python Essential Reference". which I picked up at a used 
bookstore. I found it excellent - particularly if you use internet 
websites 
such as python.org, "thinking like a computer scientist".. etc to 
suppliment it. I also got Fredrik Lundh's Python Standard Library to see 
what the libraries have to offer (haven't used it that much).

However I find I have gaps in my knowledge - and was looking for a third 
book to get along with the python cookbook (available 
July 15, 2002). 

What other book would you recommend ? - I looked at the Programming Python 
(2nd Edition) by Mark Lutz and Core Python Programming.

I find the layout of "Core" not that good. What about Quick Python? It 
seems to get good reviews....

> More OOP with Python
> More advanced error handling
> Algorithms/Threads etc...
> sockets 

The Ruby Way (a ruby book) looks excellent - but it is _not_ python...

Thanks,

Anthony


--=_alternative 006C255185256BF7_=
Content-Type: text/html; charset="us-ascii"


<br><font size=2 face="Arial">Hi:</font>
<br>
<br><font size=2 face="Arial">I have Beazley: &quot;Python Essential Reference&quot;. which I picked up at a used bookstore. I found it excellent - particularly if you use internet websites </font>
<br><font size=2 face="Arial">such as python.org, &quot;thinking like a computer scientist&quot;.. etc to suppliment it. I also got Fredrik Lundh's Python Standard Library to see what the libraries have to offer (haven't used it that much).</font>
<br>
<br><font size=2 face="Arial">However I find I have gaps in my knowledge - and was looking for a third book to get along with the python cookbook (available </font>
<br><font size=2 face="Arial">July 15, 2002). </font>
<br>
<br><font size=2 face="Arial">What other book would you recommend ? - I looked at the Programming Python (2nd Edition) by Mark Lutz and Core Python Programming.</font>
<br>
<br><font size=2 face="Arial">I find the layout of &quot;Core&quot; not that good. What about Quick Python? It seems to get good reviews....</font>
<br>
<br><font size=2 face="Arial">&gt; More OOP with Python</font>
<br><font size=2 face="Arial">&gt; More advanced error handling</font>
<br><font size=2 face="Arial">&gt; Algorithms/Threads etc...</font>
<br><font size=2 face="Arial">&gt; sockets </font>
<br>
<br><font size=2 face="Arial">The Ruby Way (a ruby book) looks excellent - but it is _not_ python...</font>
<br>
<br><font size=2 face="Arial">Thanks,</font>
<br>
<br><font size=2 face="Arial">Anthony</font>
<br>
<br>
--=_alternative 006C255185256BF7_=--



From dyoo@hkn.eecs.berkeley.edu  Mon Jul 15 22:05:50 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 15 Jul 2002 14:05:50 -0700 (PDT)
Subject: [Tutor] I'd like to sort (symbol, address) set by address  [using
 cmp(), part deux]
In-Reply-To: <XFMail.20020715122337.shalehperry@attbi.com>
Message-ID: <Pine.LNX.4.44.0207151443060.5150-100000@hkn.eecs.berkeley.edu>


> >###
> > def compare_by_second(a, b):
> >     return cmp(a[1], b[1])
> >###
> >
> > which, if I didn't put any typos in there, should do the same thing as
> > Sean's sorter() function.
> >
>
> Thanks Danny.  I was trying to demonstrate how to write a sorter() style
> function.  Plus I often find that a simple call to cmp() is not
> sufficient for most sorting needs 'sort by 2nd then 3rd column in lower
> case' kind of stuff.


Actually, this case is also pretty nice, since cmp() works on almost all
the basic Python types, including tuples!

###
def compare_by_second_then_lowered_third(a, b):
    return cmp( (a[1], a[2].lower()),
                (b[1], b[2].lower()) )
###

*grin*




But on a serious note: cmp() isn't as well known as it should be.  When
most people first see that a comparison function's supposed to return a
negative, or positive, or zero, an initial reaction could be to do a
subtraction to get the right values:

###
def compare_by_second_buggy(a, b):
    """Returns a negative number if 'a' is smaller than 'b', 0 if 'a' is
equal to 'b', and a positive if 'a' is greater than 'b'."""
    return a[1] - b[1]
###

Doing a straight subtraction looks like it should work, but it might not.
There's a particular boundary condition that is dangerous but easily
overlooked: integer subtraction can overflow if we're near the edge of the
largest (or smallest) representable integer.  That is, let's say that:

###
>>> import sys
>>> print sys.version
2.1.1 (#1, Sep 14 2001, 17:14:00)
[GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-85)]
>>> minint = -sys.maxint -1
>>> minint - 1
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
OverflowError: integer subtraction
###

In Python versions before 2.2, trying to represent such a negative number
can't be done in regular 32-bit integer arithmetic, so Python raises an
OverflowError.  In Python 2.2, the number is automatically converted to a
long int, so that we can do the subtraction safely.



So in that sense, we're have nothing to worry about.  We're safe, and
there's no real problem... except that in many other programming
languages, like Java or C, there are no guards against overflow.  In these
other languages, overflow will cause our number to "wrap around" the other
side of the spectrum, so that, suddenly, instead of getting a small
number, we get a honking large one.  But by knowing about cmp(), we can
avoid writing this kind of buggy code.


Hope this helps!




From kalle@lysator.liu.se  Mon Jul 15 22:49:29 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Mon, 15 Jul 2002 23:49:29 +0200
Subject: [Tutor] Problem with program ending
In-Reply-To: <F1361uqYA2feIQR3xgT0001131c@hotmail.com>
References: <F1361uqYA2feIQR3xgT0001131c@hotmail.com>
Message-ID: <20020715214929.GE4141@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[a polite punk]
> My name is Jonathan and I am a new Python programmer!

Welcome to the list!

>  But, I am having 
> trouble with a certain practice program that I have written.  It deals with 
> functions and the try and except statements.  The trouble is with ending 
> the program.  I use these commands below:
> 
>                         import sys
>                         sys.exit()
> 
> but when i do, it ignores it and continues with the program in the main 
> function.  I think it has to do with the use of the try and except 
> statements since i do not have this problem in the programs without the try 
> and except statements.  Here is the source code of the program below:
> 
[code]
>    except:

The trouble is here.  When you use except without arguments, it
catches any exception.  sys.exit() raises an exception called
SystemExit, I think.

The thing to do is to just catch the exceptions you're expecting,
namely ValueError (from the int() call).

So, try replacing
    except:
with
    except ValueError:

This goes for all the other except: clauses as well.  except without
arguments should be used very rarely, because it can have unexpected
results (as you discovered).

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9M0NmdNeA1787sd0RAs/BAJ9Rx6ymMhfPjbUtSgFneJWEqRnX2gCgv/Qs
FvPc08uCZsMEK6QZx6LxRxQ=
=fKjw
-----END PGP SIGNATURE-----



From erikprice@mac.com  Mon Jul 15 23:12:04 2002
From: erikprice@mac.com (Erik Price)
Date: Mon, 15 Jul 2002 18:12:04 -0400
Subject: [Tutor] best book for intermediate developer
In-Reply-To: <OFF3023F26.30054BA6-ON85256BF7.006957A8-85256BF7.006C2557@notes.bmo.com>
Message-ID: <E50DACF9-983F-11D6-94ED-00039351FE6A@mac.com>

On Monday, July 15, 2002, at 03:32  PM, anthony.barker@bmo.com wrote:

> I find the layout of "Core" not that good. What about Quick Python? It 
> seems to get good reviews....

I liked "Quick Python" a LOT... but it's kind of dated now, isn't it?  
Check for a new version, if not then I would probably avoid it.  For 
learning the essentials it's still fine but for intermediate stuff, a 
lot has changed.  But I could be wrong, so someone should correct me if 
I am.



Erik




From marta_andrea@libero.it  Tue Jul 16 01:37:51 2002
From: marta_andrea@libero.it (Andrea Valle)
Date: Tue, 16 Jul 2002 02:37:51 +0200
Subject: [Tutor] Plotting
In-Reply-To: <Pine.LNX.4.44.0207142050440.9510-100000@hkn.eecs.berkeley.edu>
Message-ID: <DNEFLBNHCGCPPIGNHGILCEBLCCAA.marta_andrea@libero.it>

(Dear Sirs, sorry, it's me again).
I'd like to plot dots and segments on a 2D plane.
I have to do something like this pseudopseudocode:
line.draw(xystart, xyend).
Suppose to have a logic representation in form a of a list of points and to
have to draw lines on a plane.
Is it possible to do something like this in Python?
If it's obvious (as I suspect), please point me to a link.
Thank you as usual.

best


-a-






From shalehperry@attbi.com  Tue Jul 16 00:52:20 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 15 Jul 2002 16:52:20 -0700 (PDT)
Subject: [Tutor] I'd like to sort (symbol, address) set by address  [
In-Reply-To: <Pine.LNX.4.44.0207151443060.5150-100000@hkn.eecs.berkeley.edu>
Message-ID: <XFMail.20020715165220.shalehperry@attbi.com>

> 
> 
> Actually, this case is also pretty nice, since cmp() works on almost all
> the basic Python types, including tuples!
> 
>###
> def compare_by_second_then_lowered_third(a, b):
>     return cmp( (a[1], a[2].lower()),
>                 (b[1], b[2].lower()) )
>###
> 
> *grin*
> 

now that is a wicked pisser!  Thanks Danny.



From shalehperry@attbi.com  Tue Jul 16 00:53:47 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 15 Jul 2002 16:53:47 -0700 (PDT)
Subject: [Tutor] best book for intermediate developer
In-Reply-To: <OFF3023F26.30054BA6-ON85256BF7.006957A8-85256BF7.006C2557@notes.bmo.com>
Message-ID: <XFMail.20020715165347.shalehperry@attbi.com>

On 15-Jul-2002 anthony.barker@bmo.com wrote:
> Hi:
> 
> I have Beazley: "Python Essential Reference". which I picked up at a used 
> bookstore. I found it excellent - particularly if you use internet 
> websites 
> such as python.org, "thinking like a computer scientist".. etc to 
> suppliment it. I also got Fredrik Lundh's Python Standard Library to see 
> what the libraries have to offer (haven't used it that much).
> 
> However I find I have gaps in my knowledge - and was looking for a third 
> book to get along with the python cookbook (available 
> July 15, 2002). 
> 

what did you find missing in the Python Essential Reference?  Between that and
the info docs I have been most pleased.

Perhaps if we knew what you needed we could better direct you.



From arosado@softhome.net  Tue Jul 16 01:17:12 2002
From: arosado@softhome.net (Andres Rosado)
Date: Mon, 15 Jul 2002 20:17:12 -0400
Subject: [Tutor] cookie?
Message-ID: <5.1.0.14.0.20020715201709.00bcfeb8@mail.softhome.net>

At 02:00 AM 7/13/2002 -0400, you wrote:
>OK, fortune cookies. Plenty of people use them on the web. Randomly
>selected pictures, links, pithy sayings.
>
>Well, I wrote a fortune cookie engine in python.
>
>http://www.tinylist.org/cookielisting.shtml
>
>There's a link there to view a page with the actual working output of
>the program.
>
>You can highlight and mouse copy, then paste in to a notepad document
>for a copy, in time I will do up a tarball and a zip file, but today I'm
>a little busy. Sounds like a candidate for the useless python site,
>what?

I made one similar, but for signature usage (see below). It still needs 
some improvements, but usable in Windows and Linux (untested). I haven't 
posted anywhere, thought. :( I will put it on my website once I finish to 
update it.


-----------------------------------
Andres Rosado
Email: andresr@despammed.com
ICQ: 66750646
Homepage: http://andres980.tripod.com/

The devil can cite Scripture for his purpose.
                 -- William Shakespeare, "The Merchant of Venice"




From dman@dman.ddts.net  Tue Jul 16 01:31:49 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Mon, 15 Jul 2002 19:31:49 -0500
Subject: [Tutor] Re: Convert CJK text into HEX value string
In-Reply-To: <9449061E-97E8-11D6-83FA-00039351FE6A@mac.com>
References: <20020715044215.GA18336@dman.ddts.net> <9449061E-97E8-11D6-83FA-00039351FE6A@mac.com>
Message-ID: <20020716003149.GA1504@dman.ddts.net>

--OXfL5xGRrasGEqWY
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jul 15, 2002 at 07:47:02AM -0400, Erik Price wrote:
|=20
| On Monday, July 15, 2002, at 12:42  AM, Derrick 'dman' Hudson wrote:
|=20
| >The general method is to use the unicode() constructor to create a
| >unicode string object from whatever your input source is, and then use
| >the .encode() method to encode that in which ever encoding is
| >appropriate.  Then use the quote() method in the urllib module to
| >url encode it.  So, for example, using latin1 and utf-8 :
|=20
| Pardon me for jumping in on this thread, but I'm curious -- does the=20
| string have to be converted to unicode because that's the encoding that=
=20
| URL encodings must be taken from?  Or is there some other reason it's=20
| being converted to unicode first?

Unicode string objects have a '.encode()' method.

URLs merely need to have any "odd" character encoded as %XX where XX
is the hex code of the character.  Whether the encoded character is
treated as ascii, latin1, utf-8, or euc-jp is up to the sender and
receiver.

| And, sorta off-topic... why does it need to be converted to "utf-8"...=20
| that's something further than unicode?

Unicode is the definition of a table of characters.  Unicode
characters are 2 bytes in length.  When you send data through a
stream (eg in a file or through a socket) you send bytes.  Thus you
need some method for encoding the 2-byte Unicode characters into a
stream that is based on single bytes.  UTF-8 does just that, and has
the nice bonus of encoding the ascii subset of unicode as plain ascii.

You can, of course, encode the string in any encoding, as long as the
data you have is representable in that encoding.

-D

--=20
The heart is deceitful above all things
    and beyond cure.
    Who can understand it?
=20
I the Lord search the heart
    and examine the mind,
to reward a man according to his conduct,
    according to what his deeds deserve.
=20
        Jeremiah 17:9-10
=20
http://dman.ddts.net/~dman/

--OXfL5xGRrasGEqWY
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0zaXUACgkQO8l8XBKTpRSXSQCgp70OoAhxpLhYZoTNB7RBDNba
9M4AoIYx+LLEYFUQDI4/J7kdmMNkw2W5
=A1Op
-----END PGP SIGNATURE-----

--OXfL5xGRrasGEqWY--



From glingl@aon.at  Tue Jul 16 07:40:44 2002
From: glingl@aon.at (Gregor Lingl)
Date: Tue, 16 Jul 2002 08:40:44 +0200
Subject: [Tutor] Plotting
References: <DNEFLBNHCGCPPIGNHGILCEBLCCAA.marta_andrea@libero.it>
Message-ID: <006f01c22c93$b662d420$1615a8c0@mega>

----- Original Message -----
From: "Andrea Valle" <marta_andrea@libero.it>
To: <tutor@python.org>
Sent: Tuesday, July 16, 2002 2:37 AM
Subject: [Tutor] Plotting


> (Dear Sirs, sorry, it's me again).
> I'd like to plot dots and segments on a 2D plane.
> I have to do something like this pseudopseudocode:
> line.draw(xystart, xyend).

One way to accomplish this task is to use the standard
GUI toolkit of Python, Tkinter

example:

from Tkinter import *

lines = [10,20,40,10,65.77,111.5,215.33333, 28, 280,195]

root = Tk()                              # create Tk Window
cv = Canvas(root, width=300, height=200) # Canvas widget to do graphics
cv.pack()                                # call geometry manager

cv.create_line(lines)                    # this is - more or less -
                                         # what you want
mainloop()                               # starts event handling loop
# end of code


Ressources on Tkinter:

http://www.python.org/topics/tkinter/
http://mcl.ee.hallym.ac.kr/Menu/6_psd/python/tkinter

Regards
Gregor


> Suppose to have a logic representation in form a of a list of points and
to
> have to draw lines on a plane.
> Is it possible to do something like this in Python?
> If it's obvious (as I suspect), please point me to a link.
> Thank you as usual.
>
> best
>
>
> -a-
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From glide@slingshot.co.nz  Tue Jul 16 09:11:46 2002
From: glide@slingshot.co.nz (Graeme Andrew)
Date: Tue, 16 Jul 2002 20:11:46 +1200
Subject: [Tutor] Calling functions using a variable name .. ??
Message-ID: <200207162011.46665.glide@slingshot.co.nz>

Hi All,

Sorry another newbie question !!

I am wanting to execute functions based on the names of functions read ou=
t of=20
a configuration file and assigned to a variable.

I guess something like this ...

f =3D open(myfile_file, 'r')
# read all the lines into a list
my_list=3Df.readlines()
#the list holds the names of all the functions I want to execute ...
my_function =3D my_list[n]
exec my_function()

=2E... is this possible ? =20

Thanks in advance

Regards
Graeme Andrew
=20









From lumbricus@gmx.net  Tue Jul 16 10:32:49 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Tue, 16 Jul 2002 11:32:49 +0200 (MEST)
Subject: [Tutor] Calling functions using a variable name .. ??
References: <200207162011.46665.glide@slingshot.co.nz>
Message-ID: <14752.1026811969@www57.gmx.net>

> Hi All,

Hello

[ snip ]

> .... is this possible ?  

yes
 
> Thanks in advance

SCNR
 
> Regards
> Graeme Andrew

J"o!

-- 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net




From lonetwin <lonetwin@yahoo.com>  Tue Jul 16 10:46:15 2002
From: lonetwin <lonetwin@yahoo.com> (lonetwin)
Date: Tue, 16 Jul 2002 15:16:15 +0530 (IST)
Subject: [Tutor] LHA compression
Message-ID: <Pine.LNX.4.44.0207161508170.4389-100000@localhost.localdomain>

Hi all,
   I'm smiling right now, 'cos I just read the signature at the bottom
(I've set Pine to do a "| /usr/games/fortune" to give me random sig's).
	Anyways, here's the question. How do I (if I can...that is) create a
lha archive using Python ? I can't seem to find any modules for doing
this.

Peace
Steve

-- 
Questionable day.

Ask somebody something.




From scot@possum.in-berlin.de  Tue Jul 16 14:38:32 2002
From: scot@possum.in-berlin.de (Scot W. Stevenson)
Date: Tue, 16 Jul 2002 15:38:32 +0200
Subject: [Tutor] best book for intermediate developer
In-Reply-To: <OFF3023F26.30054BA6-ON85256BF7.006957A8-85256BF7.006C2557@notes.bmo.com>
References: <OFF3023F26.30054BA6-ON85256BF7.006957A8-85256BF7.006C2557@notes.bmo.com>
Message-ID: <200207161538.32680.scot@possum.in-berlin.de>

Hello Anthony,=20

> What other book would you recommend ? - I looked at the Programming
> Python (2nd Edition) by Mark Lutz and Core Python Programming.

I have found Lutz' book extremely useful and keep coming back to it for a=
ll=20
sorts of things. However, it is rather dated by now (note that it was=20
published March 2001) and unfortunately no new version seems to be in the=
=20
works. If the time span between first and second editions is any guide, a=
=20
new version should be out in 2006.=20

If you don't mind writing Medieval Python (version 2.0, good for building=
=20
bridges out of witches), I can very much recommend it.=20

Y, Scot

--=20
  Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany




From dman@dman.ddts.net  Tue Jul 16 17:36:18 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 16 Jul 2002 11:36:18 -0500
Subject: [Tutor] Re: LHA compression
In-Reply-To: <Pine.LNX.4.44.0207161508170.4389-100000@localhost.localdomain>
References: <Pine.LNX.4.44.0207161508170.4389-100000@localhost.localdomain>
Message-ID: <20020716163618.GA12527@dman.ddts.net>

--Kj7319i9nmIyA2yE
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 16, 2002 at 03:16:15PM +0530, lonetwin wrote:

| Anyways, here's the question. How do I (if I can...that is) create a
| lha archive using Python ? I can't seem to find any modules for doing
| this.

I am not aware of any software (except for an old MS-DOS program I
used to have, back in the days of MS-DOS 3.3) for handling lha
archives.

If you can find the specification for the format of the file then you
can write the module for createing the archives.  Alternatively, just
use zip or tar or tar+gzip instead.

-D

--=20
A)bort, R)etry, D)o it right this time
=20
http://dman.ddts.net/~dman/

--Kj7319i9nmIyA2yE
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj00S4IACgkQO8l8XBKTpRRM4wCffwCH7PU3l0ZJclYJ9kl747hg
6SwAni4llccUlr2jcwlKsOPSVbwvkLvI
=uxe+
-----END PGP SIGNATURE-----

--Kj7319i9nmIyA2yE--



From shalehperry@attbi.com  Tue Jul 16 17:30:32 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 16 Jul 2002 09:30:32 -0700 (PDT)
Subject: [Tutor] Re: LHA compression
In-Reply-To: <20020716163618.GA12527@dman.ddts.net>
Message-ID: <XFMail.20020716093032.shalehperry@attbi.com>

On 16-Jul-2002 Derrick 'dman' Hudson wrote:
> On Tue, Jul 16, 2002 at 03:16:15PM +0530, lonetwin wrote:
> 
>| Anyways, here's the question. How do I (if I can...that is) create a
>| lha archive using Python ? I can't seem to find any modules for doing
>| this.
> 
> I am not aware of any software (except for an old MS-DOS program I
> used to have, back in the days of MS-DOS 3.3) for handling lha
> archives.
> 

there is a port of said DOS app to Unix, Debian has it in non-free.

> If you can find the specification for the format of the file then you
> can write the module for createing the archives.  Alternatively, just
> use zip or tar or tar+gzip instead.
> 

I haven't seen a usage in recent years that was not at least bending the laws. 
Games cracking mostly.



From alan.gauld@bt.com  Tue Jul 16 18:11:54 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 16 Jul 2002 18:11:54 +0100
Subject: [Tutor] Re: Re: small program in Python and in C++
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C728@mbtlipnt02.btlabs.bt.co.uk>

Hi Dman,

> I thought only ASM needed a line of comment per line of code ;-).
> Whatever happened to self-documenting code?

It's alive and well, but most corporate coding standards 
require extensive comment block headers at the top of 
each file as well as above each function. Thus a 5 line 
function may have a 15 line header on top!(see our 
local example appended at the end...)

> | In the real world many functions contain 200 plus lines of 
> | executable code(*) which means maybe 400-500 lines of text.
> 
> I'm glad I'm not in the "real world" ;-).

Sorry, that sounded a bit patronising. A better term might 
have been "industrial scale" software projects. 
eg Air traffic Control, Nuclear reactors, Telephone exchanges 
and the like. (Recall we were talking about C++ projects 
in this thread not Python!)

> Yeah, I can see 100 lines of
>     stream << this->foo

More usually 100 times:

 if (this->foo) || (this->bar){
      stream << this->foo;
 }

ie 300 lines!

> attribute should have its own self-contained serialization function,

Could be but for primitive types that makes the files even 
bigger and most attributes will be either integers, floats 
or strings - ie the things you can store in an RDBMS.

> | time consuming and error prone. Jumping to the top of the function 
> | is a single keystroke!
> 
> Which keystroke, btw?  It would be helpful if I knew it.  

> I know how to use ctags, but that's quite a few keystrokes 
> (depending on function names and polymorphic ussage)

It shouldn't be if your ctags is C++ aware...
However ctags doesn't help for the current function, 
but [[ should go to the start of a paragraph in text 
mode or the start of the current function in C/C++ mode.

I just tried it and it relies on you putting your opening 
brace in the leftmost collumn (Which I do normally so it 
works for me  :-) like so:

void foo()
{
   //blah blah
   if(bar){
      //blah2
   }
   return;
}

> | Well written variable declarations should all be commented! :-)
> 
> It shouldn't need a comment, except in the *few* (right? ;-))
> not-so-obvious cases :-).

Not so obvious is rarely the case in my experience. What the 
original programmer thinks is obvious very rarely is to somebody 
else later! (Of course the fact that modern compilers tend to 
allow more than 6 characters in variables helps ;-)

> | Only if reading the code sequentially, if you are jumping in 
> | at random - as is usually the case for maintenance programmers 
> THat makes sense.

Just to elaborate. The normal mode of operation for a 
maintenance programmer with a hot fault is to load up 
the executable in the debugger with a core dump(if Unix or MVS)
and do a stacktrace. They will then navigate up the stack 
which means they arrive in the upper level function 
wherever the call to the lower level one was made, not 
at the entry point..

> | A crash in those circumstances is a good thing! And NULLS help 
> | achieve it!
> 
> While I agree here, what if you got a 'NameError' exception instead of
> 'AttributeError: None object has no member foo' _or_ if the operation

We were talking C++ remember. A Name error will be caught at 
compile time in C++.

> you performed was perfectly valid with None/NULL but that was not the
> value the variable should have had.

There are obviously a few possible cases where this can happen 
but to be honest they are very rare. If you think abouit it 
most functions that accept a NULL do so only to indicate 
that a default value be used instead

Pythonically:

def foo(a=None):
  if a == None: a = 42
  # continue using a now good a...

There are very few valid uses for NULL or 0 in C/C++.

> | I see the point of wasted resource but not sure how Java/Python 
> | helps here. If you initialize the variable to a dummy object you 
> Here's an example :
> 
> // C++
> class Foo
> {
> }
> 
> void func()
> {
>     Foo local_foo ;

Ah yes, non dynamic classes. I forgot about those in C++, 
I hardly ever use them. You are quite right, in those cases 
premature initialisation would waste resource.

> One way to avoid it is to use a pointer, and then allocate the object
> using 'new' when you need it.  Then you must remember to 'delete' it
> afterwards.  Also, supposedly, the heap is slower than the stack.

I always use dymanic objects in C++ and the performance 
overhead is minimal. The loss of polymorphism in statically 
declared classes is much more serious IMHO!

> (I also like python's ability to get rid of a local ('del') after
> you're done with it.  It helps prevent you from erroneously re-using
> the old data later on -- which I've done before!)

Yes memory management is a perennial problem in C/C++, it's about
the only good thing I have to say about Java :-)

> Surely if you can actually and accurately quantize the effect, then
> you can make a better argument than aesthetics.  

Unfortunately there is a wealth of objective collected data about
maintenance programming. Its always seem as a cost rather than 
revenue earner so the bean counters monitor it closely. Sadly 
the mainsatream software community seems to ignore it by and 
large! Possibly because it invariable originates in industry 
rather than  academia? No surely not... :-)

> benefits of each method and choose the best one.  Since quantization
> isn't a viable option, experience is the next best decider.  

I'm interested in why you think quantization is hard? 
Measuring time to fix, lines changed, code quality metrics 
etc is part and parcel of every maintenance teams work that 
I've ever worked with (erm, thats only 3, all in the same 
organisation BTW!!)

> My comments here aren't intended as arguments, just clarification of
> what I had said before and of the "other" perspective.  (and some of
> it is meant to be a bit humorous)

Me too, I must apologize if my earliuer post sounded a bit 
pompous, its an unfortunate tendency I have. They were meant 
entirely as my personal experience of maintaining large scale 
projects. (The first was 3,500,000 lines of C/C++, the second 
500,000 lines of C++ and the 3rd 350,000 lines of COBOL)

Hopefully there are some points of interest to the general 
Python community in here too, hidden amongst the rantings :-)

Alan G.
(Just returned from a week without computer access!)

Function header template:

###################################
# Signature:
#
# Input parameters:
# 
# Output Parameters:
#
# Operation:
#
# Notes:
#
# Maintenance History:
#
###################################

That has to be filled in for every function regardless 
of how small... A similar but bigger template is filled 
in at the top of every file includeiong the full RCS log...





From roete142@planet.nl  Tue Jul 16 20:11:41 2002
From: roete142@planet.nl (Jeroen Roeterd)
Date: Tue, 16 Jul 2002 21:11:41 +0200
Subject: [Tutor] upgrade from 2.1.3 to 2.2.1
Message-ID: <3D346FED.9070501@planet.nl>

Hello,

I am starting new with Python programming. I had it installed to get the 
MoinMoinWiki working.
That was version 2.1.3 and in the beginnersguide it is advised to start 
with the 2.2.1 version.

Is it possible to install it over the current installtion? It default to 
python22 while I do already have a python21 install dir.

Thanks for any answers.

Greetings,
Jeroen Roeterd




From dominic.fox" <dominic.fox@ntlworld.com  Tue Jul 16 21:06:40 2002
From: dominic.fox" <dominic.fox@ntlworld.com (dominic.fox)
Date: Tue, 16 Jul 2002 21:06:40 +0100
Subject: [Tutor] Re: Tkinter
References: <20020716160004.3246.49133.Mailman@mail.python.org>
Message-ID: <001d01c22d04$4c8e2ba0$d0d5ff3e@tinypc>

Thanks for suggestions. I think Jython / Swing may have something going for
it, although I'd anticipate a fairly hefty performance hit from doing it
that way (insert standard "Java performance isn't necessarily as bad as you
think" response here). Plotting points on a Tkinter canvas by creating lots
of very-small-line objects is just what I was hoping to avoid - it sounds
like a nightmare in just about every way. This isn't to disparage that
approach to doing graphics in general, which in other contexts would be
ideal - it's rather like manipulating Drawfiles on a RISC-OS machine (if
anyone remembers that) - but even Drawfiles let you plot sprites onto the
screen (and, if you knew what to do with a few system calls, manipulate
their contents too). It just seems weird to me, having used at least three
different platforms* on which it was fairly trivial to plot pixels into a
buffer somewhere then blit it onto the screen, that there isn't an obvious
and accessible out-of-the-box way to do it in Python.

I *think* wxPython may have what I want - will investigate and report
back...

cheers,
Dominic

* that would be RISC-OS, VB and Java, btw. This isn't a brag: I sucked on
all of them apart from VB, which did a fair amount of sucking itself.

--> Nobody knows the trouble you've seen / walking from your desk to the
staff canteen <--
homepage: http://www.geocities.com/domfox




From dyoo@hkn.eecs.berkeley.edu  Tue Jul 16 21:26:52 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 16 Jul 2002 13:26:52 -0700 (PDT)
Subject: [Tutor] Re: Tkinter  [pygame with tkinter?]
In-Reply-To: <001d01c22d04$4c8e2ba0$d0d5ff3e@tinypc>
Message-ID: <Pine.LNX.4.44.0207161316310.2984-100000@hkn.eecs.berkeley.edu>


On Tue, 16 Jul 2002, dominic.fox wrote:

> anyone remembers that) - but even Drawfiles let you plot sprites onto
> the screen (and, if you knew what to do with a few system calls,
> manipulate their contents too). It just seems weird to me, having used
> at least three different platforms* on which it was fairly trivial to
> plot pixels into a buffer somewhere then blit it onto the screen, that
> there isn't an obvious and accessible out-of-the-box way to do it in
> Python.

If all you want is a buffer to draw pixels, then the pygame module might
be useful:

    http://pygame.org

I've used it for small projects with graphical output, and it's not too
hard to do sprite manipulation with it.  I don't know how to incorporate a
pygame buffer with other gui widgets though, but it might be possible.


There was a thread about using Pygame's canvas with the rest of the
Tkinter widgets here:

    http://archives.seul.org/pygame/users/Nov-2001/msg00055.html

and it might be good to bring this question up on the pygame mailing list.



There's also an article about using Pygame with Tkinter on Deitel and
Deitel:

http://www.informit.com/content/index.asp?product_id={10C3A878-BEE8-47C5-9426-422E8E107D9B}&null

so at least there's some hope of this working... *grin*



Best of wishes to you!




From dominic.fox" <dominic.fox@ntlworld.com  Tue Jul 16 21:42:42 2002
From: dominic.fox" <dominic.fox@ntlworld.com (dominic.fox)
Date: Tue, 16 Jul 2002 21:42:42 +0100
Subject: [Tutor] Re: Tkinter  [pygame with tkinter?]
References: <Pine.LNX.4.44.0207161316310.2984-100000@hkn.eecs.berkeley.edu>
Message-ID: <000501c22d09$556c1f20$d0d5ff3e@tinypc>

Oh yes, I'd forgotten about pygame. That might be quite handy for
Pyngband...

wxWindows/Python  looks nice - I've just been trying out the demos - it's a
shame my graphics card (ATI Rage Pro 128) doesn't have OpenGL drivers, 'cos
that would be *really* nice. However, after a 30-second glimpse at a couple
of bits of demo source code, it looks as if wxPython *does* do the "get a
device context then draw to it" approach which I wanted to use, so I think
I'll stop and explore here for the moment.

Also, Eric Raymond says it's his favourite...

Dominic
--> Nobody knows the trouble you've seen / walking from your desk to the
staff canteen <--
homepage: http://www.geocities.com/domfox
----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "dominic.fox" <dominic.fox@ntlworld.com>
Cc: <tutor@python.org>
Sent: Tuesday, July 16, 2002 9:26 PM
Subject: Re: [Tutor] Re: Tkinter [pygame with tkinter?]


>
>
> On Tue, 16 Jul 2002, dominic.fox wrote:
>
> > anyone remembers that) - but even Drawfiles let you plot sprites onto
> > the screen (and, if you knew what to do with a few system calls,
> > manipulate their contents too). It just seems weird to me, having used
> > at least three different platforms* on which it was fairly trivial to
> > plot pixels into a buffer somewhere then blit it onto the screen, that
> > there isn't an obvious and accessible out-of-the-box way to do it in
> > Python.
>
> If all you want is a buffer to draw pixels, then the pygame module might
> be useful:
>
>     http://pygame.org
>
> I've used it for small projects with graphical output, and it's not too
> hard to do sprite manipulation with it.  I don't know how to incorporate a
> pygame buffer with other gui widgets though, but it might be possible.
>
>
> There was a thread about using Pygame's canvas with the rest of the
> Tkinter widgets here:
>
>     http://archives.seul.org/pygame/users/Nov-2001/msg00055.html
>
> and it might be good to bring this question up on the pygame mailing list.
>
>
>
> There's also an article about using Pygame with Tkinter on Deitel and
> Deitel:
>
>
http://www.informit.com/content/index.asp?product_id={10C3A878-BEE8-47C5-942
6-422E8E107D9B}&null
>
> so at least there's some hope of this working... *grin*
>
>
>
> Best of wishes to you!
>




From lonetwin@yahoo.com  Wed Jul 17 06:37:50 2002
From: lonetwin@yahoo.com (lonetwin)
Date: Wed, 17 Jul 2002 11:07:50 +0530
Subject: [Tutor] Re: LHA compression
In-Reply-To: <XFMail.20020716093032.shalehperry@attbi.com>
References: <XFMail.20020716093032.shalehperry@attbi.com>
Message-ID: <20020717053750.56A6F2F6E4@mercury.sapatmt>

Hi,
    Thanx for replying dman, Sean. Actually, I myself hadn't heard of LHA 
compression till I bought a Casio PV(S460) a few days back, there is an 
application called TextViewer (an ebook reader) for the PV that requires 
files to be compressed using lha compression. The author of the app. has also 
written an application called PVUploader that lets you upload the archive to 
the PV thru' linux (Unfortunately ....most of the other s/w that lets you 
interact with the PV runs only on windoze). 
	So I thought of writing a front end to PVUploader (....maybe even
some other apps too) using python. That's the reason why I was wondering if  
a lha module was available.
	Anyways, I discovered lha is available for most linux distros (free too 
...does debian really have it non free ???). So I guess it's ok. Although, 
not having to build a dependency on lha would have been nice.

Thanx again

Peace
Steve

On Tuesday 16 July 2002 10:00 pm, you wrote:
> On 16-Jul-2002 Derrick 'dman' Hudson wrote:
> > On Tue, Jul 16, 2002 at 03:16:15PM +0530, lonetwin wrote:
> >| Anyways, here's the question. How do I (if I can...that is) create a
> >| lha archive using Python ? I can't seem to find any modules for doing
> >| this.
> >
> > I am not aware of any software (except for an old MS-DOS program I
> > used to have, back in the days of MS-DOS 3.3) for handling lha
> > archives.
>
> there is a port of said DOS app to Unix, Debian has it in non-free.
>
> > If you can find the specification for the format of the file then you
> > can write the module for createing the archives.  Alternatively, just
> > use zip or tar or tar+gzip instead.
>
> I haven't seen a usage in recent years that was not at least bending the
> laws. Games cracking mostly.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Wish and hope succeed in discerning signs of paranormality where reason and
careful scientific procedure fail.
- James E. Alcock, The Skeptical Inquirer, Vol. 12




From lonetwin@subdimension.com  Wed Jul 17 06:29:58 2002
From: lonetwin@subdimension.com (lonetwin_SubD)
Date: Wed, 17 Jul 2002 10:59:58 +0530
Subject: [Tutor] Re: LHA compression
In-Reply-To: <XFMail.20020716093032.shalehperry@attbi.com>
References: <XFMail.20020716093032.shalehperry@attbi.com>
Message-ID: <20020717052958.AA72D2F6E4@mercury.sapatmt>

Hi,
    Thanx for replying dman, Sean. Actually, I myself hadn't heard of LHA 
compression till I bought a Casio PV(S460) a few days back, there is an 
application called TextViewer (an ebook reader) for the PV that requires 
files to be compressed using lha compression. The author of the app. has also 
written an application called PVUploader that lets you upload the archive to 
the PV thru' linux (Unfortunately ....most of the other s/w that lets you 
interact with the PV runs only on windoze). 
	So I thought of writing a front end to PVUploader (....maybe even
some other apps too) using python. That's the reason why I was wondering if  
a lha module was available.
	Anyways, I discovered lha is available for most linux distros (free too 
...does debian really have it non free ???). So I guess it's ok. Although, 
not having to build a dependency on lha would have been nice.

Thanx again

Peace
Steve

On Tuesday 16 July 2002 10:00 pm, you wrote:
> On 16-Jul-2002 Derrick 'dman' Hudson wrote:
> > On Tue, Jul 16, 2002 at 03:16:15PM +0530, lonetwin wrote:
> >| Anyways, here's the question. How do I (if I can...that is) create a
> >| lha archive using Python ? I can't seem to find any modules for doing
> >| this.
> >
> > I am not aware of any software (except for an old MS-DOS program I
> > used to have, back in the days of MS-DOS 3.3) for handling lha
> > archives.
>
> there is a port of said DOS app to Unix, Debian has it in non-free.
>
> > If you can find the specification for the format of the file then you
> > can write the module for createing the archives.  Alternatively, just
> > use zip or tar or tar+gzip instead.
>
> I haven't seen a usage in recent years that was not at least bending the
> laws. Games cracking mostly.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Wish and hope succeed in discerning signs of paranormality where reason and
careful scientific procedure fail.
- James E. Alcock, The Skeptical Inquirer, Vol. 12



From guillermo.fernandez@epfl.ch  Wed Jul 17 07:34:22 2002
From: guillermo.fernandez@epfl.ch (Guillermo Fernandez)
Date: Wed, 17 Jul 2002 16:04:22 +0930
Subject: [Tutor] print function
References: <XFMail.20020716093032.shalehperry@attbi.com> <20020717053750.56A6F2F6E4@mercury.sapatmt>
Message-ID: <3D350FEE.F2171EB6@epfl.ch>

Hi!

I would like to make a print. There is, of course, the print function,
but this one automatically add a '\n' at the end of the line. Is there a
way to avoid this behaviour?

I would like to do something like:

print "first fct"
fct1()
print " second fct"
fct2()
print " third fct"
fct3()

and have an output like:
"first fct second fct third fct"

I've searched through the library reference, but I did not find any
function that allows me to do that.

I'm using Python 2.0

Thanks!

Guille



From shalehperry@attbi.com  Wed Jul 17 07:44:20 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 16 Jul 2002 23:44:20 -0700 (PDT)
Subject: [Tutor] Re: LHA compression
In-Reply-To: <20020717052958.AA72D2F6E4@mercury.sapatmt>
Message-ID: <XFMail.20020716234420.shalehperry@attbi.com>

>       Anyways, I discovered lha is available for most linux distros (free too 
> ...does debian really have it non free ???). So I guess it's ok. Although, 
> not having to build a dependency on lha would have been nice.
> 

non-free simply means it does not have a 100% free license.  It does not imply
cost.  Without downloading it and looking at the license I could not tell you
why.  My guess is it either has a "free for non-commerical use" or "free but
don't change it" style license.



From lonetwin@yahoo.com  Wed Jul 17 07:41:47 2002
From: lonetwin@yahoo.com (lonetwin)
Date: Wed, 17 Jul 2002 12:11:47 +0530
Subject: [Tutor] print function
In-Reply-To: <3D350FEE.F2171EB6@epfl.ch>
References: <3D350FEE.F2171EB6@epfl.ch>
Message-ID: <20020717064147.9DBF82F6E4@mercury.sapatmt>

Hi Guillermo,
	You need to append a "," at the end for your string, thats all.
ie:
 print "first fct", 
 fct1()
 print "second fct",
 .....
 .....

will print
 first fct second fct ....
	The comma will aslo take care of adding the space between strings that get 
printed continuously.

Peace
Steve


On Wednesday 17 July 2002 12:04 pm, you wrote:
> Hi!
>
> I would like to make a print. There is, of course, the print function,
> but this one automatically add a '\n' at the end of the line. Is there a
> way to avoid this behaviour?
>
> I would like to do something like:
>
> print "first fct"
> fct1()
> print " second fct"
> fct2()
> print " third fct"
> fct3()
>
> and have an output like:
> "first fct second fct third fct"
>
> I've searched through the library reference, but I did not find any
> function that allows me to do that.
>
> I'm using Python 2.0
>
> Thanks!
>
> Guille
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
To err is human, to repent, divine, to persist, devilish.
		-- Benjamin Franklin



From shalehperry@attbi.com  Wed Jul 17 07:49:23 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 16 Jul 2002 23:49:23 -0700 (PDT)
Subject: [Tutor] Re: LHA compression
In-Reply-To: <XFMail.20020716234420.shalehperry@attbi.com>
Message-ID: <XFMail.20020716234923.shalehperry@attbi.com>

On 17-Jul-2002 Sean 'Shaleh' Perry wrote:
>>       Anyways, I discovered lha is available for most linux distros (free
>>       too 
>> ...does debian really have it non free ???). So I guess it's ok. Although, 
>> not having to build a dependency on lha would have been nice.
>> 
> 
> non-free simply means it does not have a 100% free license.  It does not
> imply
> cost.  Without downloading it and looking at the license I could not tell you
> why.  My guess is it either has a "free for non-commerical use" or "free but
> don't change it" style license.
> 

We have lha 1.14i.

Translated License Statement (translated by GOTO Masanori <gotom@debian.org>):

   It's free to distribute on the network, but if you distribute for
   the people who cannot access the network (by magazine or CD-ROM),
   please send E-Mail (Inter-Net address) to the author before the
   distribution. That's well where this software is appeard.
   If you cannot do, you must send me the E-Mail later.

So we have permission to give it to people but no permission to modify.  The
license was originally in Japanese.

If you find some other implementation of lha someone could port it to python
or make a c wrapper.



From lonetwin@yahoo.com  Wed Jul 17 08:02:17 2002
From: lonetwin@yahoo.com (lonetwin)
Date: Wed, 17 Jul 2002 12:32:17 +0530
Subject: [Tutor] Re: LHA compression
In-Reply-To: <XFMail.20020716234420.shalehperry@attbi.com>
References: <XFMail.20020716234420.shalehperry@attbi.com>
Message-ID: <20020717070217.7906A2F6E4@mercury.sapatmt>

Hi Sean,
	I looked at the license in the sources bundled with the .src.rpm, it says 
"License: Freeware-like" ...wonder what that means ...the homepage of the 
author and for his "lha for unix page" is in japanese, So, I'm lost.
    Anyways, I most certainly would be using it for "non-commercial use" 
Maybe this is inspiration enough to seriously think about writing a "free" 
python module for lha compression, like dman suggested. Anyone wanna jump in 
?? ...Me being me, I'd get down to __actually__ doing instead of just 
thinking, if I have work with someone else. :)
	Right away tho' I need to find out if the algo. itself is not patented or 
propriety.

Ta for now,
Peace
Steve

On Wednesday 17 July 2002 12:14 pm, you wrote:
> >       Anyways, I discovered lha is available for most linux distros (free
> > too ...does debian really have it non free ???). So I guess it's ok.
> > Although, not having to build a dependency on lha would have been nice.
>
> non-free simply means it does not have a 100% free license.  It does not
> imply cost.  Without downloading it and looking at the license I could not
> tell you why.  My guess is it either has a "free for non-commerical use" or
> "free but don't change it" style license.

-- 
	"How would I know if I believe in love at first sight?" the sexy
social climber said to her roommate.  "I mean, I've never seen a Porsche
full of money before."




From virketis@post.harvard.edu  Wed Jul 17 07:54:32 2002
From: virketis@post.harvard.edu (Pijus Virketis)
Date: Wed, 17 Jul 2002 09:54:32 +0300
Subject: [Tutor] how to get a unique handle on an email?
Message-ID: <ISPFE7OoORYRoOQ9Rjo0003d327@mail.takas.lt>

<HTML><HEAD>
</HEAD>
<BODY>
<div><FONT FACE=3D"Arial" SIZE=3D3>Dear All,</FONT></div>
<div>&nbsp;</div>
<FONT FACE=3D"Arial" SIZE=3D3></FONT><div><FONT FACE=3D"Arial" SIZE=3D3>I=
 recently wrote a little script that deletes all the messages=
 sitting in my email client's Trash mailbox from the mail server.=
 It uses poplib, and there's really nothing to it. </FONT></div>
<div>&nbsp;</div>
<FONT FACE=3D"Arial" SIZE=3D3></FONT><div><FONT FACE=3D"Arial"=
 SIZE=3D3>My problem is that it occasionally skips a message it=
 should have deleted. I know little of email protocols, but I saw=
 the "Message-ID" tag in the header, and I thought that would do=
 to uniquely identify any email. But there are some emails that=
 *do* seem to have the header and that don't get picked up.=
 Furthermore, there are other occasional emails that *don't* seem=
 have one to begin with (mostly mass-mailings). So, I have been=
 wondering lately: what do "real" email clients use to identify a=
 message? Is it some sort of hash made out of the header tags? Is=
 there a module/script to make such a handle? </FONT></div>
<div>&nbsp;</div>
<FONT FACE=3D"Arial" SIZE=3D3></FONT><div><FONT FACE=3D"Arial"=
 SIZE=3D3>Thanks for your help, </FONT></div>
<div>&nbsp;</div>
<FONT FACE=3D"Arial" SIZE=3D3></FONT><div><FONT FACE=3D"Arial"=
 SIZE=3D3>Pijus</FONT></div>
<div>&nbsp;</div>
<FONT FACE=3D"Arial" SIZE=3D3></FONT><div><FONT FACE=3D"Arial"=
 SIZE=3D3>-- </FONT></div>
<div><FONT FACE=3D"Arial" SIZE=3D3>"Anyone attempting to generate=
 random numbers by deterministic means </FONT><FONT FACE=3D"Arial"=
 SIZE=3D3>is, of course, living in a state of sin." -- John Von=
 Neumann</FONT></div>
</body></html>




From shalehperry@attbi.com  Wed Jul 17 15:52:41 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 17 Jul 2002 07:52:41 -0700 (PDT)
Subject: [Tutor] Re: LHA compression
In-Reply-To: <20020717070217.7906A2F6E4@mercury.sapatmt>
Message-ID: <XFMail.20020717075241.shalehperry@attbi.com>

>       Right away tho' I need to find out if the algo. itself is not patented
or 
> propriety.
> 

is there a perl/ruby/java/whatever module?  That may help in both tracking down
the algo and the legality of it.



From shalehperry@attbi.com  Wed Jul 17 15:54:37 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 17 Jul 2002 07:54:37 -0700 (PDT)
Subject: [Tutor] how to get a unique handle on an email?
In-Reply-To: <ISPFE7OoORYRoOQ9Rjo0003d327@mail.takas.lt>
Message-ID: <XFMail.20020717075437.shalehperry@attbi.com>

> <FONT FACE="Arial" SIZE=3></FONT><div><FONT FACE="Arial" SIZE=3>I recently
> wrote a little script that deletes all the messages sitting in my email
> client's Trash mailbox from the mail server. It uses poplib, and there's
> really nothing to it. </FONT></div>
> <div>&nbsp;</div>
> <FONT FACE="Arial" SIZE=3></FONT><div><FONT FACE="Arial" SIZE=3>My problem is
> that it occasionally skips a message it should have deleted. I know little of
> email protocols, but I saw the "Message-ID" tag in the header, and I thought
> that would do to uniquely identify any email. But there are some emails that
> *do* seem to have the header and that don't get picked up. Furthermore, there
> are other occasional emails that *don't* seem have one to begin with (mostly
> mass-mailings). So, I have been wondering lately: what do "real" email
> clients use to identify a message? Is it some sort of hash made out of the
> header tags? Is there a module/script to make such a handle? </FONT></div>
> <div>&nbsp;</div>
> <FONT FACE="Arial" SIZE=3></FONT><div><FONT FACE="Arial" SIZE=3>Thanks for
> your help, </FONT></div>

gah, kill the html will you please, this is a public list.

Look at rfc822 and the pop rfc whose number escapes me right now.  The answers
are there.



From terjeja@hotmail.com  Wed Jul 17 17:14:59 2002
From: terjeja@hotmail.com (Terje Johan Abrahamsen)
Date: Wed, 17 Jul 2002 16:14:59 +0000
Subject: [Tutor] Fuctions & instances
Message-ID: <F43EtZjbdu0EvK0B04M00012a2c@hotmail.com>

I am trying to get a program to run itself. But it doesn't seem to work. So 
I have to create another program to run the first one. Sometimes it works, 
other times it doesn't. So it is not a stable solution. How can I get this 
to work correct?


-----
import win32com.client
import win32com.client.dynamic
from win32com.client import Dispatch

class divxl:
    xlApp = Dispatch("Excel.Application")
    xlBook = xlApp.Workbooks(1)
    xlSheet = xlApp.Sheets(1)

    xlrad = 1
    func = 0            #Funksjon man ønsker 1) legg sammen med samme 
policynummer

    n = divxl()

    def __init__(self):
        print "Function numbers"
        print " 1) Add rows where there are more than one equals in a 
collumn"
        print " 2) Remove rows that contain/not contain bold fields"
        divxl.func = int(raw_input("Type the function # : "))
        noff.starter()

    def starter(self):
        if divxl.func == 1:
            summer()
        elif divxl.func == 2:
            bold()

    def summer(self):
        kolonne1 = int(raw_input("Collumn# where the equals are : "))
        kolonne2 = int(raw_input("Collumn# where addition should be: "))
        xlrad = 1
        while divxl.xlSheet.Cells(xlrad + 1, kolonne1).Value != None:
            pol1 = divxl.xlSheet.Cells(xlrad, kolonne1).Value
            pol2 = divxl.xlSheet.Cells(xlrad + 1, kolonne1).Value
            if pol1 == pol2:
                divxl.xlSheet.Cells(xlrad, kolonne2).Value = 
divxl.xlSheet.Cells(xlrad, kolonne2).Value + divxl.xlSheet.Cells(xlrad + 1, 
kolonne2).Value
                divxl.xlSheet.Rows(xlrad + kolonne1).Delete()
                xlrad = xlrad - 1
            xlrad = xlrad + 1

    def bold(self):
        boldyn = int(raw_input("Remove bold, '1', keep bold, '2' : "))
        rad = 1
        while divxl.xlSheet.Cells(rad, 1).Value != None:
            if boldyn == 1:
                if divxl.xlSheet.Cells(rad, 1).Font.Bold == 1:
                    divxl.xlSheet.Rows(rad).Delete()
            if boldyn == 2:
                if divxl.xlSheet.Cells(rad, 1).Font.Bold == 0:
                    divxl.xlSheet.Rows(rad).Delete()
            rad = rad + 1

------

The code itself works great. Just does some simple Excel tasks. But, I have 
to write n = divxl(), then I have to write n.starter() for it to work. How 
can I make it start just by creating the instance n=divxl()? From there it 
should start n = starter() automatic? I want the whole thing made by py2exe 
so that others also can use it. Thats not an option.

Usually I have made a script like this (for another program) that run the 
program I want to run:

----------------
import sys
from time import sleep
import acnodate
from acnodate import *

n = acnodate()
n.start()

while 1:
    sleep(0.5)
    n.finnxlpolicy()
    sleep(0.5)
    n.fiex()
    sleep(0.5)
    n.skriv()
    sleep(0.5)

---------------------

But, today that doesn't seem to work. I have no idea why. But I know this is 
not an optimal solution...

Thanks,
Terje

_________________________________________________________________
Join the world’s largest e-mail service with MSN Hotmail. 
http://www.hotmail.com




From wolf_binary@hotmail.com  Wed Jul 17 18:20:52 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Wed, 17 Jul 2002 12:20:52 -0500
Subject: [Tutor] engines
Message-ID: <DAV31KFRJrzdDW6lCPx0000de4b@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_0005_01C22D8C.64A98DA0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hi all,

How does a program engine work?  How do you develope one and how do you =
use it?

Thanks,

Cameron Stoner

------=_NextPart_000_0005_01C22D8C.64A98DA0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2713.1100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hi all,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>How does a program engine work?&nbsp; =
How do you=20
develope one and how do you use it?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Cameron =
Stoner</FONT></DIV></BODY></HTML>

------=_NextPart_000_0005_01C22D8C.64A98DA0--



From ATrautman@perryjudds.com  Wed Jul 17 19:11:25 2002
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Wed, 17 Jul 2002 13:11:25 -0500
Subject: [Tutor] Printing
Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A32F@CORP_EXCHANGE>

All,

I think I found at least a good source for printing formatted documents in
Python in the Windows environment:)

wxPython (part of ActiveState at
http://aspn.activestate.com/ASPN/Downloads/ActivePython/Extensions/) has a
printout class the separates the text from the formatting and allows you to
format the text on the fly. It also handles the communication with the
printer for you. There is also a preview mode. It appears at this time that
both HP LaserJet's and HP Inkjets work well with it.

Thanks 
Alan



From shalehperry@attbi.com  Wed Jul 17 20:17:47 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 17 Jul 2002 12:17:47 -0700 (PDT)
Subject: [Tutor] engines
In-Reply-To: <DAV31KFRJrzdDW6lCPx0000de4b@hotmail.com>
Message-ID: <XFMail.20020717121747.shalehperry@attbi.com>

On 17-Jul-2002 Cameron Stoner wrote:
> Hi all,
> 
> How does a program engine work?  How do you develope one and how do you use
> it?
> 

the term "engine" can mean several things.  It generally refers to the central
control structure of the program.

For instance a "game engine" is the part that controls the way a scene is
rendered, the actions of the participants (human and computer), etc.  In many
ways it is an event loop and in others it resembles a interpreter similar to
python or perl.

Mozilla could be said to have a "rendering engine" which is given data and it
turns into a visual representation.

Hope this helps, if not maybe it will shake loose the real questions.



From dman@dman.ddts.net  Thu Jul 18 00:42:37 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Wed, 17 Jul 2002 18:42:37 -0500
Subject: [Tutor] C++, Java, Python, metrics, etc. (was Re: Re: small program in Python and in C++)
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C728@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C728@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020717234237.GA21006@dman.ddts.net>

--NzB8fVQJ5HfG6fxh
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 16, 2002 at 06:11:54PM +0100, alan.gauld@bt.com wrote:
| Hi Dman,
|=20
| > I thought only ASM needed a line of comment per line of code ;-).
| > Whatever happened to self-documenting code?
|=20
| It's alive and well, but most corporate coding standards=20
| require extensive comment block headers at the top of=20
| each file as well as above each function.

Yeah, those are useful, particularly for the non-obvious functions.

| Thus a 5 line function may have a 15 line header on top!(see our=20
| local example appended at the end...)

15 lines!?  That's a rather low signal:noise ratio.  At least that is
outside the body of the function :-).

| > | In the real world many functions contain 200 plus lines of=20
| > | executable code(*) which means maybe 400-500 lines of text.
| >=20
| > I'm glad I'm not in the "real world" ;-).
|=20
| Sorry, that sounded a bit patronising. A better term might=20
| have been "industrial scale" software projects.=20
| eg Air traffic Control, Nuclear reactors, Telephone exchanges=20
| and the like. (Recall we were talking about C++ projects=20
| in this thread not Python!)

All of my C++ projects were in class.  Hence saying it isn't "real
world" is rather accurate.  Pretty much all the non-school stuff I did
was either for a small java shop (my first co-op) or a non-profit org.
where "if it works that's what counts" (there's only me and another
programmer/admin, and they're switching accounting systems too.  more
than enough work for the two of us and then some :-)).

| > Yeah, I can see 100 lines of
| >     stream << this->foo
|=20
| More usually 100 times:
|=20
|  if (this->foo) || (this->bar){
|       stream << this->foo;
|  }
|=20
| ie 300 lines!
|=20
| > attribute should have its own self-contained serialization function,
|=20
| Could be but for primitive types that makes the files even=20
| bigger and most attributes will be either integers, floats=20
| or strings - ie the things you can store in an RDBMS.
|=20
| > | time consuming and error prone. Jumping to the top of the function=20
| > | is a single keystroke!
| >=20
| > Which keystroke, btw?  It would be helpful if I knew it. =20
|=20
| > I know how to use ctags, but that's quite a few keystrokes=20
| > (depending on function names and polymorphic ussage)
|=20
| It shouldn't be if your ctags is C++ aware...

I didn't know about ctags back when I had my C++ projects, but I used
it for a large Java project.  If there was an abstract class defining
the method "meth", and 3 concrete subclasses, :tselect would list 4
occurences of the tag "meth".

| However ctags doesn't help for the current function,=20

True.

| but [[ should go to the start of a paragraph in text=20
| mode or the start of the current function in C/C++ mode.

Ahh, cool!

| I just tried it and it relies on you putting your opening=20
| brace in the leftmost collumn (Which I do normally so it=20
| works for me  :-) like so:

In vim type ':help [[' and at the bottom of the paragraph about
"section" is a series of maps to handle an indented brace.  I'll be
practicing with this one!

| > | Well written variable declarations should all be commented! :-)
| >=20
| > It shouldn't need a comment, except in the *few* (right? ;-))
| > not-so-obvious cases :-).
|=20
| Not so obvious is rarely the case in my experience. What the=20
| original programmer thinks is obvious very rarely is to somebody=20
| else later! (Of course the fact that modern compilers tend to=20
| allow more than 6 characters in variables helps ;-)

Yeah, I think the number of libraries around now would certainly have
overflowed the 6-character universe a long time ago.

| > | Only if reading the code sequentially, if you are jumping in=20
| > | at random - as is usually the case for maintenance programmers=20
| > THat makes sense.
|=20
| Just to elaborate. The normal mode of operation for a=20
| maintenance programmer with a hot fault is to load up=20
| the executable in the debugger with a core dump(if Unix or MVS)
| and do a stacktrace. They will then navigate up the stack=20
| which means they arrive in the upper level function=20
| wherever the call to the lower level one was made, not=20
| at the entry point..

Yeah, that's what I do when I try running a not-quite-mature app and
it crashes :-).  Then I can submit at least a halfway decent bug
report, and maybe fix or workaround the crash if it is simple enough.

| > | A crash in those circumstances is a good thing! And NULLS help=20
| > | achieve it!
| >=20
| > While I agree here, what if you got a 'NameError' exception instead of
| > 'AttributeError: None object has no member foo' _or_ if the operation
|=20
| We were talking C++ remember. A Name error will be caught at=20
| compile time in C++.

Not if you declared the name at the top of the function :-).  You
won't even get an "uninitialized variable" warning if you initialize
it to NULL.

| > you performed was perfectly valid with None/NULL but that was not the
| > value the variable should have had.
|=20
| There are obviously a few possible cases where this can happen=20
| but to be honest they are very rare. If you think abouit it=20
| most functions that accept a NULL do so only to indicate=20
| that a default value be used instead

Yeah, that is true.  I don't do enough large-scale C/C++ work.  I'll
be doing some more C soon than I have in a long time.

| > | I see the point of wasted resource but not sure how Java/Python=20
| > | helps here. If you initialize the variable to a dummy object you=20
| > Here's an example :
| >=20
| > // C++
| > class Foo
| > {
| > }
| >=20
| > void func()
| > {
| >     Foo local_foo ;
|=20
| Ah yes, non dynamic classes. I forgot about those in C++,=20
| I hardly ever use them. You are quite right, in those cases=20
| premature initialisation would waste resource.

Yeah, you trade off the convenience of stack-automatic memory
management for premature initialization (or declaring it later so that
the init isn't premature).

Another fun effect of is the ability to subvert the Singleton pattern.
Alex Martelli has explained on c.l.p how the copy constructor (which
the compiler automatically creates for you) can be used to copy a
singleton to a stack-allocated instance of the class.  Oops.  (just
one of his reasons for preferring the Flyweight-Proxy pattern as a
replacement for Singleton)

| > One way to avoid it is to use a pointer, and then allocate the object
| > using 'new' when you need it.  Then you must remember to 'delete' it
| > afterwards.  Also, supposedly, the heap is slower than the stack.
|=20
| I always use dymanic objects in C++ and the performance=20
| overhead is minimal. The loss of polymorphism in statically=20
| declared classes is much more serious IMHO!
|=20
| > (I also like python's ability to get rid of a local ('del') after
| > you're done with it.  It helps prevent you from erroneously re-using
| > the old data later on -- which I've done before!)
|=20
| Yes memory management is a perennial problem in C/C++, it's about
| the only good thing I have to say about Java :-)

Mmm hmm.  However, early JVMs (eg jdk 1.1.8) handled the gc so poorly
that it was effectively the same as just never freeing anything.

| > Surely if you can actually and accurately quantize the effect, then
| > you can make a better argument than aesthetics. =20
|=20
| Unfortunately there is a wealth of objective collected data about
| maintenance programming. Its always seem as a cost rather than=20
| revenue earner so the bean counters monitor it closely. Sadly=20
| the mainsatream software community seems to ignore it by and=20
| large! Possibly because it invariable originates in industry=20
| rather than  academia? No surely not... :-)

Of course not.  :-).  (actually, I don't know)  I do know that
comp.lang.python has periodic threads regarding precisely which coding
style is more effective, and they always seem to go 'round and 'round
in circles.

| > benefits of each method and choose the best one.  Since quantization
| > isn't a viable option, experience is the next best decider. =20
|=20
| I'm interested in why you think quantization is hard?=20
| Measuring time to fix, lines changed, code quality metrics=20
| etc is part and parcel of every maintenance teams work that=20
| I've ever worked with (erm, thats only 3, all in the same=20
| organisation BTW!!)

LOC depends on many factors that tend to be project-specific.  For
example, the programming language used, the libraries used (the
convenience of their APIs), and the design of the system all
contributed.  Not to mention the fact that "line" is not well-defined
(across the field).  If LOC is weighted too heavily (eg programmer
performance reviews) then the programmers will have a tendency to
skew it.

Code quality is also hard to measure quantitatively.  The measurements
I've seen (McCabe Cyclomatic Number and something else I forget)
didn't seem to be very effective.  They also seemed to require more
effort than writing the software in the first place!

The main thing I learned in my "Software Process and Product Metrics"
course is that software is hard to measure.  (it was also a boring
course and the prof. didn't help that at all)

I'm sure that a large enough organization (neither of the orgs I
worked for qualify) will have a defined process and metrics used to
keep the paperwork flowing, but I am skeptical as to their real
usefulness.

| > My comments here aren't intended as arguments, just clarification of
| > what I had said before and of the "other" perspective.  (and some of
| > it is meant to be a bit humorous)
|=20
| Me too, I must apologize if my earliuer post sounded a bit=20
| pompous, its an unfortunate tendency I have. They were meant=20
| entirely as my personal experience of maintaining large scale=20
| projects. (The first was 3,500,000 lines of C/C++, the second=20
| 500,000 lines of C++ and the 3rd 350,000 lines of COBOL)

I understood your comments to be based on your work experience,
whereas I don't have that.

The largest C++ project I've worked on had 4 developers with 3,000
lines hand-coded and 3,100 lines generated by glade--.  (where 1
semicolon =3D=3D 1 line, and that was an after-the-fact "I wonder how big
this thing is" measurement)  I haven't measured any of the other
projects I worked on, which were mainly java or "trivial".  I did work
on a few sizeable java projects, but most were so short lived that
they had no maintenance (school projects.  once you have a grade,
you're done.)  At my last job I worked on the most significant java
project I have worked on, but we didn't measure it for size.  At my
current job I have mostly been pulling things together, and also
making a couple of zope-based web apps.  They're not huge, though, and
it would be hard to measure LOC with the mix of python scripts, page
templates, and SQL.  An LOC measurement would also have no relation to
your projects since zope already provides lots and lots of glue for
the bits that I actually wrote.

| Hopefully there are some points of interest to the general=20
| Python community in here too, hidden amongst the rantings :-)

Yes, hopefully.

| That has to be filled in for every function regardless=20
| of how small... A similar but bigger template is filled=20
| in at the top of every file includeiong the full RCS log...

RCS?  Don't you mean CVS? ;-).  You don't put all your files in one
big directory and work on them one person at a time, now do you?
(I'm just picking on the limitations of RCS that CVS solves)

-D

--=20
Emacs is a nice operating system, it lacks a decent editor though
=20
http://dman.ddts.net/~dman/

--NzB8fVQJ5HfG6fxh
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj02AOwACgkQO8l8XBKTpRQPlgCgn470iH/H7wpjC6eJB5Cic2/8
mU0AoJ5Bzsj77PADow9PjWjTU+q4L1uc
=LDfC
-----END PGP SIGNATURE-----

--NzB8fVQJ5HfG6fxh--



From alan.gauld@bt.com  Thu Jul 18 17:50:48 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 18 Jul 2002 17:50:48 +0100
Subject: [Tutor] engines
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C74C@mbtlipnt02.btlabs.bt.co.uk>

------_=_NextPart_001_01C22E7B.44C45D90
Content-type: text/plain; charset="iso-8859-1"

>  How does a program engine work?   
 
I've heard the phrase engine used in many context in programming but never 
any standard. I think you need to give us a bit more context to answer
sensibly.
 
>  How do you develope one and how do you use it? 
 
Depends what kind of engine you mean.
In one sense the python interpreter can be considered a program engine....
 
Alan g

------_=_NextPart_001_01C22E7B.44C45D90
Content-type: text/html; charset="iso-8859-1"

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">


<META content="MSHTML 5.50.4807.2300" name=GENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=#ffffff>
<DIV><FONT face=Arial><FONT size=2><SPAN class=020415516-18072002><FONT 
face="Courier New" color=#0000ff>&gt; &nbsp;</FONT></SPAN>How does a program 
engine work?&nbsp;&nbsp;<SPAN class=020415516-18072002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=020415516-18072002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=020415516-18072002>I've heard the 
phrase engine used in many context in programming but never 
</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=020415516-18072002>any standard. 
I think you need to give us a bit more context to answer 
sensibly.</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=020415516-18072002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=020415516-18072002><FONT 
face="Courier New" color=#0000ff>&gt; </FONT>&nbsp;</SPAN>How do you develope 
one and how do you use it?<SPAN class=020415516-18072002><FONT 
face="Courier New" color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><SPAN class=020415516-18072002><FONT face=Arial size=2>Depends what kind of 
engine you mean.</FONT></SPAN></DIV>
<DIV><SPAN class=020415516-18072002><FONT face=Arial size=2>In one sense the 
python interpreter can be considered a program engine....</FONT></SPAN></DIV>
<DIV><SPAN class=020415516-18072002><FONT face=Arial 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=020415516-18072002><FONT face=Arial size=2>Alan 
g</FONT></SPAN></DIV></BODY></HTML>

------_=_NextPart_001_01C22E7B.44C45D90--



From slime@vsnl.net  Wed Jul 17 04:02:35 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Wed, 17 Jul 2002 08:32:35 +0530
Subject: [Tutor] Sending email in Python...
In-Reply-To: <Pine.LNX.4.44.0207150034480.23670-100000@hkn.eecs.berkeley.edu>
References: <FA9060A56B68D511947F00A024B2D40001952162@agf3uex01.lasalle.navy.mil> <Pine.LNX.4.44.0207150034480.23670-100000@hkn.eecs.berkeley.edu>
Message-ID: <20020717030235.GA8453@localhost.localdomain>

Hi,

On Mon, 15 Jul 2002 Danny Yoo spewed into the ether:
> On Sun, 14 Jul 2002, Belan, Martin ET3 (AGF-3) wrote:
> 
> >     I was wondering how one would go about sending an email using
> > python.  I am currently running python 2.2 under a Windows NT OS, which
> > utilizes a proxy server.  If anyone out there could aid my quest until I
> > am able to procure some decent documentation I would be much obliged.
> 
> Hi Belan,
> 
> You may find the 'smtplib' module appropriate --- SMTP is the protocol
> that computers use to send off email.

    Here is a module that is a wrapper around the MimeWriter and smtplib
modules (I think I posted the link sometime back as well), which I find
useful to send MIME messages :

    http://www.symonds.net/~prahladv/files/MailMsg.py

    Also, If you are interested, and you have a fairly recent python,
you could look up the 'email' module to construct your mail.

[-- snippity --]
> The docs also come with an example, so it should be enough to get you
> started.  However, I'm not quite sure how it works with a proxy, so
> perhaps someone else on the Tutor list can talk more about that.

    I'm just guessing, but shouldn't it suffice to set the $http_proxy
variable in the shell, or, do this :

    os.environ['http_proxy'] = 'http://www.proxy.com:3128'

HTH,

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

The groundhog is like most other prophets; it delivers its message and then
disappears.



From alan.gauld@bt.com  Thu Jul 18 18:06:18 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 18 Jul 2002 18:06:18 +0100
Subject: [Tutor] C++, Java, Python, metrics, etc.
 (was Re: Re: small program in Python and in C++)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C74D@mbtlipnt02.btlabs.bt.co.uk>

> RCS?  Don't you mean CVS? ;-).  You don't put all your files in one
> big directory and work on them one person at a time, now do you?
> (I'm just picking on the limitations of RCS that CVS solves)

Actually I do mean RCS because for a maintenance team 
parallel development is rarely necessary. To maintain 
3,500,000 lines of C++ we only had 8 of us, one being 
the team lead (me, who wasn't officially allowed anywhere 
near code :-) and another the build manager/regression 
tester. So only 6 programmers per se, usually working 
independantly on their own bugs/changes. Since we 
released patches at least once a week the extra features 
of CVS were rarely needed and the warning of parallel 
working that RCS gave was a positive advantage.

Nowadays we actually use much heavier weight tools 
like ClearCase and Continuus ($$$$$!) which incorporate 
change control and fault reporting tools along with 
version control.

In the same way the capture of metrics is all done by 
commercial tools bought for the purpose and fully 
integrated with the CM tool. Thus we can ask it to 
generate the metrics for release X.Y and it will 
examine the change logs and dump the stats....

The advantage of working in a large organisation is they 
can afford such luxuries - in fact they become cost 
effective. The disadvantages are obvious to readers of 
Dilbert....

Alan g



From erikprice@mac.com  Thu Jul 18 16:28:25 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 18 Jul 2002 11:28:25 -0400
Subject: [Tutor] when to use exceptions
Message-ID: <008535DA-9A63-11D6-B07C-00039351FE6A@mac.com>

Where do you draw the line of when to use an exception and when not to 
use an exception?  It seems that you could go on trying to catch 
exceptions for every conceiveable problem... but you would spend all of 
your time writing exception-catching code, right?

I'm asking in a theoretical sense, I don't have specific code that I'm 
curious about.

Thanks for your thoughts,


Erik




From scott@zenplex.com  Thu Jul 18 15:23:55 2002
From: scott@zenplex.com (Scott Comboni)
Date: 18 Jul 2002 10:23:55 -0400
Subject: [Tutor] General question on Python vs PHP web programming
Message-ID: <1027002235.1912.21.camel@scott.zenplex.com>

I have been writing in Python for about a year or so and by no means am
I a programmer.  I recently have a begun looking into Webware for
writing some web apps and I was curious if someone can just tell me what
some of the advantages of using Python over PHP?  The one advantage I
have is that I'm familiar enough with Python. PHP would be all new. 

Again just looking for some general input.

S-










From shalehperry@attbi.com  Thu Jul 18 18:40:20 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Thu, 18 Jul 2002 10:40:20 -0700 (PDT)
Subject: [Tutor] when to use exceptions
In-Reply-To: <008535DA-9A63-11D6-B07C-00039351FE6A@mac.com>
Message-ID: <XFMail.20020718104020.shalehperry@attbi.com>

On 18-Jul-2002 Erik Price wrote:
> Where do you draw the line of when to use an exception and when not to 
> use an exception?  It seems that you could go on trying to catch 
> exceptions for every conceiveable problem... but you would spend all of 
> your time writing exception-catching code, right?
> 
> I'm asking in a theoretical sense, I don't have specific code that I'm 
> curious about.
> 
> Thanks for your thoughts,
> 

It depends on the "professional" appearance of the code I am working on.  For
instance if I just write:

<code>
#!/usr/bin/python

def cool_stuff(input):
  # do lots of cool stuff here

while 1:
  cool_stuff(...)
</code>

Then when I run it decide to use Ctrl-C to stop it I get a python traceback and
a KeyboardInterrupt exception.  This may be ok for a devel script but looks
real bad to give to end users.  So I end up with a top level exception handler
which attempts to be more clean about it and not show the user the python
traceback.



From Michael Montagne <montagne@boora.com>  Thu Jul 18 18:49:44 2002
From: Michael Montagne <montagne@boora.com> (Michael Montagne)
Date: Thu, 18 Jul 2002 10:49:44 -0700
Subject: [Tutor] Parsing HTML
Message-ID: <20020718174944.GA4789@boora.com>

Here's my problem.  I want to extract a players score from the live
leaderboard at the british open.  The URL is
http://scores.golfweb.com/scoreboards/britishopen/2002/leaderboard/

I have some players listed in a text file.
For each player in the text file, I need to extract his total score.
It appears the total score is 3 lines below the line that has his name.

How can I get this info?




-- 
  Michael Montagne  [montagne@boora.com]   503.226.1575 
--    



From glingl@aon.at  Thu Jul 18 18:53:55 2002
From: glingl@aon.at (Gregor Lingl)
Date: Thu, 18 Jul 2002 19:53:55 +0200
Subject: [Tutor] engines
References: <DAV31KFRJrzdDW6lCPx0000de4b@hotmail.com>
Message-ID: <3D3700B3.7040602@aon.at>

This is a multi-part message in MIME format.
--------------020609000405030103040107
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit

Hi Cameron, hi Pythonistas!

By accident I'm just working on a tiny (and well known) game
(see attachment!) It has an example of a game-engine built in -
or at least what I could imagine this could be.
It's designed to serve for some educational meterial I'm
going to prepare and it's not finished yet - so it's not well
documented.I'm learning more than I'm programming, at the moment.  

Nevertheless it may serve as an example, Cameron was searching for
in his posting.

Of course I'm interested to know, if you all consider it a
useful example.

Specifically I use a pattern for implementing a keyboard-controlled
animation, which I would like to know if it's the standard way doing
things like this with Tkinter or if there are better ways to do it.

It goes like this:

1.)  a function like

eventlist = []
def taste(event):
    key = event.keysym
    if key in goodkeys:
        self.eventlist.append(key)

is bound to the GUI and maintains a list of
events, which serve to control the

2.) animation, which runs in some canvas:

def run():
    taste = None
    # 1. suck one command from the eventlist
    if self.eventlist:
         taste = self.eventlist[0]
         self.eventlist = self.eventlist[1:]
    # 2. then process some sort of finite state machine:
    if state == "start":
         if taste == ...:
              * do this *
         elif taste == ...:
              * do that *
         < if necessary change state >
    elif state = "running":
         <  do other stuff depending on commands
            waiting in eventlist >
    ....

    elif state = "over":
          <etc..   >

    # 3.  finally
    canvas.update()
    canvas.after(100, run)

Have fun studying it ( and perhaps even playing it ;;;-) ).
Critical comments and suggestions for improvement of the code
are VERY welcome.

With kind regards

Gregor

Cameron Stoner schrieb:

> Hi all,
>  
> How does a program engine work?  How do you develope one and how do 
> you use it?
>  
> Thanks,
>  
> Cameron Stoner




--------------020609000405030103040107
Content-Type: text/plain;
 name="snake.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="snake.py"

""" snake - OOP training   (V. OOP12)
    author: gregor lingl, vienna.    email:  glingl@aon.at   """
from Tkinter import *
from Canvas import Rectangle
import sys, random

class Spielbrett(Canvas):
    def __init__(self, root, NX, NY, feldbreite=12, **kwargs):
        Canvas.__init__(self, root, kwargs)
        w,h = NX*feldbreite, NY*feldbreite
        self.config(width=w+2, height=h+2, bg = 'yellow')
        self.grid = {}
        for zeile in range(NY):
            for spalte in range(NX):
                x0 = 2 + spalte * feldbreite
                y0 = 2 + zeile  * feldbreite
                x1 = x0 + feldbreite
                y1 = y0 + feldbreite
                r = Rectangle(self, x0, y0, x1, y1,
                              fill='yellow', outline='yellow' )
                self.grid[(spalte,zeile)] = r
    def set(self,feld,farbe):
        self.grid[feld]['fill'] = farbe

class Snake:
    def __init__(self, size):
        self.N = size
        self.futter = None
        self.reset()
    def reset(self):
        self.schlange = [(self.N/2,self.N/2)]
        selfFutter = None
        self.setzeFutter()
        self.richtung = None
        self.alive = 1         
    def setzeFutter(self):
        while not self.futter or self.futter in self.schlange:
            self.futter = (random.randrange(self.N), random.randrange(self.N))
    def getscore(self):
        return "Score: " + str(max(0,len(self.schlange)-4))        
    def schwanzAb(self):
        self.schlange = self.schlange[1:]
    def kopfDran(self,feld):
        self.schlange.append(feld)
    def neuesFeld(self):
        x,y = self.schlange[-1]
        if self.richtung == 'Up':
            y=y-1
        elif self.richtung == 'Down':
            y=y+1
        elif self.richtung == 'Left':
            x=x-1
        elif self.richtung == 'Right':
            x=x+1
        else:
            return None
        return (x,y)
    def amBrett(self, neu):
        x,y=neu
        return 0 <= x < self.N and 0 <= y < self.N
    def schritt(self, neueRichtung):
        changed = {}
        if neueRichtung:
            if (neueRichtung,self.richtung) not in (('Up','Down'),('Down','Up'),
                                                ('Right','Left'),('Left','Right')):
                self.richtung = neueRichtung
        neu = self.neuesFeld()
        # Fall 1: angestossen
        if not self.amBrett(neu) or neu in self.schlange:
            self.alive = 0
            for glied in self.schlange:
                changed[glied]='black'
        # Fall 2: Futter gefunden
        elif neu == self.futter:
            self.kopfDran(neu)
            changed[neu]='red'
            self.setzeFutter()
            changed[self.futter]='blue'
        # Fall 3: normaler Schritt
        else:
            if len(self.schlange) > 3:
                changed[self.schlange[0]]='yellow'
                self.schwanzAb()
            self.kopfDran(neu)
            changed[neu]='red'
        return changed

class SnakeEngine:
    def __init__(self, N):
        self.N = N
        root = Tk()
        root.title("SNAKE")
        root.bind('<KeyPress>', self.taste)
        self.brett = Spielbrett(root,N,N)
        self.brett.pack()
        self.scorelabel = Label(root,width=22,text="",font=("Courier",14,"bold"),fg='red')
        self.hintlabel  = Label(root,width=22,text="",font=("Courier",14,"normal"))
        self.scorelabel.pack()
        self.hintlabel.pack()
        self.schlange = Snake(N)
        self.reset()
    def taste(self,event):
        key = event.keysym
        if key == 'Return':
            sys.exit(0)
        if key in ['Up','Down','Left','Right','space']:
                self.eventlist.append(key)
    def reset(self):
        for feld in self.brett.grid:
            self.brett.set(feld,'yellow')
        self.eventlist = []
        self.state = "waiting"
        self.schlange.reset()
        self.brett.set(self.schlange.schlange[0],'red')
        self.brett.set(self.schlange.futter,'blue')
        self.brett.update()
        self.hintlabel.config(text="Steuerung: Pfeiltasten")
        self.scorelabel.config(text=self.schlange.getscore())
    def run(self):
        changed = {}
        taste = None
        if self.eventlist:
            taste = self.eventlist[0]
            self.eventlist = self.eventlist[1:]
        if self.state == "waiting":
            if taste in ['Up','Down','Right','Left']:
                self.state = "running"
        if self.state == "running":
            if taste in ['Up','Down','Right','Left', None]:
                changed = self.schlange.schritt(taste)
                self.scorelabel.config(text=self.schlange.getscore())
            if not self.schlange.alive:
                self.state="over"
                self.hintlabel.config(text="Neues Spiel: Leertaste")
        elif self.state == "over":
            if taste == 'space':
                self.reset()
        for feld in changed:
            self.brett.set(feld, changed[feld])
        self.brett.update()
        self.brett.after(100, self.run)
       
SnakeEngine(21).run()
mainloop()
--------------020609000405030103040107--





From trivas7@rawbw.com  Thu Jul 18 03:51:37 2002
From: trivas7@rawbw.com (Thomas Rivas)
Date: Wed, 17 Jul 2002 19:51:37 -0700
Subject: [Tutor] lost my IDLE
Message-ID: <200207180238.g6I2c7087335@mail0.rawbw.com>

Hi, folks--

In the process of trashing the IDLEfork that overwrote IDLE from VPython I 
lost it. Any way I can get it one w/o re-installing Python 2.2? IDLEfork 
couldn't find a config file from /usr/lib/ python2.2 so it not much use to 
me. I should have read up more on the VPython Installation.

Thanks.



From virketis@post.harvard.edu  Thu Jul 18 08:35:50 2002
From: virketis@post.harvard.edu (Pijus Virketis)
Date: Thu, 18 Jul 2002 10:35:50 +0300
Subject: [Tutor] how to get a unique handle on an email?
In-Reply-To: <XFMail.20020717075437.shalehperry@attbi.com>
Message-ID: <ISPFE7u6WY9IuXZ2y2F00047722@mail.takas.lt>

<HTML><HEAD>
</HEAD>
<BODY>
<div>&nbsp;</div>
<FONT FACE=3D"Arial" SIZE=3D3></FONT><div><FONT FACE=3D"Arial" SIZE=3D3=
 COLOR=3D"#800000">>>So, I have been</FONT></div>
<div><FONT FACE=3D"Arial" SIZE=3D3 COLOR=3D"#800000">>>wondering=
 lately: what do "real" email clients use to identify=
 a</FONT></div>
<div><FONT FACE=3D"Arial" SIZE=3D3 COLOR=3D"#800000">>>message? Is it=
 some sort of hash made out of the header tags? Is</FONT></div>
<div>&nbsp;</div>
<FONT FACE=3D"Arial" SIZE=3D3 COLOR=3D"#000080"></FONT><div><FONT=
 FACE=3D"Arial" SIZE=3D3 COLOR=3D"#000080">>Look at rfc822 and the pop=
 rfc whose number escapes me right now.</FONT></div>
<div><FONT FACE=3D"Arial" SIZE=3D3 COLOR=3D"#000080">>The answers are=
 there.</FONT></div>
<div>&nbsp;</div>
<FONT FACE=3D"Arial" SIZE=3D3 COLOR=3D"#000080"></FONT><div><FONT=
 FACE=3D"Arial" SIZE=3D3>Hm ... Well, I looked at both. RFC822=
 (whoever came up with this </FONT><FONT FACE=3D"Arial"=
 SIZE=3D3>elegant naming scheme? :)) says that "message-id" is=
 indeed a unique, machine-readable identification for an email.=
 Unfortunately, it says that this tag is *optional*! I have=
 myself noticed, that some messages don't have one. Nothing else=
 in 822 or 1939 (POP3) jumps out at me as having the needed=
 qualities. So, I guess the only option remaining is a=
 combination of name, subject and date, and keeping my fingers=
 crossed that important emails don't arrive too close to each=
 other. ;)</FONT></div>
<div>&nbsp;</div>
<FONT FACE=3D"Arial" SIZE=3D3></FONT><div><FONT FACE=3D"Arial"=
 SIZE=3D3>Cheers, </FONT></div>
<div>&nbsp;</div>
<FONT FACE=3D"Arial" SIZE=3D3></FONT><div><FONT FACE=3D"Arial"=
 SIZE=3D3>Pijus </FONT></div>
<div><FONT FACE=3D"Arial" SIZE=3D3><br>
</FONT><br></div>
<div><FONT FACE=3D"Arial" SIZE=3D3>-- </FONT><br></div>
<div><FONT FACE=3D"Arial" SIZE=3D3>"Anyone attempting to generate=
 random numbers by deterministic means </FONT><FONT FACE=3D"Arial"=
 SIZE=3D3>is, of course, living in a state of sin." -- John Von=
 Neumann</FONT><br></div>
</body></html>




From yuenm@cpsc.ucalgary.ca  Thu Jul 18 05:07:19 2002
From: yuenm@cpsc.ucalgary.ca (Mike Yuen)
Date: Wed, 17 Jul 2002 22:07:19 -0600 (MDT)
Subject: [Tutor] Loopy question
Message-ID: <Pine.SOL.4.44.0207172203500.44372-100000@csc>

This is a real newbie question.
I got a question about a step in a loop.  I want to make my step really
small for a problem i'm testing.  However, the interpreter says my step in
the for loop (0.01) is a zero step for range.

Now, I tried to make a variable a real and assign it a 0.01 value but it
didn't seem to work either.
Here's the exact error I get (hopefully you can provide a bit of insight):

Traceback (most recent call last):
  File "2.py", line 6, in ?
    for x in range(2, 5, 0.01):
ValueError: zero step for range()


for x in range(2, 5, 0.01):
        for loop in range (1, 7, 2):
                result =  ((x-1)**loop) / (loop*((x+1)**loop))
                sum = result + sum
        answer = 2 * sum
        print "X: ", x, " ", "Answer: ", answer
        sum = 0

Thanks,
Mike






From yduppen@xs4all.nl  Thu Jul 18 20:20:40 2002
From: yduppen@xs4all.nl (Yigal Duppen)
Date: Thu, 18 Jul 2002 21:20:40 +0200
Subject: [Tutor] how to get a unique handle on an email?
In-Reply-To: <ISPFE7u6WY9IuXZ2y2F00047722@mail.takas.lt>
References: <ISPFE7u6WY9IuXZ2y2F00047722@mail.takas.lt>
Message-ID: <200207182120.40440.yduppen@xs4all.nl>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Thursday 18 July 2002 09:35, Pijus Virketis wrote:
[a lot of HTML encoded stuff, stating that the suggested RFCs only tell there 
is an optional message-id part]

Hi,
The following site contains an IETF draft with a recommendation on how to 
generate unique message IDs (and even other IDs):

http://www.newsreaders.com/tech/draft-ietf-usefor-msg-id-alt-00

As for the HTML in your e-mail: please don't do that! Turning off all mark-up 
will significantly improve your chances of getting an answer.

Regards,
YDD
- -- 
.sigmentation Fault
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE9NxUILsKMuCf5EdwRArELAKDCf2vN4F4oJh0MC7NXEmEagjHs2QCfUBDR
s/odlLpRTW92vO1W4MF+woM=
=6iVv
-----END PGP SIGNATURE-----




From yduppen@xs4all.nl  Thu Jul 18 20:30:57 2002
From: yduppen@xs4all.nl (Yigal Duppen)
Date: Thu, 18 Jul 2002 21:30:57 +0200
Subject: [Tutor] Loopy question
In-Reply-To: <Pine.SOL.4.44.0207172203500.44372-100000@csc>
References: <Pine.SOL.4.44.0207172203500.44372-100000@csc>
Message-ID: <200207182130.57228.yduppen@xs4all.nl>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Thursday 18 July 2002 06:07, Mike Yuen wrote:
> This is a real newbie question.
> I got a question about a step in a loop.  I want to make my step really
> small for a problem i'm testing.  However, the interpreter says my step in
> the for loop (0.01) is a zero step for range.

That's correct. 
The interpreter tries to evaluate the step to an integer, something you cannot 
influence. And since int(0.01) == 0, range complains.

So you basically have two options:
1) step like you would step 20 years ago
2) use generators (but only for python2.2)

Example 1)

x = 2
while x < 5:
	print x 	# or whatever you want here :)
	x += 0.01


Example 2)
(more reusable, much nicer)

def frange(start, stop, step=1):
	"""Returns an iterator, just like xrange, that accepts floating point
	steps.
	"""
	x = start
	while x < stop:
		yield x
		x += step


for x in frange(2, 5, 0.01):
	print x



I personally prefer the second option for the following reasons:
*) the counting complexity is hidden away in the frange function
*) the entire loop looks much more pythonic
However, this example only works in python2.2 (and above); in python2.2 you 
_must_ put an "from __future__ import generators" statement at the beginning 
of your script.

YDD
- -- 
.sigmentation Fault
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE9NxdxLsKMuCf5EdwRAjc2AKCDWgj7dCeJtACTYfDjIf0lijvKhACgpgn+
czBnraVYUtABnzPZ3cX8Le8=
=o+ZU
-----END PGP SIGNATURE-----




From glingl@aon.at  Thu Jul 18 21:45:43 2002
From: glingl@aon.at (Gregor Lingl)
Date: Thu, 18 Jul 2002 22:45:43 +0200
Subject: [Tutor] engines - minor typo in snake
References: <DAV31KFRJrzdDW6lCPx0000de4b@hotmail.com> <3D3700B3.7040602@aon.at>
Message-ID: <3D3728F7.2010503@aon.at>

Gregor Lingl schrieb:

> Hi Cameron, hi Pythonistas!
>
> By accident I'm just working on a tiny (and well known) game
> (see attachment!) It has... 

a minor typo built-in (as it happens sometimes with work in progress),
which hinders creation of new food when a new game restarts -
and uses the old one --- poor snake!!:

line 32:

        selfFutter = None

should read (of course):

        self.Futter = None

sorry for the inconvenience
Gregor






From marcolinux@linuxbr.com.br  Thu Jul 18 20:10:00 2002
From: marcolinux@linuxbr.com.br (Marc)
Date: Thu, 18 Jul 2002 16:10:00 -0300
Subject: [Tutor] engines
In-Reply-To: <3D3700B3.7040602@aon.at>
References: <DAV31KFRJrzdDW6lCPx0000de4b@hotmail.com> <3D3700B3.7040602@aon.at>
Message-ID: <20020718191000.GA7540@marcolab.proconet>

Gregor Lingl (glingl@aon.at) wrote:

> Hi Cameron, hi Pythonistas!

Ola, Gregor...
> 
> By accident I'm just working on a tiny (and well known) game
> (see attachment!) It has an example of a game-engine built in -
> or at least what I could imagine this could be.

Very nice!!

> Of course I'm interested to know, if you all consider it a
> useful example.

Sure I am.But...

> Have fun studying it ( and perhaps even playing it ;;;-) ).
> Critical comments and suggestions for improvement of the code
> are VERY welcome.

A suggestion:
I noticed that you named variables with english/german words.
Well, I can barely read english, let alone german.
So, can u send me a translated version? *grin*.
Maybe post it on list again.Im sure several people will be interested
in your code.
> 
> With kind regards
> 
> Gregor

Thanks

-- 
I SeE NeRD pEoPle.
.:: MarcoLinux ::.



From Michael Montagne <montagne@boora.com>  Thu Jul 18 23:33:36 2002
From: Michael Montagne <montagne@boora.com> (Michael Montagne)
Date: Thu, 18 Jul 2002 15:33:36 -0700
Subject: [Tutor] Line in a file
Message-ID: <20020718223336.GB6188@boora.com>

How do I go directly to an exact line number in a file?


-- 
  Michael Montagne  [montagne@boora.com]   503.226.1575 
--    



From erikprice@mac.com  Fri Jul 19 00:24:01 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 18 Jul 2002 19:24:01 -0400
Subject: [Tutor] Line in a file
In-Reply-To: <20020718223336.GB6188@boora.com>
Message-ID: <714E1692-9AA5-11D6-AE60-00039351FE6A@mac.com>

On Thursday, July 18, 2002, at 06:33  PM, Michael Montagne wrote:

> How do I go directly to an exact line number in a file?

Well, I was trying to figure this one out for ya as an exercise, but I 
got stumped.  So in trying answer one question, another came up.  Can 
anyone tell me what's wrong here?

 >>> f = open('./sampletext.txt')			# open a file
 >>> line = f.readline()					# read a line
 >>> line								# print it
'this is line 1\n'
 >>> line2 = f.readline()				# read another line relative
 >>> line2								# to where we left off, print it
'this is line 2\n'
 >>> f.tell()							# what position are we at?
30L
 >>> f.seek(0)							# go back to the beginning of f
 >>> f.tell()							# make sure we're at the beginning
0L
 >>> i                       			# we set i to 0 earlier
0
 >>> for line in f.xreadlines():			# xreadlines() sequentially reads
...   i = i + 1						# lines, so this is one way to get
...   if (i == 3):						# a certain line from a file
...     print line						# (in this case line 3)
...
line 3 is high as my knee

 >>> f.tell()							# where are we now?
86L
 >>> f.seek(0)							# go back to the beginning of f
 >>> f.tell()							# double check
0L
 >>> def printLine(fh, num):				# let's make code reuseable
...   c = 0
...   for line in fh.xreadlines():
...     c = c + 1
...     if (line == num):
...       fh.seek(0)					# resets file pointer
...       return line					# returns the line we want
...
 >>> data = ''							# initialize a container variable
 >>> data = printLine(f, 2)				# try out our function
 >>> data								# nothing in the container!
 >>> print data						# nothing!
None
 >>>

Why doesn't this work?


Erik




From kalle@lysator.liu.se  Fri Jul 19 00:29:29 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Fri, 19 Jul 2002 01:29:29 +0200
Subject: [Tutor] Line in a file
In-Reply-To: <714E1692-9AA5-11D6-AE60-00039351FE6A@mac.com>
References: <20020718223336.GB6188@boora.com> <714E1692-9AA5-11D6-AE60-00039351FE6A@mac.com>
Message-ID: <20020718232929.GB1090@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Erik Price]
> Well, I was trying to figure this one out for ya as an exercise, but
> I got stumped.  So in trying answer one question, another came up.
> Can anyone tell me what's wrong here?
[...]
> >>> def printLine(fh, num):	# let's make code reuseable
> ...   c = 0
> ...   for line in fh.xreadlines():
> ...     c = c + 1
> ...     if (line == num):
[...]

This should be c == num, not line == num.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9N09VdNeA1787sd0RAvasAKCTHMxmlP1aQ55Edkp9g1qszHwCngCfWitf
6668ZD1/PTwNRkpvoD8+hik=
=ZxIF
-----END PGP SIGNATURE-----



From Michael Montagne <montagne@boora.com>  Fri Jul 19 00:55:06 2002
From: Michael Montagne <montagne@boora.com> (Michael Montagne)
Date: Thu, 18 Jul 2002 16:55:06 -0700
Subject: [Tutor] Sub
Message-ID: <20020718235505.GA7048@boora.com>

Ok,
I'm getting close now.  I've found the line and now I need to extract
the score.
scoreline='<td><font class="be">-4</font></td>' #the line I wanted
s='<td><font class="be">(.*)</font></td>'
e.sub(s,'\1',scoreline)

This should give me '-4' but it gives me \x01.  What is that?

I know I'm close!!

-- 
  Michael Montagne  [montagne@boora.com]   503.226.1575 
--    



From Michael Montagne <montagne@boora.com>  Fri Jul 19 01:09:32 2002
From: Michael Montagne <montagne@boora.com> (Michael Montagne)
Date: Thu, 18 Jul 2002 17:09:32 -0700
Subject: [Tutor] Sub
In-Reply-To: <20020718235505.GA7048@boora.com>
References: <20020718235505.GA7048@boora.com>
Message-ID: <20020719000932.GF7048@boora.com>

>On 18/07/02, from the brain of Michael Montagne tumbled:

> Ok,
> I'm getting close now.  I've found the line and now I need to extract
> the score.
> scoreline='<td><font class="be">-4</font></td>' #the line I wanted
> s='<td><font class="be">(.*)</font></td>'
> e.sub(s,'\1',scoreline)
> 
> This should give me '-4' but it gives me \x01.  What is that?
> 
> I know I'm close!!
> 

It should be  re.sub(s,"\\1",scoreline)

Back in business!!


-- 
  Michael Montagne  [montagne@boora.com]   503.226.1575 
--    



From scot@possum.in-berlin.de  Fri Jul 19 04:39:32 2002
From: scot@possum.in-berlin.de (Scot W. Stevenson)
Date: Fri, 19 Jul 2002 05:39:32 +0200
Subject: [Tutor] Why x+=y instead of x=x+y?
In-Reply-To: <200207182130.57228.yduppen@xs4all.nl>
References: <Pine.SOL.4.44.0207172203500.44372-100000@csc> <200207182130.57228.yduppen@xs4all.nl>
Message-ID: <200207190539.32916.scot@possum.in-berlin.de>

Hello Yigal,=20

While reading your post on "Loopy Questions" I noticed these lines:

> =09x +=3D 0.01
>     x +=3D step

Now I know this is shorthand for "x =3D x+0.01" and "x =3D x+step", but I=
 have=20
always wondered what the point is - surely it is not too much to ask for=20
to type that extra character, especially because the resulting version is=
=20
not clear to newbies (why put the "+" _before_ the "=3D", for starters - =
"x=20
=3D+ step" would make more sense). If we want to save space, then "cnt"=20
instead of "continue" or "prt" instead of "print" might be a better place=
=20
to start. =20

Or, to put it differently: Is this just another example of a construct th=
at=20
was included in Python to make the "Waaah, I wanna keep my C style, even=20
if it is bizarre and non-intuitive"-crowd happy, or is there a real=20
difference between "x +=3Dy" and "x =3D x+y" that justifies a notation th=
at=20
looks like a typo?

Y, Scot

--=20
  Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany




From ak@silmarill.org  Fri Jul 19 06:28:09 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 19 Jul 2002 01:28:09 -0400
Subject: [Tutor] when to use exceptions
In-Reply-To: <008535DA-9A63-11D6-B07C-00039351FE6A@mac.com>
References: <008535DA-9A63-11D6-B07C-00039351FE6A@mac.com>
Message-ID: <20020719052809.GA18773@ak.silmarill.org>

On Thu, Jul 18, 2002 at 11:28:25AM -0400, Erik Price wrote:
> Where do you draw the line of when to use an exception and when not to 
> use an exception?  It seems that you could go on trying to catch 
> exceptions for every conceiveable problem... but you would spend all of 
> your time writing exception-catching code, right?

Not really, I don't think so.. Of course, in the early stages you
shouldn't do too much of that, but later on you write exception
handling for anything that could go wrong. Not enough space on a
partition, wrong user input, etc. Of course it may be handled without
exceptions, i.e. if it's user input testing you may have an infinite
loops that only breaks when user enters a valid answer. 

> 
> I'm asking in a theoretical sense, I don't have specific code that I'm 
> curious about.
> 
> Thanks for your thoughts,
> 
> 
> Erik
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From ak@silmarill.org  Fri Jul 19 06:32:16 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 19 Jul 2002 01:32:16 -0400
Subject: [Tutor] General question on Python vs PHP web programming
In-Reply-To: <1027002235.1912.21.camel@scott.zenplex.com>
References: <1027002235.1912.21.camel@scott.zenplex.com>
Message-ID: <20020719053215.GB18773@ak.silmarill.org>

On Thu, Jul 18, 2002 at 10:23:55AM -0400, Scott Comboni wrote:
> I have been writing in Python for about a year or so and by no means am
> I a programmer.  I recently have a begun looking into Webware for
> writing some web apps and I was curious if someone can just tell me what
> some of the advantages of using Python over PHP?  The one advantage I
> have is that I'm familiar enough with Python. PHP would be all new. 
> 
> Again just looking for some general input.

Python is much wider in its application. PHP is only meant for writing
database driven websites; Python is meant for anything from games to
web browsers to AI bots.

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From mark6433@hotmail.com  Fri Jul 19 06:57:50 2002
From: mark6433@hotmail.com (Mark Holder)
Date: Fri, 19 Jul 2002 05:57:50 +0000
Subject: [Tutor] From Text Editor to Interpreter
Message-ID: <LAW2-F398e2haZp5jRv00016832@hotmail.com>

<html><div style='background-color:'><DIV>
<P>Greetings from Sydney, AU.</P>
<P>I'm beginning programming (literally, starting today). I've downloaded Python 2.2 and opened the "Instant Hacking" page, written by Magnus Lie Hetland, in which the author states, </P>
<P><B class=greentext>Note</B>: To get the examples working properly, write the programs in a text file and then run that with the interpreter; do <EM>not</EM> try to run them directly in the interactive interpreter - not all of them will work. (Please don't ask me on details on this. Check the <A href="http://www.python.org/doc">documentation</A> or ask on the <A href="http://mail.python.org/mailman/listinfo/tutor">tutor</A> list). </P>
<P>My question is: what steps must a rank amateur take to write the programs in a text file and then run them with the interpretor? I've downloaded ConTEXT, which saves text as a Python file, but how do I run such programs as the Spam salad recipe in Python? </P>
<P>TIA,</P>
<P>Mark<BR></P></DIV></div><br clear=all><hr>MSN Photos is the easiest way to share and print your photos: <a href='http://g.msn.com/1HM1ENAU/c156??PI=44314'>Click Here</a><br></html>



From glingl@aon.at  Fri Jul 19 06:58:58 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 19 Jul 2002 07:58:58 +0200
Subject: [Tutor] engines
References: <DAV31KFRJrzdDW6lCPx0000de4b@hotmail.com> <3D3700B3.7040602@aon.at> <20020718191000.GA7540@marcolab.proconet>
Message-ID: <3D37AAA2.6030404@aon.at>

This is a multi-part message in MIME format.
--------------030100030702070606010305
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit

Marc schrieb:

>I noticed that you named variables with english/german words.
>Well, I can barely read english, let alone german.
>So, can u send me a translated version? *grin*.
>Maybe post it on list again.Im sure several people will be interested
>in your code.
>
Here it is!

Gregor

--------------030100030702070606010305
Content-Type: text/plain;
 name="esnake.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="esnake.py"

""" snake - OOP training   (V. OOP12)   - ENGLISH VERSION
    author: gregor lingl, vienna.    email:  glingl@aon.at   """
from Tkinter import *
from Canvas import Rectangle
import sys, random

class Gameboard(Canvas):
    def __init__(self, root, NX, NY, fieldwidth=12, **kwargs):
        Canvas.__init__(self, root, kwargs)
        w,h = NX*fieldwidth, NY*fieldwidth
        self.config(width=w+2, height=h+2, bg = 'yellow')
        self.grid = {}
        for row in range(NY):
            for column in range(NX):
                x0 = 2 + column * fieldwidth
                y0 = 2 + row  * fieldwidth
                x1 = x0 + fieldwidth
                y1 = y0 + fieldwidth
                r = Rectangle(self, x0, y0, x1, y1,
                              fill='yellow', outline='yellow' )
                self.grid[(column,row)] = r
    def set(self,field,colour):
        self.grid[field]['fill'] = colour

class Snake:
    def __init__(self, size):
        self.N = size
        self.food = None
        self.reset()
    def reset(self):
        self.snake= [(self.N/2,self.N/2)]
        self.food = None
        self.newFood()
        self.direction = None
        self.alive = 1         
    def newFood(self):
        while not self.food or self.food in self.snake:
            self.food = (random.randrange(self.N), random.randrange(self.N))
    def getscore(self):
        return "Score: " + str(max(0,len(self.snake)-4))        
    def cutoffTail(self):
        self.snake = self.snake[1:]
    def newHead(self,field):
        self.snake.append(field)
    def nextField(self):
        x,y = self.snake[-1]
        if self.direction == 'Up':
            y=y-1
        elif self.direction == 'Down':
            y=y+1
        elif self.direction == 'Left':
            x=x-1
        elif self.direction == 'Right':
            x=x+1
        else:
            return None
        return (x,y)
    def onBoard(self, next):
        x,y=next
        return 0 <= x < self.N and 0 <= y < self.N
    def step(self, newDirection):
        changed = {}
        if newDirection:
            if (newDirection,self.direction) not in (('Up','Down'),('Down','Up'),
                                                ('Right','Left'),('Left','Right')):
                self.direction = newDirection
        next = self.nextField()
        # Case 1: hit edge or bit herself
        if not self.onBoard(next) or next in self.snake:
            self.alive = 0
            for member in self.snake:
                changed[member]='black'
        # Fall 2: food found
        elif next == self.food:
            self.newHead(next)
            changed[next]='red'
            self.newFood()
            changed[self.food]='blue'
        # Fall 3: normal step
        else:
            if len(self.snake) > 3:
                changed[self.snake[0]]='yellow'
                self.cutoffTail()
            self.newHead(next)
            changed[next]='red'
        return changed

class SnakeEngine:
    def __init__(self, N):
        self.N = N
        root = Tk()
        root.title("SNAKE")
        root.bind('<KeyPress>', self.taste)
        self.board = Gameboard(root,N,N)
        self.board.pack()
        self.scorelabel = Label(root,width=22,text="",font=("Courier",14,"bold"),fg='red')
        self.hintlabel  = Label(root,width=22,text="",font=("Courier",14,"normal"))
        self.scorelabel.pack()
        self.hintlabel.pack()
        self.snake = Snake(N)
        self.reset()
    def taste(self,event):
        key = event.keysym
        if key == 'Return':
            sys.exit(0)
        if key in ['Up','Down','Left','Right','space']:
                self.eventlist.append(key)
    def reset(self):
        for field in self.board.grid:
            self.board.set(field,'yellow')
        self.eventlist = []
        self.state = "waiting"
        self.snake.reset()
        self.board.set(self.snake.snake[0],'red')
        self.board.set(self.snake.food,'blue')
        self.board.update()
        self.hintlabel.config(text="Control: arrow keys")
        self.scorelabel.config(text=self.snake.getscore())
    def run(self):
        changed = {}
        taste = None
        if self.eventlist:
            taste = self.eventlist[0]
            self.eventlist = self.eventlist[1:]
        if self.state == "waiting":
            if taste in ['Up','Down','Right','Left']:
                self.state = "running"
        if self.state == "running":
            if taste in ['Up','Down','Right','Left', None]:
                changed = self.snake.step(taste)
                self.scorelabel.config(text=self.snake.getscore())
            if not self.snake.alive:
                self.state="over"
                self.hintlabel.config(text="New game: space bar")
        elif self.state == "over":
            if taste == 'space':
                self.reset()
        for field in changed:
            self.board.set(field, changed[field])
        self.board.update()
        self.board.after(100, self.run)
       
SnakeEngine(21).run()
mainloop()
--------------030100030702070606010305--





From guillermo.fernandez@epfl.ch  Fri Jul 19 08:33:00 2002
From: guillermo.fernandez@epfl.ch (Guillermo Fernandez)
Date: Fri, 19 Jul 2002 17:03:00 +0930
Subject: [Tutor] turtle module
Message-ID: <3D37C0AC.D7A85A61@epfl.ch>

Hi,

I'm learning tk, and I've started with the turtle module. My problem is
that the documentation says:
"The procedural interface uses a pen and a canvas which are
automagically created when any of the functions are called."
but this canva (the window where the turtle is supposed to draw) only
last for 1/2 of second, and the turtle documentation does not propose
any function to make the image stay longuer.

How could I make this window stay longuer?

Thanks,

Guille



From yduppen@xs4all.nl  Fri Jul 19 09:54:01 2002
From: yduppen@xs4all.nl (Yigal Duppen)
Date: Fri, 19 Jul 2002 10:54:01 +0200
Subject: [Tutor] Why x+=y instead of x=x+y?
In-Reply-To: <200207190539.32916.scot@possum.in-berlin.de>
References: <Pine.SOL.4.44.0207172203500.44372-100000@csc> <200207182130.57228.yduppen@xs4all.nl> <200207190539.32916.scot@possum.in-berlin.de>
Message-ID: <200207191054.04801.yduppen@xs4all.nl>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> ...or is there a real
> difference between "x +=y" and "x = x+y" that justifies a notation that
> looks like a typo?

Hi Scot,

As far as I know there is a difference between the expressions in that the += 
notation requires one less lookup; furthermore, objects can have a separate 
method for the 'typo'-version: I believe those are the __iadd__, __isub__ 
etc. methods.

In practice, (especially when doing += on integers) this has no performance 
impact whatsoever; however, years of happy Java coding have slowly ingrained 
the notion that "+=" is read as "is incremented by"; and vice-versa, 
incrementing stuff is automatically done using +=.

I just can't help it, it's stronger than me :-)
But given the absence of any good reason, I think this notation was included 
to keep people like me happy.

YDD
- -- 
.sigmentation Fault
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE9N9OsLsKMuCf5EdwRAoC3AJ40oA7FB9w/8V5fYsfG5c1KFx48MgCfVBiH
ic9g28x/hAAmBVhJL7xmtgQ=
=ulLY
-----END PGP SIGNATURE-----




From mark.weinem@uni-duisburg.de  Fri Jul 19 12:34:19 2002
From: mark.weinem@uni-duisburg.de (Mark Weinem)
Date: Fri, 19 Jul 2002 13:34:19 +0200
Subject: [Tutor] From Text Editor to Interpreter
In-Reply-To: <LAW2-F398e2haZp5jRv00016832@hotmail.com>
References: <LAW2-F398e2haZp5jRv00016832@hotmail.com>
Message-ID: <20020719113419.GB78949@pandora.plagegeister.de>

On Fri, 19 Jul 2002, Mark Holder wrote:

> My question is: what steps must a rank amateur take to write the programs in a
> text file and then run them with the interpretor? I've downloaded ConTEXT,
> which saves text as a Python file, but how do I run such programs as the Spam
> salad recipe in Python?

Maybe you should learn some basics about your Operation System before
you start programming.

 - Open a texteditor, copy&paste the program code and save the file as
   spamsalad.py

 - Switch to the command line and type:

 		python spamsalad.py


And please, do not send html messages. 


Greetings, Mark



From abli@freemail.hu  Fri Jul 19 13:09:56 2002
From: abli@freemail.hu (Abel Daniel)
Date: Fri, 19 Jul 2002 14:09:56 +0200
Subject: [Tutor] Why x+=y instead of x=x+y?
In-Reply-To: <200207190539.32916.scot@possum.in-berlin.de>
References: <Pine.SOL.4.44.0207172203500.44372-100000@csc> <200207182130.57228.yduppen@xs4all.nl> <200207190539.32916.scot@possum.in-berlin.de>
Message-ID: <20020719120956.GA3871@hooloovoo>

Scot W. Stevenson (scot@possum.in-berlin.de) wrote:
> 
> Hello Yigal, 
> 
> While reading your post on "Loopy Questions" I noticed these lines:
> 
> > 	x += 0.01
> >     x += step
> 
> Now I know this is shorthand for "x = x+0.01" and "x = x+step", but I have 
> always wondered what the point is - surely it is not too much to ask for 
> to type that extra character, especially because the resulting version is 
> not clear to newbies (why put the "+" _before_ the "=", for starters - "x 
> =+ step" would make more sense). If we want to save space, then "cnt" 
> instead of "continue" or "prt" instead of "print" might be a better place 
> to start.  
> 
> Or, to put it differently: Is this just another example of a construct that 
> was included in Python to make the "Waaah, I wanna keep my C style, even 
> if it is bizarre and non-intuitive"-crowd happy, or is there a real 
> difference between "x +=y" and "x = x+y" that justifies a notation that 
> looks like a typo?
It is really hand if you have to do somethin like this:

really['long'].data[structure].to_increment += 1

in this case if += wouldnt exist, you would have to write the data
structure two times, which not only means a lot of typing, but more
importantly, you would also have to check _every_ time that you did it
correctly and the same stuff is on both sides of the equation.

abli
abli@freemail.hu



From alan.gauld@bt.com  Fri Jul 19 13:22:51 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 19 Jul 2002 13:22:51 +0100
Subject: [Tutor] when to use exceptions
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C750@mbtlipnt02.btlabs.bt.co.uk>

> Where do you draw the line of when to use an exception and 
> when not to use an exception?  

By use I assume you mean writing a handler.
The answer then becomes "when you can do something useful"
If you can't do amnything useful then write a generic 
handler that prints out a friendly error message, logs the 
useful info and then exits.

In practice I usually find that means writing 2 or 3 at 
most specific handlers and one generic handler.

Often, if the try block is short then its only a single 
handler for a specific error type that is most likely 
to occur- Divide by zero, IO error etc.

> exceptions for every conceiveable problem... but you would 
> spend all of your time writing exception-catching code, right?

<Puts large scale programming hat on again!>
In commercial C++ programs its not uncommon to find 
that 30-50% of the code consists of error handlers.
Exception handling helps reduce that but old style C
error handling(still necedssary in many C++ libraries)
led to very verbose error handling code.

In my experience of Python(ie no large scale projects)
the percentage of error handling code is much reduced but
if you really wanted a bulletproof system then yes, 
you could write as much error handler code as core 
application.

Alan g.



From glingl@aon.at  Fri Jul 19 13:38:06 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 19 Jul 2002 14:38:06 +0200
Subject: [Tutor] turtle module
References: <3D37C0AC.D7A85A61@epfl.ch>
Message-ID: <001201c22f21$21fd9b90$1615a8c0@mega>

I did use the turtle module several times, but I could not
observe this effect.

Normally I start IDLE, then 

>>> from turtle import *

Any turtle command. e. g.

>>> forward(100)

opens the canvas, shows the turtle wandering, eventually stopping
and remains on the screen.

I suppose, most probably you are writing scripts using the 
turtle module, containing several turtle commands.

Those scripts have to contain the command

Tkinter.mainloop()

as the last line in order to keep the Tk window open and let
it respond to user actions, as e. g. clicking x to close the
window.

# --- Example:

from turtle import *

for i in range(5):
    forward(72) # ;-)
    left(72)

Tkinter.mainloop()    

# --- end of example

Please note, that mainloop(() must not be used
when working from within IDLE in direct mode!

If this doesn't work on your machine,
please submit how exactly you are using
the turtle module and which commands cause
the behaviour you described - perhaps we
can give you better tips.

Gregor


----- Original Message ----- 
From: "Guillermo Fernandez" <guillermo.fernandez@epfl.ch>
To: <tutor@python.org>
Sent: Friday, July 19, 2002 9:33 AM
Subject: [Tutor] turtle module


> Hi,
> 
> I'm learning tk, and I've started with the turtle module. My problem is
> that the documentation says:
> "The procedural interface uses a pen and a canvas which are
> automagically created when any of the functions are called."
> but this canva (the window where the turtle is supposed to draw) only
> last for 1/2 of second, and the turtle documentation does not propose
> any function to make the image stay longuer.
> 
> How could I make this window stay longuer?
> 
> Thanks,
> 
> Guille
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




From alan.gauld@bt.com  Fri Jul 19 13:34:31 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 19 Jul 2002 13:34:31 +0100
Subject: [Tutor] engines
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C751@mbtlipnt02.btlabs.bt.co.uk>

Hi Gregor,

Yes it sounds like you are writing an engine but....

> eventlist = []
> def taste(event):
>     key = event.keysym
>     if key in goodkeys:
>         self.eventlist.append(key)
> 
> def run():
>     taste = None
>     # 1. suck one command from the eventlist
>     if self.eventlist:
>          taste = self.eventlist[0]
>          self.eventlist = self.eventlist[1:]

Why not just use the Tkinter event list? 
ie just catch the event and process it directly in 
the run code? Maintaining your own event list when 
you don't change the order of the received events 
seems like redundant effort.

>     # 2. then process some sort of finite state machine:
>     if state == "start":
>     elif state = "running":
>     elif state = "over":

This is pretty standard state machine processing but you 
might get a performance improvement if there are many 
states by writing lots of small state handling functions 
and storing them in a dictionary. Even if not for performance 
its much easier to extend the state machine this way, 
simply add a new state handler and an entry in the dictionary.
Often the same habdler can be used for several states...

states = {"start":dostart,
          "running":doRunning,
          "over":doOver,....}

then just call the functions like so:

state = states[state](param)

This assumes the doXXX functions can be made to take a common 
parameter set and that they return the next state.

Just some thoughts,

Alan g.



From alan.gauld@bt.com  Fri Jul 19 13:39:57 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 19 Jul 2002 13:39:57 +0100
Subject: [Tutor] Loopy question
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C752@mbtlipnt02.btlabs.bt.co.uk>

> I got a question about a step in a loop.  I want to make my 
> step really small for a problem i'm testing.  

What you really mean is you want lots of steps?

> however, the interpreter says my step in the for loop(0.01) 
> is a zero step for range.

Coz range uses integers not reals.

Solution? -  you have to multiply up the values, 
in your case by 1/0.01 = 100

so it becomes:
for i in range(200,500): # 300 steps
   step = i/100.0  # 2.00, 2.01, 2.02,.., 4.99 etc
   # use step here...

Alan G.



From alan.gauld@bt.com  Fri Jul 19 13:44:34 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 19 Jul 2002 13:44:34 +0100
Subject: [Tutor] Line in a file
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C753@mbtlipnt02.btlabs.bt.co.uk>

> How do I go directly to an exact line number in a file?

If the linev length is constant you can use seek() 
to jump directly by passing N*lineLength

Otherwise you have to read N lines:

for i in range(N): line = f.readline()

If the file is not too big it may be faster to read 
the whole lot to a list then index the list:

lines = f.readlines()
line = lines[N-1] # zero indexing

Alan g.



From alan.gauld@bt.com  Fri Jul 19 13:50:04 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 19 Jul 2002 13:50:04 +0100
Subject: [Tutor] Line in a file
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C754@mbtlipnt02.btlabs.bt.co.uk>

>  >>> def printLine(fh, num):				# let's 
> ...   c = 0
> ...   for line in fh.xreadlines():
> ...     c = c + 1
> ...     if (line == num):
> ...       fh.seek(0)					# 
> ...       return line					# 

Only returns if line == num but line is a 
string not a num... should check if c==num...

Incidentally there's a potential bug in that you 
return None if the required line is never reached. 
Might be better to raise an exception instead?

Alan G.



From churmtom@hotmail.com  Fri Jul 19 14:01:10 2002
From: churmtom@hotmail.com (Tom Churm)
Date: Fri, 19 Jul 2002 15:01:10 +0200
Subject: [Tutor] General question on Python vs PHP web programming
Message-ID: <LAW2-F418wSA1XvpFVj00007dda@hotmail.com>

regarding the info given by Andrei Kulakov:

>Python is much wider in its application. PHP is only meant for writing
>database driven websites; Python is meant for anything from games to
>web browsers to AI bots.

uhh, i believe you're wrong on this one, andrei.  i would agree that python 
is more powerful than php, but your minimizing php's abilities when you say 
it's 'meant only for writing database driven websites'.

just take a look at the huge library of built-in php functions listed at 
http://www.php.net to find out how wrong you are.  and 90% of these 
functions work without having to install any extra module; which is 
something that i find to be such a pain in the ass with python--with python 
you're always searching for modules, and it's not a lot of fun continually 
synchronizing the python builds on the various different computers you have 
to work on.

php can create dynamic images, dynamic pdf's, and can create dynamic web 
pages without using any database, and is even easier to learn than 
python--in my humble opinion. the documentation and examples and open source 
resources for php are also twice as good as for python.  if you need to find 
a code snippet for a specific task, you're likely to find exactly what you 
need within ten minutes from the slew of websites that offer such resources 
(for free), whereas this kind of thing is hard to find for python.  (ie: try 
to find the python equivalent of hotscripts.com for python, and you'll be 
out of luck, even taking into account 'vaults of parnassus'). no need to 
worry about that fancy-schmanzy spacing syntax in php, either.

add to this the fact that almost every webhoster these days offers php 
preinstalled as a standard feature.  lots of luck trying to find a webhoster 
that offers python installed at a price comparable to one with just php 
installed..

churmtom@hotmail.com
http://www.churm.com


_________________________________________________________________
Join the world’s largest e-mail service with MSN Hotmail. 
http://www.hotmail.com




From alan.gauld@bt.com  Fri Jul 19 13:57:27 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 19 Jul 2002 13:57:27 +0100
Subject: [Tutor] Why x+=y instead of x=x+y?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C755@mbtlipnt02.btlabs.bt.co.uk>

> > 	x += 0.01
> Now I know this is shorthand for "x = x+0.01" and "x = 
> x+step", but I have always wondered what the point is 

It comres from C which was initially implemented on a 
computer which had a different set of assembler instructions 
for generic addition and 'self addition' Thus += etc 
actually produced faster code. (For the same reason x++ still 
does because many assemblers have an INC X command for 
incrementing which is faster than ADD X 1)

> Or, to put it differently: Is this just another example of a 
> construct that was included in Python to make the "Waaah, 
> I wanna keep my C style, 

Absolutely correct. Virtiually all C derived languages have 
kept the shortcut version. Of course if your variable has 
a long (aka meaningful) name then it saves a lot more 
than 1 keystroke:

Compare:

currentIndexPosition += stepSize

with

currentIndexPosition = currentIndexPosition + stepSize

Alan G.



From alan.gauld@bt.com  Fri Jul 19 14:06:01 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 19 Jul 2002 14:06:01 +0100
Subject: [Tutor] From Text Editor to Interpreter
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C756@mbtlipnt02.btlabs.bt.co.uk>

------_=_NextPart_001_01C22F25.0830B360
Content-type: text/plain; charset="ISO-8859-1"

>  My question is: what steps must a rank amateur take to write the programs

>  in a text file and then run them with the interpretor? I've downloaded
ConTEXT,  
>  which saves text as a Python file, but how do I run such programs as the

>  Spam salad recipe in Python?  
 
First I'd recommend taking a look at Danny Yoo's IDLE 
tutor before going further. 
 
However having got the text into a file ending .py
(Lets call it first.py) then you have several options 
on how to run it:
 
1) Double click in explorer - snag, this will run it so 
fast you probably wont see the output as it flashes past!
 
2) Assuming you are in Windowsland! Start a MS DOS box 
(I usually do Start->Run and type COMMAND in the dialog)... 
In the resultant window with a prompt like:
 
C:\WINDOWS>
 
Change to the directory/folder where you saved first.py 
and then type python first.py. 
 
ie:
 
C:\WINDOWS> cd C:\PROJECTS\PYTHON
C:\PROJECTS\PYTHON> python first.py
 
You should see the output in your window before returning to the
 
C:\PROJECTS\PYTHON> 
prompt
 
3) Use IDLE (or Pythonwin if you downloaded the 
Activestate version of Python)
 
IDLE makes it much easier, read Danny's tutor :-)
 
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld
<http://www.freenetpages.co.uk/hp/alan.gauld>  


------_=_NextPart_001_01C22F25.0830B360
Content-type: text/html; charset="ISO-8859-1"

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">


<META content="MSHTML 5.50.4807.2300" name=GENERATOR></HEAD>
<BODY>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>&gt; &nbsp;</FONT></SPAN>My question is: what steps must a rank amateur 
take to write the programs&nbsp;<SPAN class=970080513-19072002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>in a text file and then run them with the 
interpretor? I've downloaded ConTEXT,&nbsp;<SPAN class=970080513-19072002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>which saves text as a Python file, but how do I 
run such programs as the&nbsp;<SPAN class=970080513-19072002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>Spam salad recipe in Python?&nbsp;<SPAN 
class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>First I'd recommend taking a look at Danny Yoo's IDLE 
</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>tutor before going further.</FONT>&nbsp;</SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>However having got the text into a file ending .py</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>(Lets call it first.py) then you have several options 
</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>on how to run it:</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>1) Double click in explorer - snag, this will run it so 
</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>fast you probably wont see the output as it flashes 
past!</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>2) Assuming you are in Windowsland! Start a MS DOS box 
</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>(I usually do Start-&gt;Run and </FONT></SPAN><SPAN 
class=970080513-19072002><FONT face="Courier New" color=#0000ff size=2>type 
COMMAND in the dialog)... </FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>In the resultant window </FONT></SPAN><SPAN 
class=970080513-19072002><FONT face="Courier New" color=#0000ff size=2>with a 
prompt like:</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>C:\WINDOWS&gt;</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>Change to the directory/folder where you saved first.py 
</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>and then </FONT></SPAN><SPAN class=970080513-19072002><FONT 
face="Courier New" color=#0000ff size=2>type python first.py. 
</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>ie:</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>C:\WINDOWS&gt; cd C:\PROJECTS\PYTHON</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002><FONT face="Courier New" color=#0000ff 
size=2>C:\PROJECTS\PYTHON&gt; python first.py</FONT></SPAN></DIV>
<DIV><SPAN class=970080513-19072002></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002>You should see the output in your window 
before returning to the</SPAN></DIV>
<DIV><SPAN class=970080513-19072002></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002>C:\PROJECTS\PYTHON&gt; </SPAN></DIV>
<DIV><SPAN class=970080513-19072002>prompt</SPAN></DIV>
<DIV><SPAN class=970080513-19072002></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002>3) Use IDLE (or Pythonwin if you downloaded 
the </SPAN></DIV>
<DIV><SPAN class=970080513-19072002>Activestate version of Python)</SPAN></DIV>
<DIV><SPAN class=970080513-19072002></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002>IDLE makes it much easier, read Danny's 
tutor :-)</SPAN></DIV>
<DIV><SPAN class=970080513-19072002></SPAN>&nbsp;</DIV>
<DIV><SPAN class=970080513-19072002>
<P><FONT size=2>Alan g.<BR>Author of the 'Learning to Program' web site<BR><A 
target=_blank 
href="http://www.freenetpages.co.uk/hp/alan.gauld">http://www.freenetpages.co.uk/hp/alan.gauld</A></FONT> 
</P></SPAN></FONT></SPAN></DIV></DIV></BODY></HTML>

------_=_NextPart_001_01C22F25.0830B360--



From erikprice@mac.com  Fri Jul 19 15:53:06 2002
From: erikprice@mac.com (Erik Price)
Date: Fri, 19 Jul 2002 10:53:06 -0400
Subject: [Tutor] General question on Python vs PHP web programming
In-Reply-To: <20020719053215.GB18773@ak.silmarill.org>
Message-ID: <3BF4FC8F-9B27-11D6-AE60-00039351FE6A@mac.com>

On Friday, July 19, 2002, at 01:32  AM, Andrei Kulakov wrote:

> On Thu, Jul 18, 2002 at 10:23:55AM -0400, Scott Comboni wrote:
>> I have been writing in Python for about a year or so and by no means am
>> I a programmer.  I recently have a begun looking into Webware for
>> writing some web apps and I was curious if someone can just tell me 
>> what
>> some of the advantages of using Python over PHP?  The one advantage I
>> have is that I'm familiar enough with Python. PHP would be all new.
>>
>> Again just looking for some general input.
>
> Python is much wider in its application. PHP is only meant for writing
> database driven websites; Python is meant for anything from games to
> web browsers to AI bots.

In general I agree with this.  Admittedly there is more to PHP than 
that, but this is its primary stated purpose.  Here are some comparisons 
that I have noticed (mind you I am far more familiar with PHP than 
Python):

Documentation -
Both languages have excellent support sites, but the PHP documentation 
rises above almost every other project I have ever seen in terms of 
looking up functions and such.  I even wrote a script that I execute 
from my text editor that takes the highlighted function name in the 
editor and opens up the browser and takes me to the appropriate page for 
that function.  Check out http://www.php.net/ and take a look at the 
online docs.

Installation -
I haven't actually installed mod_python or mod_snake, but I have done 
mod_php many times.  It's not really easy, and took me a while to get it 
right.  But you're best off doing it yourself rather than installing an 
RPM or something.  I understand that the Windows installation is a 
breeze.

Support -
PHP doesn't have a "tutor" list, which is a loss, because 
tutor@python.org is an extremely helpful forum for people of all sorts.  
However, I was an active participant in the php-general@lists.php.net 
mailing list, first as a complete newbie and later helping other 
newbies.  You can generally get immediate help there, but be careful 
because the gurus on that list are quicker to RTFM you than the gurus on 
this list.  It's also very high volume.  And to be honest with you, web 
programming with PHP is way way more common than with Python, so you'll 
find more tutorials and support forums for PHP web programming than 
Python web programming (this has been my experience).

Language syntax -
Python's syntax is nothing short of elegant IMO, whereas PHP is like a 
slightly cleaner and stricter Perl or C.  It uses the $ symbol for 
variable names, though it doesn't have fifty different special symbols 
like Perl, and there aren't as many ways to do something as there are in 
Perl, which some agree with me is a good thing.  Python is fully 
object-oriented, where PHP's object orientation works fine but isn't 
implemented as beautifully.  If you like objects (I do) then you'll 
probably find a much easier time working with Python.

Performance -
I actually have no idea how they compare.

Extensibility -
Python can be used for a greater variety of applications than PHP, I 
believe, but there is a lot of activity in extending PHP's 
capabilities.  Still, keep in mind that PHP is really aimed toward web 
development, so a lot of the cool stuff PHP can do is related to that.

Popularity -
There aren't as many jobs that are looking for Python web programmers as 
PHP programmers, but this shouldn't really be a factor anyway.  Why?  
Because there are next to no jobs that are looking for PHP programmers!  
ASP is way more popular among pointy haired bosses.  And Java/JSP seems 
to be more popular too.  Tough life!

Also, it's not true that PHP can only be used for web stuff, you can 
install it as a binary standalone program on your system and just use it 
for scripting, but if you have Python and are familiar with Python, 
there's no reason to use PHP for this purpose.



Erik




From terjeja@hotmail.com  Fri Jul 19 15:49:04 2002
From: terjeja@hotmail.com (Terje Johan Abrahamsen)
Date: Fri, 19 Jul 2002 14:49:04 +0000
Subject: [Tutor] Instances
Message-ID: <F200YIWtpU07Gy7phn60000d2db@hotmail.com>

I want to create a program that runs as an .exe file with py2exe or similar. 
In order to do so, the program has to create an instance of itself.

Hopefully this can show you what I want:

class test:

    n = test()
    choice = 0

    def __init__(self):
        test.choice = int(raw_input("What do you want to print? 1)Hello or 
2)Hey : "))
        if test.choice == 1:
            n.hello()
        else:
            n.hey()

    def hello(self):
        print"Hello"

    def hey(self):
        print"Hey"

But, it doesn't work. I get the following error: NameError: name 'test' is 
not defined. In other words, I have to write n = test() myself in the IDLE 
window. But, if it is an .exe file, I cannot write that. So, usually I have 
made a runme.py script that just contains:

from test import *
n = test()

But, this solution doesn't seem to work all the time either. How can I 
modify the first script to work?

_________________________________________________________________
Send and receive Hotmail on your mobile device: http://mobile.msn.com




From ATrautman@perryjudds.com  Fri Jul 19 16:24:48 2002
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Fri, 19 Jul 2002 10:24:48 -0500
Subject: [Tutor] Instances
Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A330@CORP_EXCHANGE>

I don't know if this helps as I am very confused about what you are trying
to accomplish but this seems to do what your example wants it to do. It is
not very elegant please write back if I'm missing the point.

class test:

    d = test()
    e = test()
    
    def __init__(self):
        self.choice = 0
        self.choice = int(raw_input("What do you want to print? 1)Hello or
2)Hey : "))
        if self.choice == 1:
            self.hello()
        else:
            self.hey()

    def hello(self):
        print"Hello"

    def hey(self):
        print"Hey"


    
print "starting"
aw = test()

Alan

-----Original Message-----
From: Terje Johan Abrahamsen [mailto:terjeja@hotmail.com]
Sent: Friday, July 19, 2002 9:49 AM
To: tutor@python.org
Subject: [Tutor] Instances


I want to create a program that runs as an .exe file with py2exe or similar.

In order to do so, the program has to create an instance of itself.

Hopefully this can show you what I want:

class test:

    n = test()
    choice = 0

    def __init__(self):
        test.choice = int(raw_input("What do you want to print? 1)Hello or 
2)Hey : "))
        if test.choice == 1:
            n.hello()
        else:
            n.hey()

    def hello(self):
        print"Hello"

    def hey(self):
        print"Hey"

But, it doesn't work. I get the following error: NameError: name 'test' is 
not defined. In other words, I have to write n = test() myself in the IDLE 
window. But, if it is an .exe file, I cannot write that. So, usually I have 
made a runme.py script that just contains:

from test import *
n = test()

But, this solution doesn't seem to work all the time either. How can I 
modify the first script to work?

_________________________________________________________________
Send and receive Hotmail on your mobile device: http://mobile.msn.com



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



From erikprice@mac.com  Fri Jul 19 16:58:47 2002
From: erikprice@mac.com (Erik Price)
Date: Fri, 19 Jul 2002 11:58:47 -0400
Subject: [Tutor] Line in a file
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C754@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <693C2505-9B30-11D6-AE60-00039351FE6A@mac.com>

On Friday, July 19, 2002, at 08:50  AM, alan.gauld@bt.com wrote:

>>>>> def printLine(fh, num):				# let's
>> ...   c = 0
>> ...   for line in fh.xreadlines():
>> ...     c = c + 1
>> ...     if (line == num):
>> ...       fh.seek(0)					#
>> ...       return line					#
>
> Only returns if line == num but line is a
> string not a num... should check if c==num...
>
> Incidentally there's a potential bug in that you
> return None if the required line is never reached.
> Might be better to raise an exception instead?

Good question.  I'm brand new to exceptions.  I understand the syntax 
and the theory.  But the practice is what matters.  So help me out if 
you can.

First I tried this function definition:

def printline(fh, num):
   c = 0
   try:
     for line in fh.xreadlines():
       c = c + 1
       if (c == num):
         return line
       else:
         raise IndexError
   finally:						# I like this, it executes no
     fh.seek(0)					# matter what

My first question about the above code, is why couldn't I put an 
exception handler in there with the finally?  I thought that you could 
do this, but you can only have one or the other.

The second thing is that the above code doesn't work -- the exception is 
raised if the "if" statement fails, which means that the function will 
only return the first line of the file (because if the "if" statement 
fails, the loop doesn't continue due to the exception).

So then I tried it this way:

 >>> def printline(fh, num):
...  c = 0
...  try:
...   for line in fh.xreadlines():
...     c = c + 1
...     if (c == num):
...       return line
...   raise IndexError
...  except IndexError:
...   print "The line you want was not found.\n"


This works but it doesn't seem right, because it raises an error unless 
the function returns first.  It just seems... well it's hard to say but 
it seems like I'm not using proper style.

Anyways, with this version, there's no "finally", so I can't reset the 
file pointer with fh.seek(0).  I liked it better the first time.  So 
then, should it instead be written like this?:

 >>> def printline(fh, num):
...  c = 0
...  try:
...   for line in fh.xreadlines():
...    c = c + 1
...    if (c == num):
...     return line
...   raise IndexError
...  finally:
...   fh.seek(0)
...
 >>> f = open('./pyreadfile.txt')
 >>> try:
...  output = printline(f, 4)
... except IndexError:
...  print "That line was not found\n"
...
 >>> output
'Four to the door\n'
 >>> try:
...  output2 = printline(f, 8)
... except IndexError:
...  print "That line was not found\n"
...
That line was not found



By doing it this way, I perform the "try" from the calling code, and 
return an exception.  It seems like I should be able to just have the 
exception handler defined within the function definition, but not if I 
want to use "finally" to reset my file pointer.  Is this really the way 
it's supposed to work?

Extra credit: can someone give me a clue as to how to make my 
"printline()" function a method of a file pointer, so that instead of

printline(filepointer, linenumber)

I can do

filepointer.printline(linenumber)

That seems like the way it should be done.  I seems like I'll have to 
extend the file pointer class.  But not sure...


Erik




From max_ig@yahoo.com  Fri Jul 19 17:14:46 2002
From: max_ig@yahoo.com (MIG)
Date: Fri, 19 Jul 2002 09:14:46 -0700 (PDT)
Subject: [Tutor] integers and float
Message-ID: <20020719161446.76661.qmail@web11304.mail.yahoo.com>

I've got a question with float and $.

I wrote a code for a Point-Of-Sales using floating variables for
dollars instead of integers using cents.

When I had problems printing the values I used the following line:

str(float(int((Variable_for_money)*100)/100)

I haven't found any problem yet testing the program, but since people
will pay their bills based on the program, I'm afraid some proble can
arise.

Please let me know if I can keep working with this or should I fix it
(with a lot of work because the program interacts with a MySQL data
base for accounting prupouses).


Thanks,

Max

__________________________________________________
Do You Yahoo!?
Yahoo! Autos - Get free new car price quotes
http://autos.yahoo.com



From glingl@aon.at  Fri Jul 19 17:14:40 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 19 Jul 2002 18:14:40 +0200
Subject: [Tutor] engines [- event handling]
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C751@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3D383AF0.7030608@aon.at>

alan.gauld@bt.com schrieb:

>Hi Gregor,
>
>Yes it sounds like you are writing an engine but....
>
>  
>
>>eventlist = []
>>def taste(event):
>>    key = event.keysym
>>    if key in goodkeys:
>>        self.eventlist.append(key)
>>
>>def run():
>>    taste = None
>>    # 1. suck one command from the eventlist
>>    if self.eventlist:
>>         taste = self.eventlist[0]
>>         self.eventlist = self.eventlist[1:]
>>    
>>
>
>Why not just use the Tkinter event list? 
>ie just catch the event and process it directly in 
>the run code? Maintaining your own event list when 
>you don't change the order of the received events 
>seems like redundant effort.
>  
>
I did this in an first version of  snake.py, but it turned out, that there
occurred cases, where the user (i.e. me in this case) pressed more
than one key in the 0.1 sec interval between two "steps". Every
keypress changed the "direction" of the snake, but - in this approach -
only the last one was processed. In some cases this led to the effect
that the snake ate itself and died. But even even other lost keys were
a bit disturbing when playing.

Next I tried to figure out if I hat direct access to Tkinters event list 
- but
did not succeed - perhaps you  can give some hints in this direction.
(However, as I thought about this a little more, I found it a bad idea, 
since  
then I had to filter out a lot of  events irrelevant to the snake-movement.)

The approach I finally used guarantees, that only one keypress is
processed in every step of the game and also that no keypress gets lost.

>  
>
>>    # 2. then process some sort of finite state machine:
>>    if state == "start":
>>    elif state = "running":
>>    elif state = "over":
>>    
>>
>
>This is pretty standard state machine processing but you 
>might get a performance improvement if there are many 
>states by writing lots of small state handling functions 
>and storing them in a dictionary. Even if not for performance 
>its much easier to extend the state machine this way, 
>simply add a new state handler and an entry in the dictionary.
>Often the same habdler can be used for several states...
>
>states = {"start":dostart,
>          "running":doRunning,
>          "over":doOver,....}
>
>then just call the functions like so:
>
>state = states[state](param)
>
>This assumes the doXXX functions can be made to take a common 
>parameter set and that they return the next state.
>  
>
This looks like a very fine and beautiful idea and I'll try to rewrite 
the corresponding
parts of the game in this way. [Maybe eventually there will result some 
kind of GameEngine
class, where one can plug in different games (played on this sort of 
Gameboard).]  I like
this sort of "practical abstraction", starting with some concrete 
example and discovering
general structures behind it.

>Just some thoughts,
>
>Alan g.
>
>  
>
Many thanks for your comments - this is exactly the kind of feedback I 
need and which is
most valuable for me.

Gregor
 





From alan.gauld@bt.com  Fri Jul 19 17:37:59 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 19 Jul 2002 17:37:59 +0100
Subject: [Tutor] Line in a file
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C75B@mbtlipnt02.btlabs.bt.co.uk>

> My first question about the above code, is why couldn't I put an 
> exception handler in there with the finally?  I thought that 
> you could do this

Nope you have to nest them:

try:
  try:
    #do it here
  except: # catch errors
finally: #tidy up

Which try goes inside is a fairly arbitrary choice, I prefer 
the finally outside because it then comes finally in the code too...

> So then I tried it this way:
> 
>  >>> def printline(fh, num):
> ...  c = 0
> ...  try:
> ...   for line in fh.xreadlines():
> ...     c = c + 1
> ...     if (c == num):
> ...       return line
> ...   raise IndexError
> ...  except IndexError:
> ...   print "The line you want was not found.\n"

The problem is you are raising and catching the exception, 
you only want to raise it so that your user can catch it!

remove the try/except and keep the raise.
(sounds like a poker game!)

then wrap the call to your function in a try/except:

>>> def printline(fh, num):
...   c = 0
...   for line in fh.xreadlines():
...     c = c + 1
...     if (c == num):
...       return line
...   raise IndexError
...
>>> try: printline(f,27)
... except IndexError: print "Couldn't access line 27"
...

Of course you also should define the IndexError 
exception class too:

class IndexError(Exception): pass

> it seems like I'm not using proper style.

You are trying to handle your own exception rather 
than raising it for your user to catch.

> Anyways, with this version, there's no "finally", so I can't 
> reset the file pointer with fh.seek(0).  

But you can now we;'ve removed the try/catch
>>> class IndexError(Exception): pass
>>> def printline(fh, num):
...   c = 0
...   try:
...     for line in fh.xreadlines():
...       c = c + 1
...       if (c == num):
...         return line
...    finally: fh.seek(0)
...    raise IndexError()

> I liked it better the first time. 

Is that any better?

> By doing it this way, 

Exactly right. I should have read further before 
'explaining'!


> It seems like I should be able to just have the 
> exception handler defined within the function definition

No, you want a way to signal to the function user that 
an error occured, that's exactly what raise is for. It 
only makes sense for you to handle the exception if you 
know how to recover from it. Given that you don't know 
how the client wants to deal with a non existent line 
you have to pass responsibility back to them!

> want to use "finally" to reset my file pointer.  Is this 
> really the way it's supposed to work?

Absolutely. The finally is something that you as function 
writer want to guaranrtee about the function - namely that 
it returns the line requested and leaves the file pointer 
at 0.

> Extra credit: can someone give me a clue as to how to make my 
> "printline()" function a method of a file pointer, so 
> that instead of

You'd need to create your own file subclass:

class RandomFile:
   def __init__(fn,md='r'):
     self.fp = open(fn,md)
   def printLine(num): # code here
   # and other file methods

Now you can open your class:

try:
  fp = RandomFile('foo.txt','r')
  fp.printline(27)
except: print 'oops!'

> That seems like the way it should be done.  I seems like I'll have to 
> extend the file pointer class.  But not sure...

Yes, if thats an extensible class, or there might be a 
UserFile or somesuch. But thats what you'll need to do.

Alan G.



From glingl@aon.at  Fri Jul 19 17:43:52 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 19 Jul 2002 18:43:52 +0200
Subject: [Tutor] integers and float
References: <20020719161446.76661.qmail@web11304.mail.yahoo.com>
Message-ID: <3D3841C8.20604@aon.at>

MIG schrieb:

>I've got a question with float and $.
>
>I wrote a code for a Point-Of-Sales using floating variables for
>dollars instead of integers using cents.
>
>When I had problems printing the values I used the following line:
>
>str(float(int((Variable_for_money)*100)/100)
>
>  
>
Have you tried to use "format-codes" to print formatted rounded  floats:

 >>> money = 15.232
 >>> money
15.231999999999999
 >>> "%.2f" % money
'15.23'
 >>> print "%.2f" % money
15.23
 >>> money = 15.239
 >>> money
15.239000000000001
 >>> print "%.2f" % money
15.24
 >>>

Information on format-codes are here:  

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

Good luck
Gregor






From ak@silmarill.org  Fri Jul 19 17:49:20 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 19 Jul 2002 12:49:20 -0400
Subject: [Tutor] General question on Python vs PHP web programming
In-Reply-To: <LAW2-F418wSA1XvpFVj00007dda@hotmail.com>
References: <LAW2-F418wSA1XvpFVj00007dda@hotmail.com>
Message-ID: <20020719164920.GA22677@ak.silmarill.org>

On Fri, Jul 19, 2002 at 03:01:10PM +0200, Tom Churm wrote:
> regarding the info given by Andrei Kulakov:
> 
> >Python is much wider in its application. PHP is only meant for writing
> >database driven websites; Python is meant for anything from games to
> >web browsers to AI bots.
> 
> uhh, i believe you're wrong on this one, andrei.  i would agree that python 
> is more powerful than php, but your minimizing php's abilities when you say 
> it's 'meant only for writing database driven websites'.
> 
> just take a look at the huge library of built-in php functions listed at 
> http://www.php.net to find out how wrong you are.  and 90% of these 

>From PHP faq:

he biggest advantage of PHP over Perl is that PHP was designed for
scripting for the web where Perl was designed to do a lot more
and can because of this get very complicated.

> functions work without having to install any extra module; which is 
> something that i find to be such a pain in the ass with python--with python 
> you're always searching for modules, and it's not a lot of fun continually 
> synchronizing the python builds on the various different computers you have 
> to work on.

I'd estimate that out of 3 years using python I spent all of 20 minutes
"always searching for modules", but YMMV :-).

> 
> php can create dynamic images, dynamic pdf's, and can create dynamic web 
> pages without using any database, and is even easier to learn than 
> python--in my humble opinion. 

I've no doubt it can - but for example awk can also be used to write
games or a chess program; but it was not designed for that.

It *should* be easier to learn than python, I'd hope - considering its
narrower appeal. That's the whole point of languages that focus on one
field - they're better in that field than anything else.

>
> the documentation and examples and open 
> source resources for php are also twice as good as for python.  if you need 
> to find a code snippet for a specific task, you're likely to find exactly 
> what you need within ten minutes from the slew of websites that offer such 
> resources (for free), whereas this kind of thing is hard to find for 
> python.  (ie: try to find the python equivalent of hotscripts.com for 
> python, and you'll be out of luck, even taking into account 'vaults of 
> parnassus'). no need to worry about that fancy-schmanzy spacing syntax in 
> php, either.

I don't know hotscripts but there's activestate's archive of python
snippets. VoP is geared more for larger apps.

> 
> add to this the fact that almost every webhoster these days offers php 
> preinstalled as a standard feature.  lots of luck trying to find a 
> webhoster that offers python installed at a price comparable to one with 
> just php installed..

Well, I had such luck, I pay $36/year. digitalspace.net

> 
> churmtom@hotmail.com
> http://www.churm.com
> 
> 
> _________________________________________________________________
> Join the world?s largest e-mail service with MSN Hotmail. 
> http://www.hotmail.com
> 
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From runsun@bilbo.bio.purdue.edu  Fri Jul 19 17:48:31 2002
From: runsun@bilbo.bio.purdue.edu (runsun)
Date: Fri, 19 Jul 2002 11:48:31 -0500
Subject: [Tutor] cgi not executed when accessed through browser
In-Reply-To: <20020719160005.29519.19248.Mailman@mail.python.org>
Message-ID: <HNEOKHJLEPAHPMJCIDCMIEPHCBAA.runsun@bilbo.bio.purdue.edu>

Hi all,

I have a simple python-based cgi :

===================[ content of test.cgi ]===========
#!/opt/bin/python
import os

print "Content-type: text/html\n\n"

print "hello\n"
print os.listdir("..")

print "\n"

print os.listdir("../..")
============================================

It was executed as expected when called from command line
in my unix account. But when it was called through a browser,
it didn't print out the listdir that I expected, but displayed the 
entire code content as text on my browser.

Any help ?

pan

============================================
  ~~ Be like water, be shapeless ~~
   Runsun Pan, PhD, 773-834-3965
 Ecology & Evolution, U of Chicago
============================================
 



From alan.gauld@bt.com  Fri Jul 19 17:48:09 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 19 Jul 2002 17:48:09 +0100
Subject: [Tutor] engines [- event handling]
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C75C@mbtlipnt02.btlabs.bt.co.uk>

> >Why not just use the Tkinter event list? 
> >
> I did this in an first version of  snake.py, but it 
> turned out, that there occurred cases, where the 
> user (i.e. me in this case) pressed more
> than one key in the 0.1 sec interval between two "steps". 

OK, the way I'd tackle that is to throw away (ie just beep!) 
the spurious keystrokes until the step was taken. Use a 'dirty' 
flag to achieve this.

When the first keystroke is received set dirty to true
When the next key arrives if dirty is true beep
When you update after 0.1 seconds reset the dirty flag 
to false ready for the next keystroke.

> every keypress changed the "direction" of the snake, but - in this 
> approach only the last one was processed. 

OK, If you definitely want every keystroke, ie a type ahead type 
control then you will need to buffer the keystrokes 
I guess.

> that the snake ate itself and died. But even even other lost keys were
> a bit disturbing when playing.

Thats why I'd beep. But I can see that in a fast game you'd 
find that confusing! OK, an event list in this case looks 
like the best solution - or just do realtime continuous 
updates!

> Next I tried to figure out if I hat direct access to Tkinters 
> event list - but did not succeed - perhaps you  can give some 
> hints in this direction.

Nope and its usually a bad idea to mess with it even if 
you can. Tk itself processes many of those events and if 
you mess with it Tk could get itself very confused!

> then I had to filter out a lot of  events irrelevant to the 
> snake-movement.)

Thats also true. Best to let Tk look after things at that level.

> The approach I finally used guarantees, that only one keypress is
> processed in every step of the game and also that no keypress 
> gets lost.

Fair enough.

> Many thanks for your comments - this is exactly the kind of 
> feedback I  need and which is most valuable for me.

Glad it helps,

Alan G.



From alan.gauld@bt.com  Fri Jul 19 17:51:21 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 19 Jul 2002 17:51:21 +0100
Subject: [Tutor] Instances
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C75D@mbtlipnt02.btlabs.bt.co.uk>

> not defined. In other words, I have to write n = test() 
> myself in the IDLE window. 
	
Does it work outside IDLE?

ie can you just douyble click the .py file?

If not I suspect you are missing the 

if __name__ == "__main__":
   n = test()

stanza to create a runnable script.

In fact you can miss the if test out and just put a last line of 

test()

But then you couldn't easily import the module elsewhere...

Alan g.



From glingl@aon.at  Fri Jul 19 17:58:00 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 19 Jul 2002 18:58:00 +0200
Subject: [Tutor] integers and float
References: <20020719161446.76661.qmail@web11304.mail.yahoo.com>
Message-ID: <3D384518.2090602@aon.at>

I  didn't recognize, that your expression doesn't work correctly,

1.) because the parentheses are not balanced

>
>str(float(int((Variable_for_money)*100)/100
>

so it should read (I presume)

    str(float(int((Variable_for_money)*100))/100)

but 2.) it doesn't round properly:

 >>> Variable_for_money=15.239
 >>> Variable_for_money
15.239000000000001
 >>> str(float(int((Variable_for_money)*100))/100)
'15.23'

And this comes so:

 >>> Variable_for_money*100
1523.9000000000001
 >>> int(Variable_for_money*100)
1523
 >>> float(int(Variable_for_money*100))
1523.0
 >>> float(int(Variable_for_money*100))/100
15.23
 >>> str(float(int(Variable_for_money*100))/100)
'15.23'
 >>>

Gregor





From erikprice@mac.com  Fri Jul 19 18:11:11 2002
From: erikprice@mac.com (Erik Price)
Date: Fri, 19 Jul 2002 13:11:11 -0400
Subject: [Tutor] Line in a file
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C75B@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <8647A453-9B3A-11D6-AE60-00039351FE6A@mac.com>

On Friday, July 19, 2002, at 12:37  PM, alan.gauld@bt.com wrote:

>> My first question about the above code, is why couldn't I put an
>> exception handler in there with the finally?  I thought that
>> you could do this
>
> Nope you have to nest them:
>
> try:
>   try:
>     #do it here
>   except: # catch errors
> finally: #tidy up
>
> Which try goes inside is a fairly arbitrary choice, I prefer
> the finally outside because it then comes finally in the code too...

Yes that makes total sense.  I didn't even think of nesting them (the 
Python Essential Reference gets points for being lightweight/thin, but 
the brevity sometimes leaves out extraneous solutions like this... 
justas it should I might add).

Though as I read through your response I realize that this isn't exactly 
what I want to do here...

> The problem is you are raising and catching the exception,
> you only want to raise it so that your user can catch it!

[...]

>> it seems like I'm not using proper style.
>
> You are trying to handle your own exception rather
> than raising it for your user to catch.

[...]

>> It seems like I should be able to just have the
>> exception handler defined within the function definition
>
> No, you want a way to signal to the function user that
> an error occured, that's exactly what raise is for. It
> only makes sense for you to handle the exception if you
> know how to recover from it. Given that you don't know
> how the client wants to deal with a non existent line
> you have to pass responsibility back to them!

This didn't even occur to me.  With one email I now have a much better 
grasp of using exceptions (especially the whole point of them as opposed 
to simply "returning false").  Thanks very much Alan.  Originally I 
thought that we handle our own Exceptions.  Now I understand that it's 
intended to be a generic yet informative way to give the user the 
ability to perform their own logic on the basis of the exception 
generated!  (Even if that user is me.)

(Tell me if this is accurate or not:)  Or, put another way, exceptions 
are simply generated within code libraries, and are meant to be handled 
by client code, regardless of who is actually writing it.


That's a big help.  I learn so much from you guys on this list.  Thank 
you.


Erik


PS:

> You'd need to create your own file subclass:

> class RandomFile:
>    def __init__(fn,md='r'):
>      self.fp = open(fn,md)
>    def printLine(num): # code here
>    # and other file methods

I see... I don't actually extend the "open()" class at all (if that's 
even a class).  I just wrap it up into my own class.  I assume that this 
is a good illustration of the difference between the "is a" and the "has 
a" relationship?  :)




From max_ig@yahoo.com  Fri Jul 19 18:29:11 2002
From: max_ig@yahoo.com (MIG)
Date: Fri, 19 Jul 2002 10:29:11 -0700 (PDT)
Subject: [Tutor] integers and float
In-Reply-To: <3D384518.2090602@aon.at>
Message-ID: <20020719172911.58903.qmail@web11307.mail.yahoo.com>

Greg,

Thank you for your comments about formats. I'll try it.

I haven't thought on the rounding because the code only uses cents (two
digits). But you gave me a good point for cases such as sale tax.

Thank you,

Max 


--- Gregor Lingl <glingl@aon.at> wrote:
> I  didn't recognize, that your expression doesn't work correctly,
> 
> 1.) because the parentheses are not balanced
> 
> >
> >str(float(int((Variable_for_money)*100)/100
> >
> 
> so it should read (I presume)
> 
>     str(float(int((Variable_for_money)*100))/100)
> 
> but 2.) it doesn't round properly:
> 
>  >>> Variable_for_money=15.239
>  >>> Variable_for_money
> 15.239000000000001
>  >>> str(float(int((Variable_for_money)*100))/100)
> '15.23'
> 
> And this comes so:
> 
>  >>> Variable_for_money*100
> 1523.9000000000001
>  >>> int(Variable_for_money*100)
> 1523
>  >>> float(int(Variable_for_money*100))
> 1523.0
>  >>> float(int(Variable_for_money*100))/100
> 15.23
>  >>> str(float(int(Variable_for_money*100))/100)
> '15.23'
>  >>>
> 
> Gregor
> 
> 


__________________________________________________
Do You Yahoo!?
Yahoo! Autos - Get free new car price quotes
http://autos.yahoo.com



From shalehperry@attbi.com  Fri Jul 19 19:49:55 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 19 Jul 2002 11:49:55 -0700 (PDT)
Subject: [Tutor] little something in the way of file parsing
Message-ID: <XFMail.20020719114955.shalehperry@attbi.com>

So in Debian we have a file called the 'available' file.  It lists the packages
that are in a particular Debian release and looks like this:

<snip>
Package: telnet
Priority: standard
Section: net
Installed-Size: 208
Maintainer: Herbert Xu <herbert@debian.org>
Architecture: i386
Source: netkit-telnet
Version: 0.17-18
Replaces: netstd
Provides: telnet-client
Depends: libc6 (>= 2.2.4-4), libncurses5 (>= 5.2.20020112a-1)
Filename: pool/main/n/netkit-telnet/telnet_0.17-18_i386.deb
Size: 70736
MD5sum: 7eb82b4facdabe95a8235993abe210f6
Description: The telnet client.
 The telnet command is used for interactive communication with another host
 using the TELNET protocol.
Task: unix-server

Package: gnushogi
Priority: optional
Section: games
Installed-Size: 402
Maintainer: Brian Mays <brian@debian.org>
Architecture: i386
Version: 1.3-3
Depends: libc6 (>= 2.2.4-4), libncurses5 (>= 5.2.20020112a-1)
Suggests: xshogi
Filename: pool/main/g/gnushogi/gnushogi_1.3-3_i386.deb
Size: 228332
MD5sum: 4a7bf0a6cce8436c6d74438a2d613152
Description: A program to play shogi, the Japanese version of chess.
 Gnushogi plays a game of Japanese chess (shogi) against the user or it
 plays against itself.  Gnushogi is an modified version of the gnuchess
 program.  It has a simple alpha-numeric board display, or it can use
 the xshogi program under the X Window System.
</snip>

One stanza after another.  As preparation for a tool that would allow me to do
better things than grep on it I wrote the following bit of python.

I am posting this because it shows some of the powers python has for rapid
coding and parsing.  Thought some of the lurkers might enjoy it.  Hope someone
learns something from it.

<code>

#!/usr/bin/python

import string

class Package:
    pass

availfile = '/var/lib/dpkg/available'

fd = open(availfile)

package_list = []
package = ''

# note I use the readline() idiom because there is currently 10 thousand plus
# entries in the file which equates to some 90,000 lines.

while 1:
    line = fd.readline()
    if not line: break

    line = string.rstrip(line)
    if not line:
        package_list.append(package)
        continue                     # end of package stanza

    if line[0] == ' ':
        if not hasattr(package, 'description'):
            setattr(package, 'description', '')
        package.description += line[1:]
        continue

    # the depends line occasionally has a line like
    # Depends: zlib1g (>= 1:1.1.3) which would break the split() so I use the
    # optional maxsplit option to ask for only the first colon
    tag, value = string.split(line, ':', 1)
    value = value[1:]

    tag = string.lower(tag)
    if tag == 'package':             # start a new package
        package = Package()

    # the Description format is the first line with Description: is the short
    # 'synopsis' the following lines are reads a paragraphs of a longer
    # description.  paragraphs are separated with '.' to make parsing easier
    if tag == 'description':
        tag = 'short'                # rename tag to allow description as long

    setattr(package, tag, value)

priorities = {}
sections = {}
maintainers = {}
sources = {}
tasks = {}

for package in package_list:
    priorities.setdefault(package.priority, []).append(package)
    sections.setdefault(package.section, []).append(package)
    maintainers.setdefault(package.maintainer, []).append(package)
    if hasattr(package, 'source'):
        sources.setdefault(package.source, []).append(package)
    if hasattr(package, 'task'):
        tasks.setdefault(package.task, []).append(package)

print 'Summary:'
print '%d packages' % len(package_list)
print '%d sources' % len(sources)
print '%d priorities' % len(priorities)
print '%d sections' % len(sections)
print '%d maintainers' % len(maintainers)
print '%d tasks' % len(tasks)
<code>

At this point I have a list of package classes and several dictionaries holding
lists of these packages.  There is only one instance of the actual package in
memory though, the rest are references handled by python's garbage collector. 
Most handy.

I could now add a gui to this which would show a tree of maintainers, sections,
tasks, whatever.  Or I could simply walk the package list and display the
synopsis.

Or fun things like who maintains more packages.  Which section has the least
packages.  What maintainer(s) is most important to Debian (he has the most
packages in the most critical section).

What I like about this solution is the empty Package class which gets filled as
we parse.  This makes it easy for the program to grow and change as the file
format changes (if that is needed).

All told this is about 30 minutes of work.



From erikprice@mac.com  Fri Jul 19 21:25:19 2002
From: erikprice@mac.com (Erik Price)
Date: Fri, 19 Jul 2002 16:25:19 -0400
Subject: [Tutor] little something in the way of file parsing
In-Reply-To: <XFMail.20020719114955.shalehperry@attbi.com>
Message-ID: <A5201406-9B55-11D6-AE60-00039351FE6A@mac.com>

On Friday, July 19, 2002, at 02:49  PM, Sean 'Shaleh' Perry wrote:

> One stanza after another.  As preparation for a tool that would allow 
> me to do
> better things than grep on it I wrote the following bit of python.
>
> I am posting this because it shows some of the powers python has for 
> rapid
> coding and parsing.  Thought some of the lurkers might enjoy it.  Hope 
> someone
> learns something from it.


See, now that's exactly what helps me learn, right there.  I really like 
to read source code written by others, because you can sort of imagine 
what's going through their head as you follow the path of execution 
through the program.  I had never even thought of making an empty class 
definition (and I still don't feel right about it), but I learned about 
the setdefault() method of dictionaries, and a few other things.

The problem with reading source code is usually that it's just way to 
big to be able to just sit down and digest.  Really, I think it's the 
best way to learn (short of actually writing code), but usually I 
download some cool looking program like Zope or Xerces or something like 
that and I just get overwhelmed because the code extends over so many 
files and you don't know where half the references are coming from, et 
cetera.  This is the kind of thing that people can learn from.

I also found it interesting that you didn't use regular expressions 
throughout the whole thing.  Normally when I think "parse", my mind goes 
"regex" and I immediately think "Perl" (yeah I like that language too, 
even though that might make me unpopular on this list ;).  But in this 
case, you didn't need them -- the file's structure was well-organized 
and you were able to use splices of line-strings and split() to grab the 
important parts of each line and place it into a meaningful attribute of 
the "package" object instance.  In fact, in my head I was wondering if 
this isn't a perfect application for an XML file, although there seems 
to be a bit more work involved in defining the structure of an XML 
file....

> # note I use the readline() idiom because there is currently 10 
> thousand plus
> # entries in the file which equates to some 90,000 lines.
>
> while 1:
>     line = fd.readline()

I assume that this comment means that you use readline() as opposed to 
readlines() ?  In other words, what are you actually saying in this 
comment (or rather why did you feel the need to clarify why you chose 
readline() ).

>
>     setattr(package, tag, value)
>

It's strange to me to see an empty class definition and then this 
function used to modify the class.  For you, it was convenient to use 
the Package class to wrap up your data into "packages" (that's a pun 
actually), but aren't class definitions usually used specifically for 
their behaviors?

In other words, I can see perfectly well that this script works 
perfectly well for your needs, so nothing else needs to be said.  But 
for the sake of my understanding, if a professor of OO programming were 
to come along, wouldn't he suggest that you define some methods of the 
Package class to do some of the work for you, rather than the 
setattr() ?  I'm curious because this is a big difference between Python 
and a language like Java.  You get more flexibility with Python, but it 
seems almost like it's too much of a shortcut.

> At this point I have a list of package classes and several dictionaries 
> holding
> lists of these packages.  There is only one instance of the actual 
> package in
> memory though, the rest are references handled by python's garbage 
> collector.
> Most handy.

Is that a specific behavior of list.append() or is that the way that 
references are passed in all Python data structures (by reference, not 
by value)?

Thanks for posting this Sean.


Erik




From shalehperry@attbi.com  Fri Jul 19 21:36:29 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 19 Jul 2002 13:36:29 -0700 (PDT)
Subject: [Tutor] little something in the way of file parsing
In-Reply-To: <A5201406-9B55-11D6-AE60-00039351FE6A@mac.com>
Message-ID: <XFMail.20020719133629.shalehperry@attbi.com>

On 19-Jul-2002 Erik Price wrote:
> On Friday, July 19, 2002, at 02:49  PM, Sean 'Shaleh' Perry wrote:
> 
>> One stanza after another.  As preparation for a tool that would allow 
>> me to do
>> better things than grep on it I wrote the following bit of python.
>>
>> I am posting this because it shows some of the powers python has for 
>> rapid
>> coding and parsing.  Thought some of the lurkers might enjoy it.  Hope 
>> someone
>> learns something from it.
> 
> 
> See, now that's exactly what helps me learn, right there.  I really like 
> to read source code written by others, because you can sort of imagine 
> what's going through their head as you follow the path of execution 
> through the program.  I had never even thought of making an empty class 
> definition (and I still don't feel right about it), but I learned about 
> the setdefault() method of dictionaries, and a few other things.
> 

the empty class thing is a recent item I learned and this was the first time I
really felt I found a use for it.  setdefault() is a new item in python 2.x.

> The problem with reading source code is usually that it's just way to 
> big to be able to just sit down and digest.  Really, I think it's the 
> best way to learn (short of actually writing code), but usually I 
> download some cool looking program like Zope or Xerces or something like 
> that and I just get overwhelmed because the code extends over so many 
> files and you don't know where half the references are coming from, et 
> cetera.  This is the kind of thing that people can learn from.
> 

I released this version because it was simple.  The real version will move the
parsing into a function so the user can say "parse the data again, I think it
changed".

> I also found it interesting that you didn't use regular expressions 
> throughout the whole thing.  Normally when I think "parse", my mind goes 
> "regex" and I immediately think "Perl" (yeah I like that language too, 
> even though that might make me unpopular on this list ;).  But in this 
> case, you didn't need them -- the file's structure was well-organized 
> and you were able to use splices of line-strings and split() to grab the 
> important parts of each line and place it into a meaningful attribute of 
> the "package" object instance.  In fact, in my head I was wondering if 
> this isn't a perfect application for an XML file, although there seems 
> to be a bit more work involved in defining the structure of an XML 
> file....
> 

I think one of the interesting bits of Python is that you can do so much
without using 'import re'.  Each language has its idioms and for perl regexs
are a big part.

This file format is *OLD* Debian has been using it since dpkg was written like
6 years ago.  It is dirt simple to parse and does not include any serious
overhead.  XML despite the hype (and we are not going down this road in this
thread) is not easier for humans to parse, type or otherwise interact with. 
XML just makes the parsers job "easier" compared to SGML or HTML.  For the most
part the XML "ease" comes from the fact that rules are enforced and there are no
special cases.

>> # note I use the readline() idiom because there is currently 10 
>> thousand plus
>> # entries in the file which equates to some 90,000 lines.
>>
>> while 1:
>>     line = fd.readline()
> 
> I assume that this comment means that you use readline() as opposed to 
> readlines() ?  In other words, what are you actually saying in this 
> comment (or rather why did you feel the need to clarify why you chose 
> readline() ).
> 

I added this comment for the tutor list.  In many intro examples you see:

for line in file.readlines()
  handle(line)

which is great for quicky code.  However readlines() returns a list of strings.
In my case it returns a 100 thousand element list of strings -- memory wasted.

>>
>>     setattr(package, tag, value)
>>
> 
> It's strange to me to see an empty class definition and then this 
> function used to modify the class.  For you, it was convenient to use 
> the Package class to wrap up your data into "packages" (that's a pun 
> actually), but aren't class definitions usually used specifically for 
> their behaviors?
> 
> In other words, I can see perfectly well that this script works 
> perfectly well for your needs, so nothing else needs to be said.  But 
> for the sake of my understanding, if a professor of OO programming were 
> to come along, wouldn't he suggest that you define some methods of the 
> Package class to do some of the work for you, rather than the 
> setattr() ?  I'm curious because this is a big difference between Python 
> and a language like Java.  You get more flexibility with Python, but it 
> seems almost like it's too much of a shortcut.
> 

In C++ or Java I would have had to define all of the attributes and methods for
this class.  Probably would have been a good 30 or so lines of code at a
minimum.  Here in Python I was able to dynamically handle this.  For rapid
coding this is a handy feature.  if I actually needed some knd of data
integrity checks the class would be fleshed out.  Part of the fun of this code
was how fast and simple it was to write.

In perl you would have defined a hash instead of making a class and the lists
would hold references to the hash.  I like the class because when I add real
code later to use the data the class names will make this clean and easy.

For instance I can have:

for package in package_list:
  if package.maintainer == "Sean 'Shaleh' Perry <shaleh@debian.org>":
    print package.package

or:

total_size = 0
for package in package_list:
  total_size += package.size

print 'If you could install all of it, Debian is %d bytes total' % total_size

which feels more natural to me than dictionary lookups which is how you would
do this without the class.  Basically I used a class to wrap a dictionary for
me.

>> At this point I have a list of package classes and several dictionaries 
>> holding
>> lists of these packages.  There is only one instance of the actual 
>> package in
>> memory though, the rest are references handled by python's garbage 
>> collector.
>> Most handy.
> 
> Is that a specific behavior of list.append() or is that the way that 
> references are passed in all Python data structures (by reference, not 
> by value)?
> 

that is how Python works.

a_list = ....
b_list = a_list
b_list[0] = something_else
print a_list[0] # you get something_else

In this case it means that my memory usage is not as large because there is
only one instance of the actual data and the lists are just place holders. 
Sure some of those lists are 5,000 elements long but it is still not too bad.
The computer science name for this is 'shallow copy'.  If you want to actually
do the copying you want a 'deep copy' and there is a special function in python
for this.

Glad you enjoyed it.



From arosado@softhome.net  Sat Jul 20 00:59:19 2002
From: arosado@softhome.net (Andres Rosado)
Date: Fri, 19 Jul 2002 19:59:19 -0400
Subject: [Tutor] CGI Question
Message-ID: <5.1.0.14.0.20020719195915.00bd2490@mail.softhome.net>


Can a CGI receive information and not reply?

-----------------------------------
Andres Rosado
Email: andresr@despammed.com
ICQ: 66750646
Homepage: http://andres980.tripod.com/

A friend may well be reckoned the masterpiece of Nature.
                 -- Ralph Waldo Emerson




From graumann@its.caltech.edu  Sat Jul 20 04:08:42 2002
From: graumann@its.caltech.edu (Johannes Graumann)
Date: Fri, 19 Jul 2002 20:08:42 -0700
Subject: [Tutor] class trouble
Message-ID: <20020719200842.58eef4ae.graumann@its.caltech.edu>

--=.vZh'/T1/uRimQl
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 7bit

Hello,

I'm just starting this and I'm absolutely clueless why the 3. and 4.
print statements give me the errors they do. Please help!

Thank you, Johannes


import string
class porf:
	def __init__(self,name,sequence):
		self.name = name
		self.sequence = string.upper(sequence)
	def length(self):
		return len(self.sequence)
	def stats(self,aa):
		aa = string.upper(aa)
		return string.count(self.sequence,aa)
ypr123a = porf('ypr123a','advboaisugvdfklabdfvlysgdvlajhsbfdlasgdclabhcd')
print ypr123a.name
print ypr123a.sequence
print ypr123a.length
print ypr123a.stats('a')
--=.vZh'/T1/uRimQl
Content-Type: application/pgp-signature

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)

iD8DBQE9ONRKJSKujSMUwjMRAvlqAJ95s0QMJq4zFdc1TVjqcYZvrBwPxQCfYo8/
h8hZ4gOnuezdOJ5tr6GWvZo=
=tVvG
-----END PGP SIGNATURE-----

--=.vZh'/T1/uRimQl--




From kalle@lysator.liu.se  Sat Jul 20 03:40:55 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Sat, 20 Jul 2002 04:40:55 +0200
Subject: [Tutor] class trouble
In-Reply-To: <20020719200842.58eef4ae.graumann@its.caltech.edu>
References: <20020719200842.58eef4ae.graumann@its.caltech.edu>
Message-ID: <20020720024055.GC2522@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Johannes Graumann]
> I'm just starting this and I'm absolutely clueless why the 3. and 4.
> print statements give me the errors they do. Please help!

> import string
> class porf:
> 	def __init__(self,name,sequence):
> 		self.name = name
> 		self.sequence = string.upper(sequence)
> 	def length(self):
> 		return len(self.sequence)
> 	def stats(self,aa):
> 		aa = string.upper(aa)
> 		return string.count(self.sequence,aa)
> ypr123a = porf('ypr123a','advboaisugvdfklabdfvlysgdvlajhsbfdlasgdclabhcd')
> print ypr123a.name

ypr123a

> print ypr123a.sequence

ADVBOAISUGVDFKLABDFVLYSGDVLAJHSBFDLASGDCLABHCD

> print ypr123a.length

A bit unexpected, maybe.  Methods and functions are objects as any
other in Python, so this just prints the object.

<method porf.length of porf instance at 0x810d79c>

If you add parantheses to invoke the method, this is the result.

>>> print ypr123a.length()
46

> print ypr123a.stats('a')

6

What errors are you experiencing?

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9OM2zdNeA1787sd0RApbnAJ9rpBWxLwIxuG/LqWDHxQtCrW6hMQCfQXu3
ua5ix1C9y/phw6kweHoBOJo=
=KwIF
-----END PGP SIGNATURE-----



From ak@silmarill.org  Sat Jul 20 04:05:26 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 19 Jul 2002 23:05:26 -0400
Subject: [Tutor] class trouble
In-Reply-To: <20020719200842.58eef4ae.graumann@its.caltech.edu>
References: <20020719200842.58eef4ae.graumann@its.caltech.edu>
Message-ID: <20020720030526.GA26603@ak.silmarill.org>

On Fri, Jul 19, 2002 at 08:08:42PM -0700, Johannes Graumann wrote:
> Hello,
> 
> I'm just starting this and I'm absolutely clueless why the 3. and 4.
> print statements give me the errors they do. Please help!
> 
> Thank you, Johannes
> 
> 
> import string
> class porf:
> 	def __init__(self,name,sequence):
> 		self.name = name
> 		self.sequence = string.upper(sequence)
> 	def length(self):
> 		return len(self.sequence)
> 	def stats(self,aa):
> 		aa = string.upper(aa)
> 		return string.count(self.sequence,aa)
> ypr123a = porf('ypr123a','advboaisugvdfklabdfvlysgdvlajhsbfdlasgdclabhcd')
> print ypr123a.name
> print ypr123a.sequence
> print ypr123a.length
> print ypr123a.stats('a')

ypr123a
ADVBOAISUGVDFKLABDFVLYSGDVLAJHSBFDLASGDCLABHCD
<method porf.length of porf instance at 0x810775c>
6

Instead of length you probably want __len__(self) - then you can do
len(instance) and it'll run that function. And to run the length
function you have, do print ypr123a.length(). 

The 4th statement is correct, I think.. Isn't it?

 - Andrei
-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From glide@slingshot.co.nz  Sat Jul 20 05:38:07 2002
From: glide@slingshot.co.nz (Graeme Andrew)
Date: Sat, 20 Jul 2002 16:38:07 +1200
Subject: [Tutor] Still pondering dynamically named functions ...
Message-ID: <200207201638.07200.glide@slingshot.co.nz>

Hi All,

Sorry but I am really struggling to understand if the follwoing is possib=
le ..=20
I asked before but perhaps I did not ask it very clearly (and I am new to=
=20
python) !!

I have a configuration file that I need to read and extract the names of =
some=20
processes that need to be executed dynamically by the python program. The=
=20
names of these processes in the configuration file are essentially the na=
mes=20
of the functions I want to call .. or classes I want to create.

My problem is understanding how in Python I can call dynamically at runti=
me=20
the name of a function I have just read from the configuration file ... i=
e=20
assign a function name to a variable and then call the function using thi=
s=20
variable.

I know I can use the 'exec function'  but this does not allow me to acces=
s=20
return values or dynamically create a class.=20

The code would kinda looks like this  ...

 # assign a function to variable name ...
 myfunction =3D=3D "function_a"  =20

 myfunction()   -- # this doesn't work I know .. but how ?
 =20
 #or perhaps=20

 my_object =3D myfunction   # create a instance .. calling the constructo=
r ...=20
is it possible somehow ?

If anyone has some suggestions on how to dynamically assign and execute a=
=20
function via a variable as described above it would be most appreciated..=
=2E

Thanks in advance.

Graeme Andrew






From idiot1@netzero.net  Sat Jul 20 06:01:49 2002
From: idiot1@netzero.net (Kirk Bailey)
Date: Sat, 20 Jul 2002 01:01:49 -0400
Subject: [Tutor] cgi not executed when accessed through browser
References: <HNEOKHJLEPAHPMJCIDCMIEPHCBAA.runsun@bilbo.bio.purdue.edu>
Message-ID: <3D38EEBD.3A71C1A4@netzero.net>

Yep. It's not a html page.

Read below.

runsun wrote:
> 
> Hi all,
> 
> I have a simple python-based cgi :
> 
> ===================[ content of test.cgi ]===========
> #!/opt/bin/python
> import os
> 
> print "Content-type: text/html\n\n"
>
See, from now on, the server treats it as a html page- and so does the
browser.
No body tag, no <HTML> tag. What's a browser to do?
 
> print "hello\n"
'\n' is useless in html. CARRIGERUTURNS are IGNORED.

> print os.listdir("..")
>
All one line in  html I fear. UNLESS one preceeds it with the <PRE> tag. 
> print "\n"
Likewise ignored.

> 
> print os.listdir("../..")
> ============================================
> 
> It was executed as expected when called from command line
> in my unix account.
sure it was, the telnet client is not a html browser.
> But when it was called through a browser,
> it didn't print out the listdir that I expected, but displayed the
> entire code content as text on my browser.
>
And probably included formatting discrepancies you did not mention.
{Possibly you did not notice? Not meaning to hurt feelings.)
 
> Any help ?
> 
Was my reply any help? Want a sample hello world script?

> pan
> 
> ============================================
>   ~~ Be like water, be shapeless ~~
>    Runsun Pan, PhD, 773-834-3965
>  Ecology & Evolution, U of Chicago
> ============================================
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 

end

Respectfully,
             Kirk D Bailey


+---------------------"Thou Art Free." -Eris-----------------------+
| http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
| http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
+------------------Thinking| NORMAL |Thinking----------------------+
                           +--------+
-------------------------------------------
Introducing NetZero Long Distance
Unlimited Long Distance only $29.95/ month!
Sign Up Today! www.netzerolongdistance.com



From kalle@lysator.liu.se  Sat Jul 20 06:11:36 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Sat, 20 Jul 2002 07:11:36 +0200
Subject: [Tutor] Still pondering dynamically named functions ...
In-Reply-To: <200207201638.07200.glide@slingshot.co.nz>
References: <200207201638.07200.glide@slingshot.co.nz>
Message-ID: <20020720051136.GE2522@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Graeme Andrew]
> My problem is understanding how in Python I can call dynamically at
> runtime the name of a function I have just read from the
> configuration file ... ie assign a function name to a variable and
> then call the function using this variable.

You can use the dictionary returned by globals() like this:

name = read_from_cfg_file()
globals()[name]()

That is assuming that your functions are bound to global names.  For
example, g won't be in globals() here:

def f():
    def g():
        pass

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9OPEEdNeA1787sd0RAm7VAJ9xTCr7UztnAalgiLKYe/Ejl/CamACfdsNL
H25CQQjLC30JRHQlFeJP6iA=
=Vc2l
-----END PGP SIGNATURE-----



From idiot1@netzero.net  Sat Jul 20 06:21:35 2002
From: idiot1@netzero.net (Kirk Bailey)
Date: Sat, 20 Jul 2002 01:21:35 -0400
Subject: [Tutor] cgi not executed when accessed through browser
References: <HNEOKHJLEPAHPMJCIDCMIEPHCBAA.runsun@bilbo.bio.purdue.edu> <3D38EEBD.3A71C1A4@netzero.net>
Message-ID: <3D38F35F.6E5014AD@netzero.net>

My first simple one.

ns# list first.py
Listing of file first.py in directory:/www/www.howlermonkey.net/cgi-bin

#!/usr/local/bin/python
print "Content-type: text/html"
print
print "<title>First program</title></head>"
print "<body bgcolor=\"FFFFFF\" text=\"000000\" link=\"0000FF\">"
print '<P>'
print "Hello world!"
print '<P>'
print '</body></html>'

And then a not so simple one:

ns# list helloworld.py
Listing of file helloworld.py in
directory:/www/www.howlermonkey.net/cgi-bin

#!/usr/local/bin/python
#import cgi
print "Content-Type: text/html"     # HTML is following
print                               # blank line, end of headers
print "<TITLE>CGI script output</TITLE>"
print "</head>"
print "<body bgcolor=\"#FFFFFF\" text=\"#000000\" ><blockquote>"
print "<P>"
print "<center><H1>This is my first CGI script</H1></center>"
print "<P>\n<br>"
print "Hello, world!"
print "<P>"
print "this is my very first python cgi script, and it works! YAHOO!"
print "<p>"
print "getting the quotes in the BODY statement to come out failed until
I remem
bered"
print "to ise a \\ in front of the quote so it would be a literal
instead of a "
print "end to a print declaration. So exxcited I plum forgot, ant
really,"
print "that's the same as in a shell script, pure human stupidity and
ham handed
ness,"
print "but it's fine <i>NOW</i>. Ya know, I could do a file copy in and
print ou
t and"
print "store the content as a simple heml file, and less work on
changing or cre
ating"
print "the scripts... hmmm..."
print "<P>\n<br>"
print "</html>"
print "</body>"


ns#
'list' is a shell script I wrote, which is so simple it is disgusting.

ns# list /usr/local/sbin/list
Listing of file /usr/local/sbin/list in
directory:/www/www.howlermonkey.net/cgi-bin

#! /bin/sh
echo -n Listing of file $1 in directory:
pwd
echo
more < $1;
echo

Home some of this helps.

-- 

end

Respectfully,
             Kirk D Bailey


+---------------------"Thou Art Free." -Eris-----------------------+
| http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
| http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
+------------------Thinking| NORMAL |Thinking----------------------+
                           +--------+
-------------------------------------------
Introducing NetZero Long Distance
Unlimited Long Distance only $29.95/ month!
Sign Up Today! www.netzerolongdistance.com



From idiot1@netzero.net  Sat Jul 20 06:27:49 2002
From: idiot1@netzero.net (Kirk Bailey)
Date: Sat, 20 Jul 2002 01:27:49 -0400
Subject: [Tutor] CGI Question
References: <5.1.0.14.0.20020719195915.00bd2490@mail.softhome.net>
Message-ID: <3D38F4D5.3A614E83@netzero.net>

Oh, yes. You can also use a script to copy in a file then spew it out,
so you could create a html page, READ IT IN, and print THAT. Therefore,
to change the page, just change the PAGE, not the SCRIPT.

Also, you can do a page this way in STAGES, such as header, main body,
and footer, and even parts of the body...

Don't ya just love cgi?
Feel free to write.


Andres Rosado wrote:
> 
> Can a CGI receive information and not reply?
> 
> -----------------------------------
> Andres Rosado
> Email: andresr@despammed.com
> ICQ: 66750646
> Homepage: http://andres980.tripod.com/
> 
> A friend may well be reckoned the masterpiece of Nature.
>                  -- Ralph Waldo Emerson
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 

end

Respectfully,
             Kirk D Bailey


+---------------------"Thou Art Free." -Eris-----------------------+
| http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
| http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
+------------------Thinking| NORMAL |Thinking----------------------+
                           +--------+
-------------------------------------------
Introducing NetZero Long Distance
Unlimited Long Distance only $29.95/ month!
Sign Up Today! www.netzerolongdistance.com



From graumann@its.caltech.edu  Sat Jul 20 09:33:11 2002
From: graumann@its.caltech.edu (Johannes Graumann)
Date: Sat, 20 Jul 2002 01:33:11 -0700 (PDT)
Subject: [Tutor] Re: class trouble (Kalle Svensson + Andrei Kulakov)
Message-ID: <Pine.GSO.4.42.0207200125150.4315-100000@clyde>

Kalle Svensson wrote:
[SNIP]
>> print ypr123a.length
>
>A bit unexpected, maybe.  Methods and functions are objects as any other
>in Python, so this just prints the object. <method porf.length of porf
>instance at 0x810d79c> If you add parantheses to invoke the method, this
>is the result.
>>>> print ypr123a.length()
>46
>> print ypr123a.stats('a')
>6 What errors are you experiencing? Peace,

None other ;0) - see below.

Andrei Kulakov wrote:
[SNIP]
><method porf.length of porf instance at 0x810775c>
>6
>Instead of length you probably want __len__(self) - then you can do
>len(instance) and it'll run that function.
>And to run the length function you have, do print ypr123a.length(). The

>4th statement is correct, I think.. Isn't it?
Yes.

Thanks! You know, second day python, stolen the setup from all kinds of
sources and then I bang my head for HOURS against a simple '()' ... ;0)
Is there any particular advantage to the '__len__(self)' solution?

Cheers and good night!

Johannes







From ak@silmarill.org  Sat Jul 20 16:36:54 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Sat, 20 Jul 2002 11:36:54 -0400
Subject: [Tutor] Re: class trouble (Kalle Svensson + Andrei Kulakov)
In-Reply-To: <Pine.GSO.4.42.0207200125150.4315-100000@clyde>
References: <Pine.GSO.4.42.0207200125150.4315-100000@clyde>
Message-ID: <20020720153654.GA31227@ak.silmarill.org>

On Sat, Jul 20, 2002 at 01:33:11AM -0700, Johannes Graumann wrote:
[snip]
> Is there any particular advantage to the '__len__(self)' solution?

It's a bit shorter - len(instance) vs. instance.length() and consistant
with the way you get length for strings, lists and dictionaries..

> 
> Cheers and good night!
> 
> Johannes
> 
> 
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From dyoo@hkn.eecs.berkeley.edu  Sat Jul 20 21:08:29 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jul 2002 13:08:29 -0700 (PDT)
Subject: [Tutor] From Text Editor to Interpreter
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C756@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.44.0207201307050.21315-100000@hkn.eecs.berkeley.edu>

> 3) Use IDLE (or Pythonwin if you downloaded the
> Activestate version of Python)
>
> IDLE makes it much easier, read Danny's tutor :-)

Hi Mark,

Here's the link to that IDLE introduction:

    http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro

If you have any questions, please feel free to bring them up on Tutor.
Best of wishes to you!




From dyoo@hkn.eecs.berkeley.edu  Sat Jul 20 22:01:50 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jul 2002 14:01:50 -0700 (PDT)
Subject: [Tutor] CGI Question
In-Reply-To: <3D38F4D5.3A614E83@netzero.net>
Message-ID: <Pine.LNX.4.44.0207201354350.21315-100000@hkn.eecs.berkeley.edu>

> > Can a CGI receive information and not reply?

Hi Andres,

Technically, it could, but then your web browser will report something
like "Error: Document received no data".

A CGI that doesn't send anything back is probably buggy, since CGI's are
expected to interact, either by spitting out a nice web page, or writing
out some error page that explains why it couldn't finish a request.

Is there a particular kind of CGI that you're thinking of, though?  There
may be a legitimate reason not to print anything from a CGI, but without
knowing more, I'd better stop here.  *grin*


Best of wishes to you!




From dyoo@hkn.eecs.berkeley.edu  Sat Jul 20 22:13:06 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jul 2002 14:13:06 -0700 (PDT)
Subject: [Tutor] little something in the way of file parsing
In-Reply-To: <A5201406-9B55-11D6-AE60-00039351FE6A@mac.com>
Message-ID: <Pine.LNX.4.44.0207201404170.21315-100000@hkn.eecs.berkeley.edu>

> The problem with reading source code is usually that it's just way to
> big to be able to just sit down and digest.  Really, I think it's the
> best way to learn (short of actually writing code), but usually I
> download some cool looking program like Zope or Xerces or something like
> that and I just get overwhelmed because the code extends over so many
> files and you don't know where half the references are coming from, et
> cetera.  This is the kind of thing that people can learn from.

We should do something sort of "Reader's Digest" to distill techniques
from a particular bit of code.  *grin*

I'm somewhat serious about this!  If anyone would like to point to a
particular bit of Python code that looks interesting, perhaps we can
discuss how it works on Tutor.  I'm convinced that programs should be
treated as literature.  I think the analogy to a written piece of work
does work, especially since many programs need to be rewritten and
revised... *grin*

Knuth takes this literary approach with "The Stanford Graphbase", where
source code and commentary are joined together; it's quite nice.




From erikprice@mac.com  Sat Jul 20 22:27:03 2002
From: erikprice@mac.com (Erik Price)
Date: Sat, 20 Jul 2002 17:27:03 -0400
Subject: [Tutor] little something in the way of file parsing
In-Reply-To: <Pine.LNX.4.44.0207201404170.21315-100000@hkn.eecs.berkeley.edu>
Message-ID: <6F2E7116-9C27-11D6-9291-00039351FE6A@mac.com>

On Saturday, July 20, 2002, at 05:13  PM, Danny Yoo wrote:

> I'm somewhat serious about this!  If anyone would like to point to a
> particular bit of Python code that looks interesting, perhaps we can
> discuss how it works on Tutor.  I'm convinced that programs should be
> treated as literature.  I think the analogy to a written piece of work
> does work, especially since many programs need to be rewritten and
> revised... *grin*
>
> Knuth takes this literary approach with "The Stanford Graphbase", where
> source code and commentary are joined together; it's quite nice.

I think it's a good idea.  I just wrote up a developer's guide to the 
[PHP] application I wrote over the past six months, and I basically 
provide a light commentary of each individual script, following the path 
of execution and explaining the functions in English (as opposed to the 
shorthand used in comments).  The source was commented too, but this 
will hopefully help the person who has to read the code next.

I would definitely be interested in learning from such a "digest", 
except that I am not very familiar with any Python projects to dissect.


Erik




From glingl@aon.at  Sat Jul 20 22:44:14 2002
From: glingl@aon.at (Gregor Lingl)
Date: Sat, 20 Jul 2002 23:44:14 +0200
Subject: [Tutor] little something ...  develops towards Stanford Graphbase
References: <Pine.LNX.4.44.0207201404170.21315-100000@hkn.eecs.berkeley.edu>
Message-ID: <3D39D9AE.9050108@aon.at>

Danny Yoo schrieb:

>>...
>>
> I think the analogy to a written piece of work
>does work, especially since many programs need to be rewritten and
>revised... *grin*
>
>Knuth takes this literary approach with "The Stanford Graphbase", where
>source code and commentary are joined together; it's quite nice.
>  
>

Hi Danny!

I read about this one or two days ago, when Guido posted some remarks 
about Leo on IDLE-Dev.
But - it's a pity - I  don't know nothing about it. I only feel, the 
idea sounds very interesting.

Could you explain in short terms what this is: "The Stanford Graphbase". 
Is it a book? Is it software?
Is it both? Or is it a website?  What is its content? In what way can an 
ordinary Python
user/trainer/teacher use it and what profit can she get from using it?

Thanks for your efforts in advance

Gregor

P.S. Perhaps can rewriting (according to Alan's suggestions) and 
revising my snake-program make
a story out of it   ;-)

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







From sarmstrong13@mac.com  Sun Jul 21 00:09:12 2002
From: sarmstrong13@mac.com (SA)
Date: Sat, 20 Jul 2002 18:09:12 -0500
Subject: [Tutor] Help with python parsing please..
Message-ID: <B95F57C8.9B9A%sarmstrong13@mac.com>

The following portion of my script is redirecting to the shell instead of
Python:
def expyth(self):
        self.t2.delete(0.0, END)
        self.output = commands.getoutput(self.t1.get(0.0, END))
        self.t2.insert(END, self.output)

Basically this part of my script takes the text I type in one window and
redirects the python output to another window. So I can write some script in
window one, this takes that text and parses the commands through Python and
displays the output in window 2.  Those of you that helped me a long time
ago with my IDLE program may remember this code. Needless to say, I've made
some sytem changes since the last time this script worked properly. Now it
is trying to parse the script through zsh instead of python and I'm getting
all kinds of errors. If there is some import command in the first window I
get a zsh error if the there is a from command (ie. From Tkinter import *) I
get an error about /var/mail/Tkinter.(No such thing on my system)

However if I write something simple like print "hello world", I get the
correct output in window two. I can't figure what the deal is. Any ideas?

Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me




From runsun@bilbo.bio.purdue.edu  Sun Jul 21 00:34:39 2002
From: runsun@bilbo.bio.purdue.edu (runsun)
Date: Sat, 20 Jul 2002 18:34:39 -0500
Subject: [Tutor] cgi not executed when accessed through browser
In-Reply-To: <20020720052202.27180.82715.Mailman@mail.python.org>
Message-ID: <HNEOKHJLEPAHPMJCIDCMAEPPCBAA.runsun@bilbo.bio.purdue.edu>

Thx for the replies but it still unsolved.

First of all, you don't need the <html> and <body> tags for a 
browser to read a document as html one. For example, a simple 
file containing only one line:

<font color=red> This is red </font>

will show up red on a browser, without <html> and <body> tags.

Therefore, the fact that my original code didn't contain these
tags can't be the reason for not showing correctly in a browser.

I did add: 

	print '<html>' 
            print '<body>'

but it didn't help.

The problem is that the cgi file was NOT EXECUTED when 
accessed through a browser, but only READ instead. It's 
executed when accessed from a command line on the server.



] Message: 8
] Date: Sat, 20 Jul 2002 01:01:49 -0400
] From: Kirk Bailey <idiot1@netzero.net>
] Organization: Silas Dent Memorial Cabal of ERIS Esoteric and hot 
] dog boiling society
] To: "tutor@python.org" <tutor@python.org>
] Subject: Re: [Tutor] cgi not executed when accessed through browser
] 
] Yep. It's not a html page.
] 
] Read below.
] 
] runsun wrote:
] > 
] > Hi all,
] > 
] > I have a simple python-based cgi :
] > 
] > ===================[ content of test.cgi ]===========
] > #!/opt/bin/python
] > import os
] > 
] > print "Content-type: text/html\n\n"
] >
] See, from now on, the server treats it as a html page- and so does the
] browser.
] No body tag, no <HTML> tag. What's a browser to do?
]  
] > print "hello\n"
] '\n' is useless in html. CARRIGERUTURNS are IGNORED.
] 
] > print os.listdir("..")
] >
] All one line in  html I fear. UNLESS one preceeds it with the <PRE> tag. 
] > print "\n"
] Likewise ignored.
] 
] > 
] > print os.listdir("../..")
] > ============================================
] > 
] > It was executed as expected when called from command line
] > in my unix account.
] sure it was, the telnet client is not a html browser.
] > But when it was called through a browser,
] > it didn't print out the listdir that I expected, but displayed the
] > entire code content as text on my browser.
] >
] And probably included formatting discrepancies you did not mention.
] {Possibly you did not notice? Not meaning to hurt feelings.)
]  
] > Any help ?
] > 
] Was my reply any help? Want a sample hello world script?
] 
] > pan
] > 
] > ============================================
] >   ~~ Be like water, be shapeless ~~
] >    Runsun Pan, PhD, 773-834-3965
] >  Ecology & Evolution, U of Chicago
] > ============================================
] > 
] > 
] > _______________________________________________
] > Tutor maillist  -  Tutor@python.org
] > http://mail.python.org/mailman/listinfo/tutor
] 
] -- 
] 
] end
] 
] Respectfully,
]              Kirk D Bailey
] 
] 
] +---------------------"Thou Art Free." -Eris-----------------------+
] | http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
] | http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
] +------------------Thinking| NORMAL |Thinking----------------------+
]                            +--------+
] -------------------------------------------
] Introducing NetZero Long Distance
] Unlimited Long Distance only $29.95/ month!
] Sign Up Today! www.netzerolongdistance.com
] 
] 
] 
] Message: 10
] Date: Sat, 20 Jul 2002 01:21:35 -0400
] From: Kirk Bailey <idiot1@netzero.net>
] Organization: Silas Dent Memorial Cabal of ERIS Esoteric and hot 
] dog boiling society
] To: "tutor@python.org" <tutor@python.org>
] Subject: Re: [Tutor] cgi not executed when accessed through browser
] 
] My first simple one.
] 
] ns# list first.py
] Listing of file first.py in directory:/www/www.howlermonkey.net/cgi-bin
] 
] #!/usr/local/bin/python
] print "Content-type: text/html"
] print
] print "<title>First program</title></head>"
] print "<body bgcolor=\"FFFFFF\" text=\"000000\" link=\"0000FF\">"
] print '<P>'
] print "Hello world!"
] print '<P>'
] print '</body></html>'
] 
] And then a not so simple one:
] 
] ns# list helloworld.py
] Listing of file helloworld.py in
] directory:/www/www.howlermonkey.net/cgi-bin
] 
] #!/usr/local/bin/python
] #import cgi
] print "Content-Type: text/html"     # HTML is following
] print                               # blank line, end of headers
] print "<TITLE>CGI script output</TITLE>"
] print "</head>"
] print "<body bgcolor=\"#FFFFFF\" text=\"#000000\" ><blockquote>"
] print "<P>"
] print "<center><H1>This is my first CGI script</H1></center>"
] print "<P>\n<br>"
] print "Hello, world!"
] print "<P>"
] print "this is my very first python cgi script, and it works! YAHOO!"
] print "<p>"
] print "getting the quotes in the BODY statement to come out failed until
] I remem
] bered"
] print "to ise a \\ in front of the quote so it would be a literal
] instead of a "
] print "end to a print declaration. So exxcited I plum forgot, ant
] really,"
] print "that's the same as in a shell script, pure human stupidity and
] ham handed
] ness,"
] print "but it's fine <i>NOW</i>. Ya know, I could do a file copy in and
] print ou
] t and"
] print "store the content as a simple heml file, and less work on
] changing or cre
] ating"
] print "the scripts... hmmm..."
] print "<P>\n<br>"
] print "</html>"
] print "</body>"
] 
] 
] ns#
] 'list' is a shell script I wrote, which is so simple it is disgusting.
] 
] ns# list /usr/local/sbin/list
] Listing of file /usr/local/sbin/list in
] directory:/www/www.howlermonkey.net/cgi-bin
] 
] #! /bin/sh
] echo -n Listing of file $1 in directory:
] pwd
] echo
] more < $1;
] echo
] 
] Home some of this helps.
] 
] -- 
] 
] end
] 
] Respectfully,
]              Kirk D Bailey
] 
] 
] +---------------------"Thou Art Free." -Eris-----------------------+
] | http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
] | http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
] +------------------Thinking| NORMAL |Thinking----------------------+
]                            +--------+
] -------------------------------------------
] Introducing NetZero Long Distance
] Unlimited Long Distance only $29.95/ month!
] Sign Up Today! www.netzerolongdistance.com
] 
] 
] 
] 
] --__--__--
] 
] _______________________________________________
] Tutor maillist  -  Tutor@python.org
] http://mail.python.org/mailman/listinfo/tutor
] 
] 
] End of Tutor Digest
] 



From arosado@softhome.net  Sun Jul 21 00:40:54 2002
From: arosado@softhome.net (Andres Rosado)
Date: Sat, 20 Jul 2002 19:40:54 -0400
Subject: [Tutor] Re: Tutor digest, Vol 1 #1778 - 3 msgs
In-Reply-To: <20020720160003.1461.49473.Mailman@mail.python.org>
Message-ID: <5.1.0.14.0.20020720193959.00bab4c0@mail.softhome.net>

At 12:00 PM 7/20/2002 -0400, you wrote:
>Oh, yes. You can also use a script to copy in a file then spew it out,
>so you could create a html page, READ IT IN, and print THAT. Therefore,
>to change the page, just change the PAGE, not the SCRIPT.
>
>Also, you can do a page this way in STAGES, such as header, main body,
>and footer, and even parts of the body...
>
>Don't ya just love cgi?

Thanks! The purpose of no-reply in my cgi is for an app that needs to 
register some info, but it doesn't need to send anything.

Thanks again. :)


-----------------------------------
Andres Rosado
Email: andresr@despammed.com
ICQ: 66750646
Homepage: http://andres980.tripod.com/

Reality -- what a concept!
                 -- Robin Williams




From arosado@softhome.net  Sun Jul 21 00:41:14 2002
From: arosado@softhome.net (Andres Rosado)
Date: Sat, 20 Jul 2002 19:41:14 -0400
Subject: [Tutor] CGI Question
In-Reply-To: <20020720160003.1461.49473.Mailman@mail.python.org>
Message-ID: <5.1.0.14.0.20020720193959.00bab4c0@mail.softhome.net>

At 12:00 PM 7/20/2002 -0400, you wrote:
>Oh, yes. You can also use a script to copy in a file then spew it out,
>so you could create a html page, READ IT IN, and print THAT. Therefore,
>to change the page, just change the PAGE, not the SCRIPT.
>
>Also, you can do a page this way in STAGES, such as header, main body,
>and footer, and even parts of the body...
>
>Don't ya just love cgi?

Thanks! The purpose of no-reply in my cgi is for an app that needs to 
register some info, but it doesn't need to send anything.

Thanks again. :)


-----------------------------------
Andres Rosado
Email: andresr@despammed.com
ICQ: 66750646
Homepage: http://andres980.tripod.com/

Reality -- what a concept!
                 -- Robin Williams




From arosado@softhome.net  Sun Jul 21 00:41:29 2002
From: arosado@softhome.net (Andres Rosado)
Date: Sat, 20 Jul 2002 19:41:29 -0400
Subject: [Tutor] Re: Why x+=y instead of x=x+y?
Message-ID: <5.1.0.14.0.20020720194126.00bf8e88@mail.softhome.net>

At 07:43 AM 7/19/2002 -0400, you wrote:
>While reading your post on "Loopy Questions" I noticed these lines:
>
> > =09x +=3D 0.01
> >     x +=3D step
>
>Now I know this is shorthand for "x =x+0.01" and "x =x+step", but I
>  have
>always wondered what the point is - surely it is not too much to ask for
>to type that extra character, especially because the resulting version is
>
>not clear to newbies (why put the "+" _before_ the "=", for starters -
>"x
>=+ step" would make more sense).

One point here is what you mean with it. If you remember correctly, there 
are two self-increment operators in C, ++x and x++. The way the ++ are 
written have a meaning, which goes first, the addition or the assigment.

a = ++x
x--
b = x++
a != b /*The result is this.*/

>If we want to save space, then "cnt"
>instead of "continue" or "prt" instead of "print" might be a better place
>
>to start.

It's not about saving space only. See below.

>Or, to put it differently: Is this just another example of a construct th
>at
>was included in Python to make the "Waaah, I wanna keep my C style, even
>if it is bizarre and non-intuitive"-crowd happy, or is there a real
>difference between "x +=y" and "x = x+y" that justifies a notation th
>at
>looks like a typo?
>
>Y, Scot

On prehistoric times, when the dinosaurs ruled the earth and DOS wasn't 
even invented, programmers had to use every single trick to optimize their 
programs. It happens that inside most microprocessor, x = x + y is:

temp = x
add x, y
x = temp

Which are 3 instructions. So, language definitions also included the +=, 
-=, /= and *= to speed this process. Nowadays, with processors so powerful, 
there is no need for these operators, but by tradition are still kept.


-----------------------------------
Andres Rosado
Email: andresr@despammed.com
ICQ: 66750646
Homepage: http://andres980.tripod.com/

Reality -- what a concept!
                 -- Robin Williams




From dyoo@hkn.eecs.berkeley.edu  Sun Jul 21 01:21:03 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jul 2002 17:21:03 -0700 (PDT)
Subject: [Tutor] cgi not executed when accessed through browser
In-Reply-To: <HNEOKHJLEPAHPMJCIDCMIEPHCBAA.runsun@bilbo.bio.purdue.edu>
Message-ID: <Pine.LNX.4.44.0207201706380.25638-100000@hkn.eecs.berkeley.edu>

On Fri, 19 Jul 2002, runsun wrote:

> I have a simple python-based cgi :
>
[script contents cut]
>
> It was executed as expected when called from command line in my unix
> account. But when it was called through a browser, it didn't print out
> the listdir that I expected, but displayed the entire code content as
> text on my browser.

Hi runsun,


If this happens, there are a few things you'll want to check.  One of them
is to see if the CGI program is "executable".  Another is to check that
the web server knows that '.py' and '.cgi' files are meant to be CGI
programs.

Since you're on a Unix server, your web server is probably Apache.  Check
with your system administrator to see if '.py' and '.cgi' files are
treated as CGI scripts.  Hopefully, they should know enough to fix this.


... but if you ARE the system administrator, you'll want to look at:

    http://httpd.apache.org/docs/howto/cgi.html


In particular, you may need to modify 'httpd.conf', and on the line that
mentions which files are cgi-able:

###
    AddHandler cgi-script .cgi
###



you'll want to add additional file extensions:

###
    AddHandler cgi-script .cgi .py .pl
###

You'll also want to all ExecCGI in the directory where the CGI files are
living; if your Apache server is configured properly, it should exclude
CGIs from running outside directories that you specify, for security
reasons.


This is, admittedly, a little involved, so we recommend a read through
that Apache CGI FAQ.  Thankfully, this is a one-time thing; once you have
your web server configured properly, it should be smooth sailing.


If you have more questions or run into problems, please feel free to ask
us on Tutor.  Best of wishes to you!




From dyoo@hkn.eecs.berkeley.edu  Sun Jul 21 01:47:54 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jul 2002 17:47:54 -0700 (PDT)
Subject: [Tutor] Still pondering dynamically named functions ...
In-Reply-To: <200207201638.07200.glide@slingshot.co.nz>
Message-ID: <Pine.LNX.4.44.0207201722480.25638-100000@hkn.eecs.berkeley.edu>


On Sat, 20 Jul 2002, Graeme Andrew wrote:

> Sorry but I am really struggling to understand if the follwoing is
> possible ..  I asked before but perhaps I did not ask it very clearly
> (and I am new to python) !!

Don't worry about it; let's take a look at your question.



> My problem is understanding how in Python I can call dynamically at
> runtime the name of a function I have just read from the configuration
> file ... ie assign a function name to a variable and then call the
> function using this variable.

One way to do this is with the getattr() function.  We can imagine that a
module is a container of variable names.  Here's an example:

###
>>> import string
>>> string.upper
<function upper at 0x8113314>
>>> getattr(string, 'upper')
<function upper at 0x8113314>
###



> I know I can use the 'exec function' but this does not allow me to
> access return values or dynamically create a class.
>
> The code would kinda looks like this  ...
>
>  # assign a function to variable name ...
>  myfunction == "function_a"

What we can do is something like:

    myfunction = globals()['function_a']

This is related to the getattr() technique above.  globals() gives us a
dictionary of all the attributes in the current module, and we can use it
to grab at that 'function_a'.


Let's try a small example in the interactive interpreter, just to make
this concrete:

###
>>> def a():
...     print "hey"
...
>>> def b():
...     print "how"
...
>>> def c():
...     print "who"
...
>>> def test():
...     name = raw_input("which function? ")
...     function = globals()[name]
...     function()
...
>>> test()
which function? a
hey
>>> test()
which function? b
how
###



But to tell the truth, I do feel a little awkward, because it feels like
there's a small inconsistancy here between the getattr() and globals()
approaches.  Does anyone know if there is a unified way of getting at
one's own module object, without using the 'globals()' function?


Please feel free to ask more questions about this.  Hope this helps!




From dman@dman.ddts.net  Sun Jul 21 03:23:29 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sat, 20 Jul 2002 21:23:29 -0500
Subject: [Tutor] Re: integers and float
In-Reply-To: <20020719161446.76661.qmail@web11304.mail.yahoo.com>
References: <20020719161446.76661.qmail@web11304.mail.yahoo.com>
Message-ID: <20020721022329.GA3074@dman.ddts.net>

--Kj7319i9nmIyA2yE
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Jul 19, 2002 at 09:14:46AM -0700, MIG wrote:
| I've got a question with float and $.

No. No. No. No. No.

Never never ever use floating point for handling money.  Always use
integers or fixed point.

If you want a demonstration of why, try this :

>>> print "%.40f" % 0.1
0.1000000000000000055511151231257827021182

For another example that doesn't involve binary, use a pencil and
paper and rewrite the expresion
    1/3
in decimal.  No, don't approximate it.  Write it *exactly*.  Ok,
nevermind I don't want to kill you.  (you can't, it's a "repeating
decimal")

If you want to learn more about binary floating point than you ever
cared, just ask Tim Peters :-).  (he's a guru with that stuff)

-D

--=20
The wise in heart are called discerning,
and pleasant words promote instruction.
        Proverbs 16:21
=20
http://dman.ddts.net/~dman/

--Kj7319i9nmIyA2yE
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj06GyEACgkQO8l8XBKTpRSFdACfXbPqPjVH8DeRV+tteBuLSUf3
oJkAoMpvx244Gk0AivdIJHm7pzDagD09
=U7bH
-----END PGP SIGNATURE-----

--Kj7319i9nmIyA2yE--



From dman@dman.ddts.net  Sun Jul 21 04:30:00 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Sat, 20 Jul 2002 22:30:00 -0500
Subject: [Tutor] Re: Why x+=y instead of x=x+y?
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C755@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C755@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020721033000.GB3074@dman.ddts.net>

--ADZbWkCsHQ7r3kzd
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Jul 19, 2002 at 01:57:27PM +0100, alan.gauld@bt.com wrote:
| > > 	x +=3D 0.01
| > Now I know this is shorthand for "x =3D x+0.01" and "x =3D=20
| > x+step", but I have always wondered what the point is=20
|=20
| It comres from C which was initially implemented on a=20
| computer which had a different set of assembler instructions=20
| for generic addition and 'self addition' Thus +=3D etc=20
| actually produced faster code. (For the same reason x++ still=20
| does because many assemblers have an INC X command for=20
| incrementing which is faster than ADD X 1)

I think it is also related to the complexity of the compiler.  I
expect that any modern compiler will turn "x+=3D1" into INC X.  I
assume, though, that early compilers were not as sophisticated, and if
they had been it would have been painful to use them on the hardware
of the day.

| > Or, to put it differently: Is this just another example of a=20
| > construct that was included in Python to make the "Waaah,=20
| > I wanna keep my C style,=20

Now in python it can still make a difference in performance because,
for example, lists are capable of performing in-place modifications.
So
    l1 =3D l1 + l2
causes the original data in l1 to be copied to a new location, the
data from l2 to be appended, and then the result returned and the
original l1 freed.  However
    l1 +=3D l2
allows l1 to simply stick the l2 data in the existing memory slots
(assuming it has enough "spares").


Coming back to the original question of using a float increment in a
range, it won't work even if you try to code it yourself.

step_count =3D 0
i =3D 0 ;
step =3D .1
while i < 10 :
    i +=3D step
    step_count +=3D 1

print "Total steps :", step_count


So how many iterations will you have, going from 0 to 10 with .1
intervals?  100?  No. 101!

Don't believe me?  Try it!  That's why range() only works on integers
-- it only works for integers.  The reason is the same as why you
don't use floats when dealing with exact data like money.  floats are
_great_ for high-speed data of either large or small magnitude where
"close" is close enough.  Particularly for scientific type work where
the precision of the floats is several orders of magnitude better than
the precision of your measuring tools.

-D

--=20
There are six things the Lord hates,
    seven that are detestable to him :
        haughty eyes,
        a lying tongue,
        hands that shed innocent blood,
        a heart that devises wicked schemes,
        feet that are quick to rush into evil,
        a false witness who pours out lies
        and a man who stirs up dissension among brothers.
=20
        Proverbs 6:16-19
=20
http://dman.ddts.net/~dman/

--ADZbWkCsHQ7r3kzd
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj06KrgACgkQO8l8XBKTpRRMyACeKndJLXBOG3iIDOJm1vTjhl5p
irMAoKVZq88M93RwEowN+5euli5WF3dU
=+QjT
-----END PGP SIGNATURE-----

--ADZbWkCsHQ7r3kzd--



From dyoo@hkn.eecs.berkeley.edu  Sun Jul 21 04:39:12 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jul 2002 20:39:12 -0700 (PDT)
Subject: [Tutor] Re: integers and float
In-Reply-To: <20020721022329.GA3074@dman.ddts.net>
Message-ID: <Pine.LNX.4.44.0207202029360.30045-100000@hkn.eecs.berkeley.edu>


On Sat, 20 Jul 2002, Derrick 'dman' Hudson wrote:

> On Fri, Jul 19, 2002 at 09:14:46AM -0700, MIG wrote:
> | I've got a question with float and $.
>
> No. No. No. No. No.
>
> Never never ever use floating point for handling money.  Always use
> integers or fixed point.

By the way, there's a module for representing money:

    http://www.post1.com/home/ngps/fin/

which looks pretty nice.

For people who are interested in financial calculations, the
python-finance group may help:

    http://groups.yahoo.com/group/python-finance/

I don't know how active the group is these days, especially with spammers
disrupting the discussion there.  Still, it might be useful.


Best of wishes to you!




From dyoo@hkn.eecs.berkeley.edu  Sun Jul 21 04:49:40 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jul 2002 20:49:40 -0700 (PDT)
Subject: [Tutor] Help with python parsing please..
In-Reply-To: <B95F57C8.9B9A%sarmstrong13@mac.com>
Message-ID: <Pine.LNX.4.44.0207202040120.30045-100000@hkn.eecs.berkeley.edu>


On Sat, 20 Jul 2002, SA wrote:

> The following portion of my script is redirecting to the shell instead of
> Python:
>
> def expyth(self):
>         self.t2.delete(0.0, END)
>         self.output = commands.getoutput(self.t1.get(0.0, END))
>         self.t2.insert(END, self.output)

Hmmm... expyth() looks ok to me.  So 't2' is the "script output" window,
while t2 is the "script input" window?  You may want to double check your
commands.getoutput() function.


> Basically this part of my script takes the text I type in one window and
> redirects the python output to another window. So I can write some
> script in window one, this takes that text and parses the commands
> through Python and displays the output in window 2.  Those of you that
> helped me a long time ago with my IDLE program may remember this code.
> Needless to say, I've made some sytem changes since the last time this
> script worked properly.

Hmmm... is it possible to have the source code available somewhere?  This
sounds like a subtle bug that will need to be hunted down.  Post a link,
and one of us here will be happy to look at the code and see what's going
on.

It might also be a great opportunity to play with the 'unittest' module!

    http://www.python.org/doc/current/lib/module-unittest.html

I've been reading Martin Fowler's "Refactoring", and his evangalizing of
unit tests is pretty persuasive to me.  *grin* It might make a great
tutorial demonstration to show how to write unit tests for your program.


> If there is some import command in the first window I get a zsh error if
> the there is a from command (ie. From Tkinter import *) I get an error
> about /var/mail/Tkinter.(No such thing on my system)
>
> However if I write something simple like print "hello world", I get the
> correct output in window two. I can't figure what the deal is. Any ideas?

Ah, but is that output coming from zsh, or from Python?  The statement:

    print "hello world"

is legitimate Python, but it is also perfectly legitimate Perl!  zsh, too
might consider it a good command, though I have never played with zsh.

We should look at commands.getoutput() to see how it works.


Best of wishes to you!




From sarmstrong13@mac.com  Sun Jul 21 05:28:49 2002
From: sarmstrong13@mac.com (SA)
Date: Sat, 20 Jul 2002 23:28:49 -0500
Subject: [Tutor] Help with python parsing please..
In-Reply-To: <Pine.LNX.4.44.0207202040120.30045-100000@hkn.eecs.berkeley.edu>
Message-ID: <B95FA2B1.9BB9%sarmstrong13@mac.com>

 
I'm sorry. The text widget in which the code is written is t1. t2 is the
text widget that displays the output. So the expyth function first clears
the output text widget, t2, then takes the text written in the input text
widget t1 parses through python and displays the output in text widget t2.
The code to the whole program is below. It is a short python script based
upon a tcl/tk script I came across that runs like a Perl IDLE. I changed it
around to run python code instead. Very simple script I'm toying with to
understand how Python works.

The problem is, this script used to work fine. Now that I have changed some
things around and re-installed Python, it no longer functions properly. For
instance, when I run a quick script to make a simple tkinter button using
"from Tkinter import *" I get the following:

from: can't read /var/mail/Tkinter
11:21PM up 6:43, 2 users, load averages: 0.05, 0.3, 0.0
USER    TTY FROM        LOGIN@  IDLE WHAT


If I use import Tkinter instead I get the following in the display text
widget:

zsh: command not found: import
11:24PM up  :47,    2 users,    load averages: 0.16, 0.01, 0.01
USER    TTY FROM        LOGIN@  IDLE WHAT


You were correct about the print statement. I've tried other simple python
code and it all looks like the output is being parsed by a zsh shell instead
of python. Any ideas?


Thanks.
SA




PyShell3.py:

from Tkinter import *
import os
import commands
import tkSimpleDialog

class PyShell:
    
    def clearin(self):
        self.t1.delete(0.0,END)
    def clearout(self):
        self.t2.delete(0.0,END)
    def expyth(self):
        self.t2.delete(0.0, END)
        self.output = commands.getoutput(self.t1.get(0.0, END))
        self.t2.insert(END, self.output)
    def doSave(self):
        SaveDialog = Saving(self.f)
        filename = SaveDialog.getName()
#        outfile = self.t1.get(0.0, END)
#        out = open(filename, 'w')
#        out.write(outfile)
#        out.close()
        self.saveText(filename)
        del(saveDialog)
    def __init__(self, top):
        self.t1 = Text(top, height="12", width="84", font="Courier 12")
        self.t1.pack(side=TOP, pady=2)
        self.f = Frame(top)
        self.f.pack()
        self.b1 = Button(self.f, text="Execute", command=self.expyth)
        self.b1.pack(side=LEFT)
        self.b2 = Button(self.f, text="Clear Input", command=self.clearin)
        self.b2.pack(side=LEFT)
        self.b3 = Button(self.f, text="Clear Output", command=self.clearout)
        self.b3.pack(side=LEFT)
        self.b4 = Button(self.f, text="Save Input", command=self.doSave)
        self.b4.pack(side=LEFT)
        self.t2 = Text(top, height="12", width="84", bg="lightblue",
font="Courier 12")
        self.t2.pack(side=TOP, pady=2)

class Saving(tkSimpleDialog.Dialog):
    
    def body(self, master):
        Label(master, text="Directory:").grid(row=0)
        Label(master, text="Filename:").grid(row=1)
        self.e1 = Entry(master)
        self.e2 = Entry(master)
        self.e1.grid(row=0, column=1)
        self.e2.grid(row=1, column=1)
        return self.e1
    def apply(self):
        dir = self.e1.get()
        fn = self.e2.get()
        self.name = dir + fn
    def getName(self):
        return self.name

                   
root = Tk()
app = PyShell(root)
root.mainloop()




From dyoo@hkn.eecs.berkeley.edu  Sun Jul 21 05:29:09 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jul 2002 21:29:09 -0700 (PDT)
Subject: [Tutor] little something ...  develops towards Stanford Graphbase
 / programs as literature
In-Reply-To: <3D39D9AE.9050108@aon.at>
Message-ID: <Pine.LNX.4.44.0207202050270.30045-100000@hkn.eecs.berkeley.edu>


> >Knuth takes this literary approach with "The Stanford Graphbase", where
> >source code and commentary are joined together; it's quite nice.
>
> I read about this one or two days ago, when Guido posted some remarks
> about Leo on IDLE-Dev. But - it's a pity - I don't know nothing about
> it. I only feel, the idea sounds very interesting.
>
> Could you explain in short terms what this is: "The Stanford Graphbase".
> Is it a book? Is it software? Is it both? Or is it a website?  What is
> its content?

The Stanford Graphbase is a book, a collection of graph algorithm
programs, with commentaries embedded within each program.

    http://www-cs-faculty.stanford.edu/~knuth/sgb.html

What makes his programs distinctly different is that the order of
presentation in the book is decoupled from the way the program itself
constructed.

When we discuss a program, we might take a small chunk and start
describing it in detail, and take another small chunk.  We may not even be
writing a whole function, but may concentrate on a particular technique,
like applying a for loop.  It's sorta what we often do on Tutor.  *grin*


That is, we write program fragments primarily for human understanding,
because it's easy for humans to understand things in little pieces --- we
often try to chunk our programs by writing functions.

What his book does is show whole programs as a bunch of chunks, complete
with documentation.  Not only does he decompose things into functions, but
he goes one step further: he actually writes them as descriptive chunks.
All of the programs are written in this way, even the custom "flipping"
random number generator.  There's a separate program that weaves the
program back into the correct order.


> In what way can an ordinary Python user/trainer/teacher use it and what
> profit can she get from using it?

It might be hard to apply directly to Python, as the code is written in C.
But there are ideas about the way he presents the code that appeals to me.

I apologize for going so off topic from Python; I'm just something of a
Knuth fanatic.  *grin*  Sorry about that.



Another book that takes this idea of source code as literature is the
"Lions' Commentary on Unix 6th Edition":

    http://www.salon.com/tech/feature/1999/11/30/lions

This is another example of someone taking a fairly large program, and
distilling ideas and techniques from it.  The commentary occupies part two
of this two-part book, so there's a bit of flipping back and forth
involved, but it's still very nice.  And again, it's in C (and in a really
old K&R C, no less!), so it's not immediately applicable.

Darn it, we need something like this for Python.  *grin*


> P.S. Perhaps can rewriting (according to Alan's suggestions) and
> revising my snake-program make a story out of it ;-)

Yes, that sounds awesome!


Best of wishes to you!




From dyoo@hkn.eecs.berkeley.edu  Sun Jul 21 05:36:04 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Jul 2002 21:36:04 -0700 (PDT)
Subject: [Tutor] Help with python parsing please..
In-Reply-To: <B95FA2B1.9BB9%sarmstrong13@mac.com>
Message-ID: <Pine.LNX.4.44.0207202130350.30045-100000@hkn.eecs.berkeley.edu>


On Sat, 20 Jul 2002, SA wrote:

> The problem is, this script used to work fine. Now that I have changed
> some things around and re-installed Python, it no longer functions
> properly. For instance, when I run a quick script to make a simple
> tkinter button using "from Tkinter import *" I get the following:
>
> from: can't read /var/mail/Tkinter

Hi SA,

Ah.  Now I see all too clearly.  That's because there's a Unix command
named 'from':

    http://www.ntua.gr/cgi-bin/man-cgi?from

*grin*

You're getting that wacky error message about /var/mail because the 'from'
Unix command deals with filtering out the sender and date of incoming mail
messages.


> If I use import Tkinter instead I get the following in the display text
> widget:
>
> zsh: command not found: import

Yes, this looks like everything's going into the zsh interpreter, rather
than Python.


> You were correct about the print statement. I've tried other simple python
> code and it all looks like the output is being parsed by a zsh shell instead
> of python. Any ideas?

Hmmm.... what does the 'commands' module look like?  Since that's the
module responsible for evaluating strings, let's take a look at that
module.


Talk to you later!




From idiot1@netzero.net  Sun Jul 21 05:45:55 2002
From: idiot1@netzero.net (Kirk Bailey)
Date: Sun, 21 Jul 2002 00:45:55 -0400
Subject: [Tutor] cgi not executed when accessed through browser
References: <HNEOKHJLEPAHPMJCIDCMAEPPCBAA.runsun@bilbo.bio.purdue.edu>
Message-ID: <3D3A3C83.4EA73465@netzero.net>

Ah, shoot. execution error.

First, check all script file permissions. Try "chmod 755 *.py" while IN
the web cgi-bin, and also go double check the apache.cf file for
permissions. it has to know it is supposed to execute file in a certain
directory, and you may also need to tell it file TYPEs to execute. It
referrs to the thing FINE, but THINKS IT IS A DOCUMENT!!!!

Um, you ARE running some flavor of U*ix, right?


Hope this helps.

runsun wrote:
> 
> Thx for the replies but it still unsolved.
> 
> First of all, you don't need the <html> and <body> tags for a
> browser to read a document as html one. For example, a simple
> file containing only one line:
> 
> <font color=red> This is red </font>
> 
> will show up red on a browser, without <html> and <body> tags.
> 
> Therefore, the fact that my original code didn't contain these
> tags can't be the reason for not showing correctly in a browser.
> 
> I did add:
> 
>         print '<html>'
>             print '<body>'
> 
> but it didn't help.
> 
> The problem is that the cgi file was NOT EXECUTED when
> accessed through a browser, but only READ instead. It's
> executed when accessed from a command line on the server.
> 
> ] Message: 8
> ] Date: Sat, 20 Jul 2002 01:01:49 -0400
> ] From: Kirk Bailey <idiot1@netzero.net>
> ] Organization: Silas Dent Memorial Cabal of ERIS Esoteric and hot
> ] dog boiling society
> ] To: "tutor@python.org" <tutor@python.org>
> ] Subject: Re: [Tutor] cgi not executed when accessed through browser
> ]
> ] Yep. It's not a html page.
> ]
> ] Read below.
> ]
> ] runsun wrote:
> ] >
> ] > Hi all,
> ] >
> ] > I have a simple python-based cgi :
> ] >
> ] > ===================[ content of test.cgi ]===========
> ] > #!/opt/bin/python
> ] > import os
> ] >
> ] > print "Content-type: text/html\n\n"
> ] >
> ] See, from now on, the server treats it as a html page- and so does the
> ] browser.
> ] No body tag, no <HTML> tag. What's a browser to do?
> ]
> ] > print "hello\n"
> ] '\n' is useless in html. CARRIGERUTURNS are IGNORED.
> ]
> ] > print os.listdir("..")
> ] >
> ] All one line in  html I fear. UNLESS one preceeds it with the <PRE> tag.
> ] > print "\n"
> ] Likewise ignored.
> ]
> ] >
> ] > print os.listdir("../..")
> ] > ============================================
> ] >
> ] > It was executed as expected when called from command line
> ] > in my unix account.
> ] sure it was, the telnet client is not a html browser.
> ] > But when it was called through a browser,
> ] > it didn't print out the listdir that I expected, but displayed the
> ] > entire code content as text on my browser.
> ] >
> ] And probably included formatting discrepancies you did not mention.
> ] {Possibly you did not notice? Not meaning to hurt feelings.)
> ]
> ] > Any help ?
> ] >
> ] Was my reply any help? Want a sample hello world script?
> ]
> ] > pan
> ] >
> ] > ============================================
> ] >   ~~ Be like water, be shapeless ~~
> ] >    Runsun Pan, PhD, 773-834-3965
> ] >  Ecology & Evolution, U of Chicago
> ] > ============================================
> ] >
> ] >
> ] > _______________________________________________
> ] > Tutor maillist  -  Tutor@python.org
> ] > http://mail.python.org/mailman/listinfo/tutor
> ]
> ] --
> ]
> ] end
> ]
> ] Respectfully,
> ]              Kirk D Bailey
> ]
> ]
> ] +---------------------"Thou Art Free." -Eris-----------------------+
> ] | http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
> ] | http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
> ] +------------------Thinking| NORMAL |Thinking----------------------+
> ]                            +--------+
> ] -------------------------------------------
> ] Introducing NetZero Long Distance
> ] Unlimited Long Distance only $29.95/ month!
> ] Sign Up Today! www.netzerolongdistance.com
> ]
> ]
> ]
> ] Message: 10
> ] Date: Sat, 20 Jul 2002 01:21:35 -0400
> ] From: Kirk Bailey <idiot1@netzero.net>
> ] Organization: Silas Dent Memorial Cabal of ERIS Esoteric and hot
> ] dog boiling society
> ] To: "tutor@python.org" <tutor@python.org>
> ] Subject: Re: [Tutor] cgi not executed when accessed through browser
> ]
> ] My first simple one.
> ]
> ] ns# list first.py
> ] Listing of file first.py in directory:/www/www.howlermonkey.net/cgi-bin
> ]
> ] #!/usr/local/bin/python
> ] print "Content-type: text/html"
> ] print
> ] print "<title>First program</title></head>"
> ] print "<body bgcolor=\"FFFFFF\" text=\"000000\" link=\"0000FF\">"
> ] print '<P>'
> ] print "Hello world!"
> ] print '<P>'
> ] print '</body></html>'
> ]
> ] And then a not so simple one:
> ]
> ] ns# list helloworld.py
> ] Listing of file helloworld.py in
> ] directory:/www/www.howlermonkey.net/cgi-bin
> ]
> ] #!/usr/local/bin/python
> ] #import cgi
> ] print "Content-Type: text/html"     # HTML is following
> ] print                               # blank line, end of headers
> ] print "<TITLE>CGI script output</TITLE>"
> ] print "</head>"
> ] print "<body bgcolor=\"#FFFFFF\" text=\"#000000\" ><blockquote>"
> ] print "<P>"
> ] print "<center><H1>This is my first CGI script</H1></center>"
> ] print "<P>\n<br>"
> ] print "Hello, world!"
> ] print "<P>"
> ] print "this is my very first python cgi script, and it works! YAHOO!"
> ] print "<p>"
> ] print "getting the quotes in the BODY statement to come out failed until
> ] I remem
> ] bered"
> ] print "to ise a \\ in front of the quote so it would be a literal
> ] instead of a "
> ] print "end to a print declaration. So exxcited I plum forgot, ant
> ] really,"
> ] print "that's the same as in a shell script, pure human stupidity and
> ] ham handed
> ] ness,"
> ] print "but it's fine <i>NOW</i>. Ya know, I could do a file copy in and
> ] print ou
> ] t and"
> ] print "store the content as a simple heml file, and less work on
> ] changing or cre
> ] ating"
> ] print "the scripts... hmmm..."
> ] print "<P>\n<br>"
> ] print "</html>"
> ] print "</body>"
> ]
> ]
> ] ns#
> ] 'list' is a shell script I wrote, which is so simple it is disgusting.
> ]
> ] ns# list /usr/local/sbin/list
> ] Listing of file /usr/local/sbin/list in
> ] directory:/www/www.howlermonkey.net/cgi-bin
> ]
> ] #! /bin/sh
> ] echo -n Listing of file $1 in directory:
> ] pwd
> ] echo
> ] more < $1;
> ] echo
> ]
> ] Home some of this helps.
> ]
> ] --
> ]
> ] end
> ]
> ] Respectfully,
> ]              Kirk D Bailey
> ]
> ]
> ] +---------------------"Thou Art Free." -Eris-----------------------+
> ] | http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
> ] | http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
> ] +------------------Thinking| NORMAL |Thinking----------------------+
> ]                            +--------+
> ] -------------------------------------------
> ] Introducing NetZero Long Distance
> ] Unlimited Long Distance only $29.95/ month!
> ] Sign Up Today! www.netzerolongdistance.com
> ]
> ]
> ]
> ]
> ] --__--__--
> ]
> ] _______________________________________________
> ] Tutor maillist  -  Tutor@python.org
> ] http://mail.python.org/mailman/listinfo/tutor
> ]
> ]
> ] End of Tutor Digest
> ]
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 

end

Respectfully,
             Kirk D Bailey


+---------------------"Thou Art Free." -Eris-----------------------+
| http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
| http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
+------------------Thinking| NORMAL |Thinking----------------------+
                           +--------+
-------------------------------------------
Introducing NetZero Long Distance
Unlimited Long Distance only $29.95/ month!
Sign Up Today! www.netzerolongdistance.com



From ejohnso9@earthlink.net  Sun Jul 21 19:15:57 2002
From: ejohnso9@earthlink.net (Erik Johnson)
Date: Sun, 21 Jul 2002 12:15:57 -0600
Subject: [Tutor] print function (again)
Message-ID: <000d01c230e2$a9b99850$3269fea9@Mako>

This is a multi-part message in MIME format.

------=_NextPart_000_000A_01C230B0.5E2E5FB0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

On Wed, July 17 Guillermo Fernandez was asking about how to print =
without the automatic newline appended:

> I would like to do something like:
>
> print "first fct"
> fct1()
> print " second fct"
> fct2()
> print " third fct"
> fct3()
>
> and have an output like:
> "first fct second fct third fct"


Steve (lonetwin@yahoo.com) responded by saying:

 You need to append a "," at the end for your string, thats all.
ie:
 print "first fct",=20
 fct1()
 print "second fct",
 .....
 .....

will print
 first fct second fct ....
	The comma will aslo take care of adding the space between strings that =
get=20
printed continuously.



    I, too, had the same question as Guillermo and thought I would share =
what I have figured out. The automatic newline is often appropriate and =
therefore often handy, but depending on what you are trying to do, it =
can equally as well be really obnoxious. If you intend to build up a =
string that is going to be separated by spaces then Steve's solution is =
dandy, but if you don't want spaces between what you are outputting in =
separate function calls, then "that simply don't work".

For example:

for x in range(5):
  print x,

0 1 2 3 4


It does NOT print: "01234"

to get the string above, one solution is to call stdout's write() method =
directly:

import sys
for x in range(5):
    sys.stdout.write(x)

01234


to make this a little more convenient, you could always do something of =
this flavor:

>>> def printf(s):          # note that this does not handle variable =
argument lists
        sys.stdout.write(s)

>>> printf
<function printf at 0x00A4F6D0>
>>> for x in range(5):
        printf(x)

=20
01234
>>>=20

    An alternate approach is to simply build up a big string as you go, =
having your functions return strings rather than printing anything and =
then concatenating those together with whatever else you want to print =
and dumping it all at once. This may or may not be convenient.

    I think it is somewhat unfortunate that Python did not adopt a =
Pascal-like approach to this function such as print() giving "normal" =
print behaviour and println() for when you want an extra "\n" on the =
end. I am a PyNewbie and know that much of Python's internals are =
exposed, but I don't readily see a way to hack "print" because it seems =
to be handled differently (keyword?) than other functions. Contrast the =
following:

>>> type(sys.stdout.write)
<type 'instance method'>
>>> sys.stdout.write
<bound method PseudoFile.write of <PyShell.PseudoFile instance at =
0x009F7168>>
>>> type(print)
SyntaxError: invalid syntax
>>> print

>>>=20


    Anyway, I hope that this helps and perhaps more advanced PyHackers =
would care to comment on subverting the print function for one's own =
devices. :)

-ej

------=_NextPart_000_000A_01C230B0.5E2E5FB0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2716.2200" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3D"Courier New" size=3D2>On Wed, July 17 Guillermo =
Fernandez was=20
asking about how to print without the automatic newline =
appended:</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>&gt;</FONT><FONT =
face=3D"Courier New"><FONT=20
size=3D2><I> I would like to do something=20
like:<BR></I>&gt;</FONT></FONT><I><BR></I><FONT face=3D"Courier New"=20
size=3D2>&gt;</FONT><FONT face=3D"Courier New"><FONT size=3D2><I> print =
"first=20
fct"<BR></I>&gt;</FONT></FONT><FONT face=3D"Courier New"><FONT =
size=3D2><I>=20
fct1()<BR></I>&gt;</FONT></FONT><FONT face=3D"Courier New"><FONT =
size=3D2><I> print=20
" second fct"<BR></I>&gt;</FONT></FONT><FONT face=3D"Courier New"><FONT =
size=3D2><I>=20
fct2()<BR></I>&gt;</FONT></FONT><FONT face=3D"Courier New"><FONT =
size=3D2><I> print=20
" third fct"<BR></I>&gt;</FONT></FONT><FONT face=3D"Courier New"><FONT =
size=3D2><I>=20
fct3()<BR></I>&gt;</FONT></FONT><I><BR></I><FONT face=3D"Courier New"=20
size=3D2>&gt;</FONT><FONT face=3D"Courier New"><FONT size=3D2><I> and =
have an output=20
like:<BR></I>&gt;</FONT></FONT><I><FONT face=3D"Courier New" size=3D2> =
"first fct=20
second fct third fct"<BR></FONT></I></DIV>
<DIV><I><FONT face=3D"Courier New" size=3D2></FONT></I>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>Steve (</FONT><A=20
href=3D"mailto:lonetwin@yahoo.com"><FONT face=3D"Courier New"=20
size=3D2>lonetwin@yahoo.com</FONT></A><FONT face=3D"Courier New" =
size=3D2>) responded=20
by saying:</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>&nbsp;You need to append a "," =
at the end=20
for your string, thats all.<BR>ie:<BR> print "first fct", <BR> =
fct1()<BR> print=20
"second fct",<BR> .....<BR> .....<BR><BR>will print<BR> first fct second =
fct=20
....<BR>	The comma will aslo take care of adding the space between =
strings that=20
get <BR>printed continuously.<BR></FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>&nbsp;&nbsp;&nbsp; I, too, had =
the same=20
question as Guillermo and thought I would share what I have figured out. =
The=20
automatic newline is often appropriate and therefore often handy, but =
depending=20
on what you are trying to do, it can equally as well be really =
obnoxious. If you=20
intend to build up a string that is going to be separated by spaces then =
Steve's=20
solution is dandy, but if you don't want spaces between what you are =
outputting=20
in separate function calls, then "that&nbsp;simply don't =
work".</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>For example:</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>for x in range(5):<BR>&nbsp; =
print=20
x,</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>0 1 2 3 4</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>It does NOT print: =
"01234"</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>to get the string above, one =
solution is to=20
call stdout's write() method directly:</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>import sys</FONT></DIV>
<DIV>
<DIV><FONT face=3D"Courier New" size=3D2>for x in =
range(5):<BR>&nbsp;&nbsp;&nbsp;=20
sys.stdout.write(x)</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>01234</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>to make this a little more =
convenient, you=20
could always&nbsp;do something of this flavor:</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>&gt;&gt;&gt; def=20
printf(s):&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # note =
that=20
this does not handle variable argument lists</FONT></DIV>
<DIV><FONT face=3D"Courier New" =
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
sys.stdout.write(s)</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>&gt;&gt;&gt; =
printf<BR>&lt;function printf=20
at 0x00A4F6D0&gt;<BR>&gt;&gt;&gt; for x in=20
range(5):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
printf(x)</FONT></DIV>
<DIV><FONT face=3D"Courier New"></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>&nbsp;<BR>01234<BR>&gt;&gt;&gt; =

</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>&nbsp;&nbsp;&nbsp; An alternate =
approach is=20
to simply build up a big string as you go, having your functions return =
strings=20
rather than printing anything and&nbsp;then concatenating those together =
with=20
whatever else you want to print and dumping it all at once. This may or =
may not=20
be convenient.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>&nbsp;&nbsp;&nbsp; I think it =
is somewhat=20
unfortunate that Python did not adopt a Pascal-like approach to this =
function=20
such as print() giving "normal" print behaviour and println() for when =
you want=20
an extra "\n" on the end. I am a PyNewbie and know that much of Python's =

internals are exposed, but I don't readily see a way to hack "print" =
because it=20
seems to be handled differently (keyword?) than other functions. =
Contrast the=20
following:</FONT></DIV>
<DIV><FONT size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>&gt;&gt;&gt;=20
type(sys.stdout.write)<BR>&lt;type 'instance method'&gt;<BR>&gt;&gt;&gt; =

sys.stdout.write<BR>&lt;bound method PseudoFile.write of =
&lt;PyShell.PseudoFile=20
instance at 0x009F7168&gt;&gt;<BR>&gt;&gt;&gt; =
type(print)<BR>SyntaxError:=20
invalid syntax<BR>&gt;&gt;&gt; print</FONT></DIV>
<DIV><FONT face=3D"Courier New"></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>&gt;&gt;&gt; </FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>&nbsp;&nbsp;&nbsp; Anyway, I =
hope that this=20
helps and perhaps more advanced PyHackers&nbsp;would care to comment on=20
subverting the print function for one's own devices. :)</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>-ej</FONT></DIV></BODY></HTML>

------=_NextPart_000_000A_01C230B0.5E2E5FB0--




From ak@silmarill.org  Sun Jul 21 21:15:53 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Sun, 21 Jul 2002 16:15:53 -0400
Subject: [Tutor] print function (again)
In-Reply-To: <000d01c230e2$a9b99850$3269fea9@Mako>
References: <000d01c230e2$a9b99850$3269fea9@Mako>
Message-ID: <20020721201553.GA10017@ak.silmarill.org>

On Sun, Jul 21, 2002 at 12:15:57PM -0600, Erik Johnson wrote:
> On Wed, July 17 Guillermo Fernandez was asking about how to print without the automatic newline appended:
> 
> > I would like to do something like:
> >
> > print "first fct"
> > fct1()
> > print " second fct"
> > fct2()
> > print " third fct"
> > fct3()
> >
> > and have an output like:
> > "first fct second fct third fct"
> 
> 
> Steve (lonetwin@yahoo.com) responded by saying:
> 
>  You need to append a "," at the end for your string, thats all.
> ie:
>  print "first fct", 
>  fct1()
>  print "second fct",
>  .....
>  .....
> 
> will print
>  first fct second fct ....
> 	The comma will aslo take care of adding the space between strings that get 
> printed continuously.
> 
> 
> 
>     I, too, had the same question as Guillermo and thought I would share what I have figured out. The automatic newline is often appropriate and therefore often handy, but depending on what you are trying to do, it can equally as well be really obnoxious. If you intend to build up a string that is going to be separated by spaces then Steve's solution is dandy, but if you don't want spaces between what you are outputting in separate function calls, then "that simply don't work".
> 
> For example:
> 
> for x in range(5):
>   print x,
> 
> 0 1 2 3 4
> 
> 
> It does NOT print: "01234"
> 
> to get the string above, one solution is to call stdout's write() method directly:
> 
> import sys
> for x in range(5):
>     sys.stdout.write(x)
> 
> 01234
> 
> 
> to make this a little more convenient, you could always do something of this flavor:
> 
> >>> def printf(s):          # note that this does not handle variable argument lists
>         sys.stdout.write(s)

You could just do: printf = sys.stdout.write

> 
> >>> printf
> <function printf at 0x00A4F6D0>
> >>> for x in range(5):
>         printf(x)
> 
>  
> 01234
> >>> 
> 
>     An alternate approach is to simply build up a big string as you go, having your functions return strings rather than printing anything and then concatenating those together with whatever else you want to print and dumping it all at once. This may or may not be convenient.
> 
>     I think it is somewhat unfortunate that Python did not adopt a Pascal-like approach to this function such as print() giving "normal" print behaviour and println() for when you want an extra "\n" on the end. I am a PyNewbie and know that much of Python's internals are exposed, but I don't readily see a way to hack "print" because it seems to be handled differently (keyword?) than other functions. Contrast the following:

In my opinion, a language should have shortcuts for the most common use
paths. print is such a shortcut, because you mostly want to have a
space between printed things. I think you're simply accustomed to
pascal approach and that's why you see it as normal, a new user may as
well look at pascals' print not putting spaces in and think that very
odd and awkward.

> 
> >>> type(sys.stdout.write)
> <type 'instance method'>
> >>> sys.stdout.write
> <bound method PseudoFile.write of <PyShell.PseudoFile instance at 0x009F7168>>
> >>> type(print)
> SyntaxError: invalid syntax
> >>> print
> >>>
Yes, print is not a function, it's a keyword - the whole point of it is
being a shortcut, not having to write the (). I think this whole
mechanism of print and sys.stdout is very well thought out, although
sys.stdout trick should perhaps be mentioned more often in tutorials
because I remember seeing this question many many times..

 - Andrei
> 
> >>> 
> 
> 
>     Anyway, I hope that this helps and perhaps more advanced PyHackers would care to comment on subverting the print function for one's own devices. :)
> 
> -ej

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From alan.gauld@bt.com  Sun Jul 21 23:26:59 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 21 Jul 2002 23:26:59 +0100
Subject: [Tutor] Line in a file
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C75E@mbtlipnt02.btlabs.bt.co.uk>

> exceptions are simply generated within code libraries, 

Yes, if you include a function definition as a 'code library'.

> by client code, regardless of who is actually writing it.

There are occasions when you might handle it locally.
A variant of the ubiquitous python idiom of

while 1:
   try:
      # do somerthing
      if exit_condition: raise MyException
      # do more
   except MyException:
       if <we really want to stop>: break

Here we use the exception as a kind of goto before finally 
breaking out of the loop - useful for tidying up open comms 
maybe...

But usually we use raise internally and it gets dealt 
with by the cient.

> > You'd need to create your own file subclass:
> 
> > class RandomFile:

> I see... I don't actually extend the "open()" class at all 

Ideally you would, but the way Python implements files the 
open *function* returns a file *object*. Because open is 
outside the file class it makes it hard to inherit from 
even in 2.2 new classes. So we fall back on delegation 
and making a class that looks like a file but using the 
constructor to call open... Its not really very nice and 
if anyone knows a better way of  'subclassing' files I'd 
love to hear about it. - One of Pythons few wrinkles IMHO...

> is a good illustration of the difference between the "is a" 
> and the "has a" relationship?  :)

An illustration certainly, whether it's good or not....!

Alan G



From alan.gauld@bt.com  Sun Jul 21 23:30:01 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 21 Jul 2002 23:30:01 +0100
Subject: [Tutor] Instances
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C75F@mbtlipnt02.btlabs.bt.co.uk>

> But, when I include n = test() in there, I tend to get this error 
> message:
> 
> Traceback (most recent call last):
>   File "C:\temp\slett2.py", line 3, in test
>     d = test()
> NameError: name 'test' is not defined

"Line 3" suggests you have it at the top of your file?
Put it at the very end, then the definition of test 
will be visible.

> >In fact you can miss the if test out and just put a last line of
> >
> >test()

Note that I mentioned putting it as "the last line".

Alan G



From guillermo.fernandez@epfl.ch  Mon Jul 22 01:44:57 2002
From: guillermo.fernandez@epfl.ch (Guillermo Fernandez)
Date: Mon, 22 Jul 2002 10:14:57 +0930
Subject: [Tutor] print function (again)
References: <000d01c230e2$a9b99850$3269fea9@Mako> <20020721201553.GA10017@ak.silmarill.org>
Message-ID: <3D3B5589.922B06C8@epfl.ch>

> >  You need to append a "," at the end for your string, thats all.
> > ie:
> >  print "first fct",
> >  fct1()
> >  print "second fct",
> >  .....
> >  .....
> >
> > will print
> >  first fct second fct ....
> >       The comma will aslo take care of adding the space between strings that get
> > printed continuously.

> >     I, too, had the same question as Guillermo and thought I would share what I have figured out. The automatic newline is often appropriate and therefore often handy, but depending on what you are trying to do, it can equally as well be really obnoxious. If you intend to build up a string that is going to be separated by spaces then Steve's solution is dandy, but if you don't want spaces between what you are outputting in separate function calls, then "that simply don't work".

Thank you for your answers. But I still have a little problem.
Both solutions work for the printing of a line, but I have some timing
problems in the printing. What I mean is that both methods first
construct the string but they only print it when they see the \n
caracter (or when the last "print" is encountered).

Look at this example (it is _very_ unelegant, sorry, but it shows the
matter):

import sys
for i in range(10):
    for j in range(1000000):
        pass
    #    print i,
    sys.stdout.write(str(i))

When you run it, it will first calculate the string (without printing
it!!) doing the 10 loops (and because of that the 1000000 loops as well)
and only at the end it will print the "0123456789" (or "0 1 2 3 4 5 6 7
8 9" if use print with coma). But I'm looking for a method that first do
the 1000000 loop, then print 0 then calculates again the 1000000 loop
and then print 1 in the same line... I think you get the idea. Is there
a kind of 'flush' method to force the printing without forcing the
newline?

Thank you.

Guille



From vince_khoo@yahoo.com  Mon Jul 22 05:16:10 2002
From: vince_khoo@yahoo.com (=?iso-8859-1?q?Vince=20Khoo?=)
Date: Mon, 22 Jul 2002 05:16:10 +0100 (BST)
Subject: [Tutor] hi
Message-ID: <20020722041610.84610.qmail@web20502.mail.yahoo.com>

--0-682786302-1027311370=:82733
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 8bit


Hi,

I read that it's better to write a programme with the notepad and then run it with the interpreter, how can I do this?

regards

Vince




---------------------------------
Get a bigger mailbox -- choose a size that fits your needs.

http://uk.docs.yahoo.com/mail_storage.html
--0-682786302-1027311370=:82733
Content-Type: text/html; charset=iso-8859-1
Content-Transfer-Encoding: 8bit

<P>Hi,</P>
<P>I read that it's better to write a programme with the notepad and then run it with the interpreter, how can I do this?</P>
<P>regards</P>
<P>Vince</P><p><p><br><hr size=1><a href="http://uk.yahoo.com/mail/tagline_xtra/?http://uk.docs.yahoo.com/mail_storage.html"><b><font face="Arial" size="2">Get a bigger mailbox -- choose a size that fits your needs.</font></b></a><br><br><a href="http://uk.yahoo.com/mail/tagline_xtra/?http://uk.docs.yahoo.com/mail_storage.html"><font face="Arial" size="2">http://uk.docs.yahoo.com/mail_storage.html</font></a>
--0-682786302-1027311370=:82733--



From dyoo@hkn.eecs.berkeley.edu  Mon Jul 22 07:20:30 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 21 Jul 2002 23:20:30 -0700 (PDT)
Subject: [Tutor] print function (again)
In-Reply-To: <3D3B5589.922B06C8@epfl.ch>
Message-ID: <Pine.LNX.4.44.0207212312370.23484-100000@hkn.eecs.berkeley.edu>

> Thank you for your answers. But I still have a little problem. Both
> solutions work for the printing of a line, but I have some timing
> problems in the printing. What I mean is that both methods first
> construct the string but they only print it when they see the \n
> caracter (or when the last "print" is encountered).

This is an issue about "buffered" output: most systems try to delay
printing a line out until it has to, that is, only after it sees a '\n'.


> Look at this example (it is _very_ unelegant, sorry, but it shows the
> matter):
>
> import sys
> for i in range(10):
>     for j in range(1000000):
>         pass
>     #    print i,
>     sys.stdout.write(str(i))
>
> When you run it, it will first calculate the string (without printing
> it!!)


Actually, it is printing it to sys.stdout; it's just that stdout does not
display things until the line is terminated or flushed.  This is often
done for efficiency reasons: it's easier for the system to write out a
line all at once, rather than in small bits.


'stdout' is short for 'standard output', and standard output can be
thought of as a buffered file.  If you'd like, you can try out the
following code to see what happens with unbuffered output:

###
import sys
for i in range(10):
    for j in range(1000000):
        pass
    #    print i,
    sys.stderr.write(str(i))
###

I've changed the file that we're using to write, from 'stdout' to
'stderr'.  This stderr 'standard error' file, like stdout, also prints to
screen, and should be unbuffered.



> 8 9" if use print with coma). But I'm looking for a method that first do
> the 1000000 loop, then print 0 then calculates again the 1000000 loop
> and then print 1 in the same line... I think you get the idea. Is there
> a kind of 'flush' method to force the printing without forcing the
> newline?


###
>>> sys.stdout.flush
<built-in method flush of file object at 0x80fe200>
###

Yes.  *grin*  Try sys.stdout.flush() to force stdout to write what it
knows to screen.


Good luck to you!




From dyoo@hkn.eecs.berkeley.edu  Mon Jul 22 07:25:15 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 21 Jul 2002 23:25:15 -0700 (PDT)
Subject: [Tutor] hi
In-Reply-To: <20020722041610.84610.qmail@web20502.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0207212320470.23484-100000@hkn.eecs.berkeley.edu>


On Mon, 22 Jul 2002, [iso-8859-1] Vince Khoo wrote:

> I read that it's better to write a programme with the notepad and then
> run it with the interpreter, how can I do this?

Hi Vince,

Actually, it's even easier if you use a text editor program called IDLE.
IDLE comes with Python, so you should have it installed already if you've
installed Python.


I have a small tutorial on using IDLE here; it might be helpful for you.
Here you go:

    http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/

This tutorial tries to show how you can start up IDLE, write a small
program, and save and restore your programs for later experiments. If you
have any questions about it, please feel free to ask here.


I hope this helps you!




From dyoo@hkn.eecs.berkeley.edu  Mon Jul 22 07:47:24 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 21 Jul 2002 23:47:24 -0700 (PDT)
Subject: [Tutor] Help with python parsing please..  [hunting down a bug]
In-Reply-To: <Pine.LNX.4.44.0207202130350.30045-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0207212326410.23484-100000@hkn.eecs.berkeley.edu>


> Hmmm.... what does the 'commands' module look like?  Since that's the
> module responsible for evaluating strings, let's take a look at that
> module.

Hi SA,

Just doing a followup; I suddenly realized that commands.getoutput() is
meant to evaluate strings in the shell:

    http://www.python.org/doc/lib/module-commands.html


So commands.getoutput() is not meant to do Python stuff at all.  This is
why everything appears to be running through zsh: it is!  *grin*


You may want to check a previous version of the 'expyth()'
python-executing code that you had used a while back, like:

    http://mail.python.org/pipermail/tutor/2002-June/015009.html

Somewhere along the line, it looks like you switched from using
os.popen()'ing a python session to using commands.getoutput(), and that's
probably where the bug was introduced: things like 'print' still appeared
to work fine, but, behind the scenes, you were using zsh from that point
forward.  Switch it back to os.popen(), and things should go back to
normal.


But although os.popen() will work, if you want to evaluate Python strings,
perhaps the built-in 'exec()' execution function would work better for
you.  Here's an example of how we can use it:

###
>>> def my_python_exec(code_string):
...     """Evaluates a string as Python code, and returns its
... output as a string."""
...     old_stdout, new_stdout = sys.stdout, StringIO.StringIO()
...     sys.stdout = new_stdout
...     exec(code_string)
...     sys.stdout = old_stdout
...     return new_stdout.getvalue()
...
>>> some_code = """
... print "hello"
... def square(x): return x * x
... print "the square of 3 is", square(3)
... """
>>> my_python_exec(some_code)
'hello\nthe square of 3 is 9\n'
###


Be aware that I haven't put ANY security in here; any code that we send to
my_python_exec() has the exact same privileges as our own code.  This may
not be a Good Thing for the paranoid.

But then, it should be good enough for the moment; for more security, the
restricted execution module, 'rexec', is a better choice:

    http://www.python.org/doc/lib/module-rexec.html

We can talk about how to use 'rexec' if you'd like.



Good luck to you!




From glingl@aon.at  Mon Jul 22 14:19:07 2002
From: glingl@aon.at (Gregor Lingl)
Date: Mon, 22 Jul 2002 15:19:07 +0200
Subject: [Tutor] Can I ask if Tkinter.mainloop() is running?
Message-ID: <3D3C064B.8080806@aon.at>

Please do not consider this to be a cross posting (sorry Danny),
but I didn't receive an answer from c.l.py.

Wohin soll ich mich wenden?  (Where shall I turn to? (?) )

Hi!

QUESTION 1:
===========

It's possible (and sometimes convenient) to develop
Tkinter-programs interactively with IDLE provided
one doesn't write the mainloop() call into the program
file. Of course one can add this later if one wants
to run the program standalone.

I'd like to know if - and how - it were possible
to use some test if a Tkinter.mainloop (in this case
the one of IDLE) is already running, thus having
a statement similar to

if __name__ == '__main__':
     < stuff>

at the end of the program of the form:

if not <mainloop already active>:
    app.mainloop()

so one could run the program from IDLE as well as
from the commandline.

QUESTION 2:
===========

Is there a special mailing list or something similar
dedicated to Tkinter related stuff?

Thanks in advance
Gregor






From wolf_binary@hotmail.com  Mon Jul 22 14:27:37 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Mon, 22 Jul 2002 08:27:37 -0500
Subject: [Tutor] engines
Message-ID: <DAV50zCWfbB1kOXXGQ300011020@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_0024_01C23159.A30D3F80
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

hi all,

I meant in the context of a game engine.  I have thought it to mean the =
main portion of the program that does most of the work and then an =
interface is built over it.  It is then reusable to make other =
applications by just making different interfaces.  This was my =
impression of an engine.  Am I right or wrong?

Cameron

------=_NextPart_000_0024_01C23159.A30D3F80
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2713.1100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>hi all,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I meant in the context of a game =
engine.&nbsp; I=20
have thought it to mean the main portion of the program that does most =
of the=20
work and then an interface is built over it.&nbsp; It is then reusable =
to make=20
other applications by just making different interfaces.&nbsp; This was =
my=20
impression of an engine.&nbsp; Am I right or wrong?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Cameron</FONT></DIV></BODY></HTML>

------=_NextPart_000_0024_01C23159.A30D3F80--



From shalehperry@attbi.com  Mon Jul 22 17:07:58 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 22 Jul 2002 09:07:58 -0700 (PDT)
Subject: [Tutor] engines
In-Reply-To: <DAV50zCWfbB1kOXXGQ300011020@hotmail.com>
Message-ID: <XFMail.20020722090758.shalehperry@attbi.com>

On 22-Jul-2002 Cameron Stoner wrote:
> hi all,
> 
> I meant in the context of a game engine.  I have thought it to mean the main
> portion of the program that does most of the work and then an interface is
> built over it.  It is then reusable to make other applications by just making
> different interfaces.  This was my impression of an engine.  Am I right or
> wrong?
> 
> Cameron

nope, that about covers it.

Take one of the Doom/Quake engines.  It knows how to place a character (user or
computer), perform the various math problems, display terrain, deal with user
input, etc.  Each game that uses the engine much implement the characters,
terrain, and game problems (locks, secrets, etc).



From shey@argonaut.com  Mon Jul 22 18:15:40 2002
From: shey@argonaut.com (shey crompton)
Date: Mon, 22 Jul 2002 18:15:40 +0100
Subject: [Tutor] Curious newbie
Message-ID: <415C917D807AD411B72C00805FF7330B0383626F@MAILSRV>

Hi all,
If I create a program like a small text based guessing game using Python,
and I want to send it to mates to try out, do they have to have python
installed to be able to play the game? If my mates don't have to have IDLE
installed, how would they (in windows) run the game? 

Thanks,

Shey



From shalehperry@attbi.com  Mon Jul 22 18:22:25 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 22 Jul 2002 10:22:25 -0700 (PDT)
Subject: [Tutor] Curious newbie
In-Reply-To: <415C917D807AD411B72C00805FF7330B0383626F@MAILSRV>
Message-ID: <XFMail.20020722102225.shalehperry@attbi.com>

On 22-Jul-2002 shey crompton wrote:
> Hi all,
> If I create a program like a small text based guessing game using Python,
> and I want to send it to mates to try out, do they have to have python
> installed to be able to play the game? If my mates don't have to have IDLE
> installed, how would they (in windows) run the game? 
> 

from a command prompt they can run your program directly 'python foo.py'.



From rob@uselesspython.com  Mon Jul 22 18:27:26 2002
From: rob@uselesspython.com (Rob)
Date: Mon, 22 Jul 2002 12:27:26 -0500
Subject: [Tutor] Curious newbie
In-Reply-To: <415C917D807AD411B72C00805FF7330B0383626F@MAILSRV>
Message-ID: <MPEOIFCOPCIHEDCLBLPBGELFCAAA.rob@uselesspython.com>

Python is an interpreted language, which means that one must have a Python
interpreter installed in order to run Python programs. There are certain
special things you can do, such as bundle up a Python interpreter with your
program for distribution, so there are different ways of looking at it.

Rob Andrews
http://uselesspython.com

> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> shey crompton
> Sent: Monday, July 22, 2002 12:16 PM
> To: 'tutor@python.org'
> Subject: [Tutor] Curious newbie
>
>
> Hi all,
> If I create a program like a small text based guessing game using Python,
> and I want to send it to mates to try out, do they have to have python
> installed to be able to play the game? If my mates don't have to have IDLE
> installed, how would they (in windows) run the game?
>
> Thanks,
>
> Shey
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>





From terjeja@hotmail.com  Mon Jul 22 20:05:31 2002
From: terjeja@hotmail.com (Terje Johan Abrahamsen)
Date: Mon, 22 Jul 2002 19:05:31 +0000
Subject: [Tutor] Curious newbie
Message-ID: <F126L5HppQBSYVfxM2R000174b3@hotmail.com>

But, in order to be able to write python foo.py, they need to install 
Python, don't they. I doubt that MS sends out the Python intepreter in their 
operating system. But, go to http://starship.python.net/crew/theller/py2exe/ 
and get the Py2exe program. That will make Python into exe files, that can 
be ran directly.

>
>
>On 22-Jul-2002 shey crompton wrote:
> > Hi all,
> > If I create a program like a small text based guessing game using 
>Python,
> > and I want to send it to mates to try out, do they have to have python
> > installed to be able to play the game? If my mates don't have to have 
>IDLE
> > installed, how would they (in windows) run the game?
> >
>
>from a command prompt they can run your program directly 'python foo.py'.
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor




_________________________________________________________________
MSN Photos is the easiest way to share and print your photos: 
http://photos.msn.com/support/worldwide.aspx




From tjenkins@devis.com  Mon Jul 22 22:23:26 2002
From: tjenkins@devis.com (Tom Jenkins)
Date: 22 Jul 2002 17:23:26 -0400
Subject: [Tutor] little something in the way of file parsing
In-Reply-To: <XFMail.20020719133629.shalehperry@attbi.com>
References: <XFMail.20020719133629.shalehperry@attbi.com>
Message-ID: <1027373006.629.74.camel@asimov>

On Fri, 2002-07-19 at 16:36, Sean 'Shaleh' Perry wrote:
> 
> On 19-Jul-2002 Erik Price wrote:
> > On Friday, July 19, 2002, at 02:49  PM, Sean 'Shaleh' Perry wrote:
> > 
[snip]
> >> # note I use the readline() idiom because there is currently 10 
> >> thousand plus
> >> # entries in the file which equates to some 90,000 lines.
> >>
> >> while 1:
> >>     line = fd.readline()
> > 
> > I assume that this comment means that you use readline() as opposed to 
> > readlines() ?  In other words, what are you actually saying in this 
> > comment (or rather why did you feel the need to clarify why you chose 
> > readline() ).
> > 
> 
> I added this comment for the tutor list.  In many intro examples you see:
> 
> for line in file.readlines()
>   handle(line)
> 
> which is great for quicky code.  However readlines() returns a list of strings.
> In my case it returns a 100 thousand element list of strings -- memory wasted.
> 

To further along Danny's idea of digging into the code...
I have a question as to why xreadlines wouldn't work here?  It seems
that this is exactly what xreadlines is for; iterating over a large file
without loading it all into memory at once.  Ah, wait xreadlines is only
available for 2.1+, was that it?

-- 

Tom Jenkins
Development InfoStructure
http://www.devis.com





From bsamal@psygenomics.com  Mon Jul 22 23:03:05 2002
From: bsamal@psygenomics.com (bsamal@psygenomics.com)
Date: Mon, 22 Jul 2002 18:03:05 -0400
Subject: [Tutor] parsing unigene data
Message-ID: <H00000a2000c52b1.1027375385.pobox@MHS>

--openmail-part-001f41c4-00000002
Content-Type: text/plain; charset=ISO-8859-1
Content-Disposition: inline; filename="BDY.RTF"
	;Creation-Date="Mon, 22 Jul 2002 18:03:05 -0400"
Content-Transfer-Encoding: quoted-printable


I am interested to use Python to parse flat files from NCBI Unigene
data. Are there any module available for this?=20
Thanks
Babru


--openmail-part-001f41c4-00000002
Content-Type: application/rtf
Content-Disposition: attachment; filename="BDY.RTF"
	;Creation-Date="Mon, 22 Jul 2002 18:03:05 -0400"
Content-Transfer-Encoding: base64

e1xydGYxXGFuc2lcYW5zaWNwZzEyNTJcZnJvbXRleHQgXGRlZmYwe1xmb250dGJsDQp7XGYw
XGZzd2lzcyBBcmlhbDt9DQp7XGYxXGZtb2Rlcm4gQ291cmllciBOZXc7fQ0Ke1xmMlxmbmls
XGZjaGFyc2V0MiBTeW1ib2w7fQ0Ke1xmM1xmbW9kZXJuXGZjaGFyc2V0MCBDb3VyaWVyIE5l
dzt9fQ0Ke1xjb2xvcnRibFxyZWQwXGdyZWVuMFxibHVlMDtccmVkMFxncmVlbjBcYmx1ZTI1
NTt9DQpcdWMxXHBhcmRccGxhaW5cZGVmdGFiMzYwIFxmMFxmczIwIFxwYXINCkkgYW0gaW50
ZXJlc3RlZCB0byB1c2UgUHl0aG9uIHRvIHBhcnNlIGZsYXQgZmlsZXMgZnJvbSBOQ0JJIFVu
aWdlbmUgZGF0YS4gQXJlIHRoZXJlIGFueSBtb2R1bGUgYXZhaWxhYmxlIGZvciB0aGlzPyBc
cGFyDQpUaGFua3NccGFyDQpCYWJydVxwYXINCn0=

--openmail-part-001f41c4-00000002--




From dyoo@hkn.eecs.berkeley.edu  Mon Jul 22 23:05:20 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 22 Jul 2002 15:05:20 -0700 (PDT)
Subject: [Tutor] Can I ask if Tkinter.mainloop() is running?
In-Reply-To: <3D3C064B.8080806@aon.at>
Message-ID: <Pine.LNX.4.44.0207221437040.7131-100000@hkn.eecs.berkeley.edu>


On Mon, 22 Jul 2002, Gregor Lingl wrote:

> It's possible (and sometimes convenient) to develop Tkinter-programs
> interactively with IDLE provided one doesn't write the mainloop() call
> into the program file. Of course one can add this later if one wants to
> run the program standalone.
>
> I'd like to know if - and how - it were possible to use some test if a
> Tkinter.mainloop (in this case the one of IDLE) is already running, thus
> having a statement similar to
>
> if __name__ == '__main__':
>      < stuff>
>
> at the end of the program of the form:
>
> if not <mainloop already active>:
>     app.mainloop()


Yes, this is possible if we intentionally raise an exception, or use the
convenient 'traceback' module.


When an exception is raised to us, it gives us information about the 'call
stack', that is, it tells us which functions were running right before the
exception was raised.  Although we often use 'traceback' as a debugging
tool, we can abuse this a bit to help us write a mainloop() detector.


Here's what a call stack looks like, just to get a feel for what we're
about to try:

###
>>> def foo(): return bar()
...
>>> def bar(): return traceback.extract_stack()
...
>>> foo()
[('<stdin>', 1, '?', None), ('<stdin>', 1, 'foo', None), ('<stdin>', 1,
'bar', None)]
>>> bar()
[('<stdin>', 1, '?', None), ('<stdin>', 1, 'bar', None)]
###

The '?' at the very bottom of the call stack represents the interpreter.
(Forgive me for using 'foo' and 'bar' as names.)


So we can detect if we've been called while within Tkinter's mainloop by
examining the call stack.  I did some experimentation, and came up with
this:

###
def getTkinterLocation():
    """Returns the location of the Tkinter module."""
    import Tkinter
    if Tkinter.__file__.endswith('pyc'):
        return Tkinter.__file__[:-1]
    return Tkinter.__file__


def inTkinterMainloop():
    """Returns true if we're called in the context of Tkinter's
mainloop(), and false otherwise."""
    stack = traceback.extract_stack()
    tkinter_file = getTkinterLocation()
    for (file_name, lineno, function_name, text) in stack:
        if (file_name, function_name) == (tkinter_file, 'mainloop'):
            return 1
    return 0
###



With recent developments in IDLEfork (the development version of IDLE),
though, you shouldn't need to do this check because Tkinter programs
should work cleanly in IDLE now.


You may want try the IDLEfork version of IDLE and see if this has been
fixed already:

    http://idlefork.sourceforge.net/




> QUESTION 2:
> ===========
>
> Is there a special mailing list or something similar
> dedicated to Tkinter related stuff?

Hmmm!  I don't know about this one.  Does anyone else know?




From dyoo@hkn.eecs.berkeley.edu  Mon Jul 22 23:20:08 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 22 Jul 2002 15:20:08 -0700 (PDT)
Subject: [Tutor] parsing unigene data
In-Reply-To: <H00000a2000c52b1.1027375385.pobox@MHS>
Message-ID: <Pine.LNX.4.44.0207221515290.7131-100000@hkn.eecs.berkeley.edu>


On Mon, 22 Jul 2002 bsamal@psygenomics.com wrote:

> I am interested to use Python to parse flat files from NCBI Unigene
> data. Are there any module available for this?

Hello!


By the way, a good place to ask bioinformatics related questions may be
the biopython-users group:

    http://biopython.org/mailman/listinfo/biopython/


About that Unigene parser... you may want to check Biopython for this:

    http://biopython.org/

There does appear to be a UniGene parser in their CVS repository, so try
checking out a copy of Biopython from the public CVS server.



Back to inserting mitochondrial and chloroplast Genbank sequences for
me... *grin*  Best of wishes to you!




From marta_andrea@libero.it  Mon Jul 22 23:39:50 2002
From: marta_andrea@libero.it (Andrea Valle)
Date: Tue, 23 Jul 2002 00:39:50 +0200
Subject: R: [Tutor] Can I ask if Tkinter.mainloop() is running?
In-Reply-To: <Pine.LNX.4.44.0207221437040.7131-100000@hkn.eecs.berkeley.edu>
Message-ID: <DNEFLBNHCGCPPIGNHGILGEEPCCAA.marta_andrea@libero.it>


> QUESTION 2:
> ===========
>
> Is there a special mailing list or something similar
> dedicated to Tkinter related stuff?

Hmmm!  I don't know about this one.  Does anyone else know?



This would be absolutely helpful. I started writing simple plotting
resources for my program in Tk. Absolutely fantastic. But resources on web
are really few. The two tutorial are mainly focused to description of
objects (canvas, etc.). I am a dummy: I need to understand how to link all
these objects together, retrieve variables, have more widgets active etc.

Do anyone know about resorces on Tk?

best

-a-

Andrea Valle
via Lanzo 108
10073 - Cirie (TO)
ITALIA
011/921 45 84 - 349/55 47 343





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




From shalehperry@attbi.com  Mon Jul 22 23:42:16 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 22 Jul 2002 15:42:16 -0700 (PDT)
Subject: [Tutor] little something in the way of file parsing
In-Reply-To: <1027373006.629.74.camel@asimov>
Message-ID: <XFMail.20020722154216.shalehperry@attbi.com>

> 
> To further along Danny's idea of digging into the code...
> I have a question as to why xreadlines wouldn't work here?  It seems
> that this is exactly what xreadlines is for; iterating over a large file
> without loading it all into memory at once.  Ah, wait xreadlines is only
> available for 2.1+, was that it?
> 

I learned python in the 1.5 days so I often forget about items like xreadlines.
I am not certain how this function would deal with a 200 thousand line file
though.

There are other 2.x isms in the code (setdefault) so ignoring xreadlines for
only that reason would be silly.



From glingl@aon.at  Tue Jul 23 01:21:22 2002
From: glingl@aon.at (Gregor Lingl)
Date: Tue, 23 Jul 2002 02:21:22 +0200
Subject: [Tutor] No more need to ask if Tkinter.mainloop() is running?
References: <Pine.LNX.4.44.0207221437040.7131-100000@hkn.eecs.berkeley.edu>
Message-ID: <3D3CA182.6050203@aon.at>

Thanks, Danny for your explanations!

>With recent developments in IDLEfork (the development version of IDLE),
>though, you shouldn't need to do this check because Tkinter programs
>should work cleanly in IDLE now.
>
>
>You may want try the IDLEfork version of IDLE and see if this has been
>fixed already:
>
>    http://idlefork.sourceforge.net/
>
>  
>
It has been fixed! I just installed it and tried it out. Looks a little 
bit like VPython's IDLE. I still
have to get accustomed to it. Nevertheless, seems to be a jewel! Even 
the -Qnew switch works!
And what I recognized for the first time (and what also works with 
ordinary IDLE 0.8 as I
know now): You can kill

while 1:
      pass

with Ctrl-C

Have to find out if there is another switch, causing it to start with an 
open shell - window.

One important point - and for me it's the only one - remains unsolved  - 
supposedly due to restrictions
of Tkinter : there is no possibility to print out program listings on a 
printer.

Last resort here on my machine for this purpose : Python Win. So I'll 
have to continue using both of them,

Thanks again!
Gregor


>
>
>  
>
>>QUESTION 2:
>>===========
>>
>>Is there a special mailing list or something similar
>>dedicated to Tkinter related stuff?
>>    
>>
>
>Hmmm!  I don't know about this one.  Does anyone else know?
>
>
>
>  
>







From idiot1@netzero.net  Tue Jul 23 06:29:29 2002
From: idiot1@netzero.net (Kirk Bailey)
Date: Tue, 23 Jul 2002 01:29:29 -0400
Subject: [Tutor] Curious newbie
References: <415C917D807AD411B72C00805FF7330B0383626F@MAILSRV>
Message-ID: <3D3CE9B9.FFCCEB1F@netzero.net>

Yes, it is an interpreted language, the interpreter MUST be present to
run any/all python programs. It is not a compiler like C, which
generates standalone executable files.

shey crompton wrote:
> 
> Hi all,
> If I create a program like a small text based guessing game using Python,
> and I want to send it to mates to try out, do they have to have python
> installed to be able to play the game? If my mates don't have to have IDLE
> installed, how would they (in windows) run the game?
> 
> Thanks,
> 
> Shey
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 

end

Respectfully,
             Kirk D Bailey


+---------------------"Thou Art Free." -Eris-----------------------+
| http://www.howlermonkey.net  mailto:highprimate@howlermonkey.net |
| http://www.tinylist.org  +--------+   mailto:grumpy@tinylist.org |
+------------------Thinking| NORMAL |Thinking----------------------+
                           +--------+
-------------------------------------------
Introducing NetZero Long Distance
Unlimited Long Distance only $29.95/ month!
Sign Up Today! www.netzerolongdistance.com



From dman@dman.ddts.net  Tue Jul 23 09:04:08 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 23 Jul 2002 03:04:08 -0500
Subject: [Tutor] Re: Curious newbie
In-Reply-To: <3D3CE9B9.FFCCEB1F@netzero.net>
References: <415C917D807AD411B72C00805FF7330B0383626F@MAILSRV> <3D3CE9B9.FFCCEB1F@netzero.net>
Message-ID: <20020723080408.GA21524@dman.ddts.net>

--ibTvN161/egqYuK8
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 23, 2002 at 01:29:29AM -0400, Kirk Bailey wrote:
| shey crompton wrote:

| > do they have to have python installed to=20
[run python prog]

| Yes, it is an interpreted language, the interpreter MUST be present to
| run any/all python programs. It is not a compiler like C, which
| generates standalone executable files.

Actually, just to be pedantic, the C compiler generates a file which
still needs a runtime environment and "interpreter" to run.  That's
why ELF (or a.out) binaries don't run on windows and PE binaries don't
run (terribly well, most of the time; 'wine' creates exceptions
sometimes) on linux.  The "interpreter" is /bin/ld (on unix at least)
which loads the binary, resolves symbols to external libraries (the
runtime support, known as .so in unix and .dll in windows) and then
locates the "main" symbol and starts execution there.  People still
need to have that runtime installed before they can run your C
program.  The only difference is the C runtime (for that OS, namely
'libc.so' or 'msvcrt.dll') is bundled with the OS and so people tend
not to see the simlarities.  The exception is if you are working on an
embedded system.  In that case you'll need to provide all the hardware
too since it will be specific to your application.


Now to be of more use to shey :

Yes, python is required to run python programs.  There are various
ways of satisfying that requirement.

Method 1 (preferred method, IMO):
    You can tell your friends to install python on their system.  You
    can provide the installer on a disk, or point them to the web
    site, or go to their house and do it for them.  This is a one-time
    step that they can forget about after it is done.

    Now all you do is send them the .py files for the program you made
    and they can run it.

Method 2 :
    You can bundle the interpreter with your program using Gordon
    McMillan's "installer" or py2exe.  In both cases you are just
    doing Method 1 in a slightly different fashion.

    This requires you to bundle the interpreter with your program
    every time.  It means that instead of sending a couple of small
    .py files to your friend, you are sending a big bundle that
    includes all of python _and_ your program.  It also means you need
    to go through the (non-trivial, it seems) process of actually
    creating that bundle.


If you are only sending 1 program to your friend(s) and you are only
doing it once, then Method 2 is easiest for them.  Method 1 takes a
little more up-front effort/knowledge/help on their part, but once
you've taken care of the prerequisites you don't have to worry about
it any more.  That's why I prefer Method 1.  (it is also better if you
want to share you program with someone who doesn't have windows)

<digressing now>
Ahh, the miracle of apt-get.  No worrying about triffles like these.
</digression>

-D

--=20
"Don't use C;  In my opinion,  C is a library programming language
 not an app programming language."  - Owen Taylor (GTK+ developer)
=20
http://dman.ddts.net/~dman/

--ibTvN161/egqYuK8
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj09DfgACgkQO8l8XBKTpRRO4wCgr3YHCpJJRq1emzRV9k+9ifNK
YykAoJSPSjwG8lSpURMkaWm3MaPvPH3Z
=4ZKY
-----END PGP SIGNATURE-----

--ibTvN161/egqYuK8--



From shey@argonaut.com  Tue Jul 23 09:30:46 2002
From: shey@argonaut.com (shey crompton)
Date: Tue, 23 Jul 2002 09:30:46 +0100
Subject: [Tutor] Re: Curious newbie
Message-ID: <415C917D807AD411B72C00805FF7330B03836273@MAILSRV>

Thank you all for the replies. 
My curiosity is satisfied, and I know what to do when I eventually make
something worth showing to friends (when that will be, who knows!). 



 -----Original Message-----
From: 	Derrick 'dman' Hudson [mailto:dman@dman.ddts.net] 
Sent:	23 July 2002 09:04
To:	'tutor@python.org'
Subject:	[Tutor] Re: Curious newbie

On Tue, Jul 23, 2002 at 01:29:29AM -0400, Kirk Bailey wrote:
| shey crompton wrote:

| > do they have to have python installed to 
[run python prog]

| Yes, it is an interpreted language, the interpreter MUST be present to
| run any/all python programs. It is not a compiler like C, which
| generates standalone executable files.

Actually, just to be pedantic, the C compiler generates a file which
still needs a runtime environment and "interpreter" to run.  That's
why ELF (or a.out) binaries don't run on windows and PE binaries don't
run (terribly well, most of the time; 'wine' creates exceptions
sometimes) on linux.  The "interpreter" is /bin/ld (on unix at least)
which loads the binary, resolves symbols to external libraries (the
runtime support, known as .so in unix and .dll in windows) and then
locates the "main" symbol and starts execution there.  People still
need to have that runtime installed before they can run your C
program.  The only difference is the C runtime (for that OS, namely
'libc.so' or 'msvcrt.dll') is bundled with the OS and so people tend
not to see the simlarities.  The exception is if you are working on an
embedded system.  In that case you'll need to provide all the hardware
too since it will be specific to your application.


Now to be of more use to shey :

Yes, python is required to run python programs.  There are various
ways of satisfying that requirement.

Method 1 (preferred method, IMO):
    You can tell your friends to install python on their system.  You
    can provide the installer on a disk, or point them to the web
    site, or go to their house and do it for them.  This is a one-time
    step that they can forget about after it is done.

    Now all you do is send them the .py files for the program you made
    and they can run it.

Method 2 :
    You can bundle the interpreter with your program using Gordon
    McMillan's "installer" or py2exe.  In both cases you are just
    doing Method 1 in a slightly different fashion.

    This requires you to bundle the interpreter with your program
    every time.  It means that instead of sending a couple of small
    .py files to your friend, you are sending a big bundle that
    includes all of python _and_ your program.  It also means you need
    to go through the (non-trivial, it seems) process of actually
    creating that bundle.


If you are only sending 1 program to your friend(s) and you are only
doing it once, then Method 2 is easiest for them.  Method 1 takes a
little more up-front effort/knowledge/help on their part, but once
you've taken care of the prerequisites you don't have to worry about
it any more.  That's why I prefer Method 1.  (it is also better if you
want to share you program with someone who doesn't have windows)

<digressing now>
Ahh, the miracle of apt-get.  No worrying about triffles like these.
</digression>

-D

-- 
"Don't use C;  In my opinion,  C is a library programming language
 not an app programming language."  - Owen Taylor (GTK+ developer)
 
http://dman.ddts.net/~dman/



From alan.gauld@bt.com  Tue Jul 23 10:50:31 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 23 Jul 2002 10:50:31 +0100
Subject: [Tutor] Re: Why x+=y instead of x=x+y?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C763@mbtlipnt02.btlabs.bt.co.uk>

> | It comes from C which was initially implemented on a 
> | computer which had a different set of assembler instructions 
> | for generic addition and 'self addition' )
> 
> I think it is also related to the complexity of the compiler.  I
> expect that any modern compiler will turn "x+=1" into INC X.  

If optimisation is turned off I sincerely hope it doesn't!
Timing issues like this are crucial for real-time and its 
often the case that a "slow" instruction will be preferred 
to a fast one to allow the hardware to 'keep up'... 
Of course you could always drop into assembler for such 
code tuning but if you know the compiler well enough, 
why bother?!

> assume, though, that early compilers were not as sophisticated, 

The optimisations were pretty good even in the '70's, 
much of the science behind compiler writing had already 
been done on Fortran/COBOL etc.

> they had been it would have been painful to use them 

Painful? Oh no, you just set it running as an overnight 
batch job. It wasn't at all unusual for project builds 
to take 4-10 hours. Since it wasn't unusual it wasn't 
painful, you just expected it!

With the heavy machine usage you, as a humble programmer, 
weren't usually allowed access to the compiler directly
that was strictly limited to the build manager who if he 
had to do a second build (coz somebody missed a semi-colon 
say) had to go cap in hand to the operations manager...

I remember being the "villain" who broke a build and 
left 150 programmers and 20 testers twiddling their 
thumbs for a whole morning waiting for the 6 hour rebuild 
to complete - They had a "name and shame" policy so I 
was not at all popular that day!

It certainly taught you to check the syntax of your code 
carefully before submitting it to the build environment ;-)

Alan g.



From alan.gauld@bt.com  Tue Jul 23 14:06:06 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 23 Jul 2002 14:06:06 +0100
Subject: [Tutor] cgi not executed when accessed through browser
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C767@mbtlipnt02.btlabs.bt.co.uk>

> My first simple one.
> 
> Listing of file first.py in 
> directory:/www/www.howlermonkey.net/cgi-bin
> 
> #!/usr/local/bin/python
> print "Content-type: text/html"
> print
> print "<title>First program</title></head>"
> print "<body bgcolor=\"FFFFFF\" text=\"000000\" link=\"0000FF\">"
> print '<P>'
> print "Hello world!"
> print '<P>'
> print '</body></html>'
> 

print ''' 
is your friend for HTML generation...as in:

print '''Content-type: text/html

<title>First program</title></head>
<body bgcolor=\"FFFFFF\" text=\"000000\" link=\"0000FF\">
<P>
Hello world!
</P>
</body></html>
'''

Looks nicer and is easier to maintain - less concerns 
over a missing quote or mixups between " and ' characters.

Alan g.



From alan.gauld@bt.com  Tue Jul 23 14:23:54 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 23 Jul 2002 14:23:54 +0100
Subject: [Tutor] Curious newbie
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C768@mbtlipnt02.btlabs.bt.co.uk>

> and I want to send it to mates to try out, do they have to have python
> installed to be able to play the game? 

One way or another yes. But....

> If my mates don't have to have IDLE
> installed, how would they (in windows) run the game? 

They don't need to do anything with IDLE, they can just 
double click the .py file and it will run. IDLE is itself 
a python program! Better still name your program .pyw and 
it won';t even start a DOS window - assuming you have 
written a GUI fron end! - if not then stick with .py...

However if you don't want them to install the whole of 
Python then they can load a package version of your program 
which includes just the bits of Python needed to run it. 
This can then be wrapped up to ook like a windows exe 
file using py2exe or Gordon McMillans installer.

Try searching google for py2exe...

Alan G.



From alan.gauld@bt.com  Tue Jul 23 14:28:31 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 23 Jul 2002 14:28:31 +0100
Subject: [Tutor] Curious newbie
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C769@mbtlipnt02.btlabs.bt.co.uk>

> Python, don't they. I doubt that MS sends out the Python 
> intepreter in their operating system. 

Sad but true :-)

> But, go to 
> http://starship.python.net/crew/theller/py2exe/ 
> and get the Py2exe program. That will make Python into exe 
> files, that can be ran directly.

But realise that if you ship a lot of python programs they 
will wind up with a lot of installations of Python on their 
PC, in which case it will save space if you get them to 
install python and then just send them the .py files.

A bit like Microsoft do with VB and the VBRUNXXX.DLL 
which basically contains the VB interpreter stuff.

Actually it might be good for python to have a direct 
equivalent - a runtime only distribution without the docs 
and .py sources just the interpreter, compiled libraries 
etc. It would probably only be about 2-3M or so in size...

Just a thought, 

Alan G.



From alan.gauld@bt.com  Tue Jul 23 14:36:33 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 23 Jul 2002 14:36:33 +0100
Subject: [Tutor] Re: Curious newbie
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C76A@mbtlipnt02.btlabs.bt.co.uk>

> Actually, just to be pedantic, the C compiler generates a file which
> still needs a runtime environment and "interpreter" to run.  

Just to be doubly pedantic, some compilers can generate 
true standalone executable files.

> why ELF (or a.out) binaries don't run on windows and PE binaries 

Onlyt partly. The librariy files in both cases implement the 
same fuctions but do so in most cases by mapping onto 
underlying operating system calls. Thus the library 
depends on the OS.

However Real Time development systems exist which contain 
OS independant libraries so that you can compile a file 
that can be blown to a EPROM and executed directly without any OS per se
installed

don't
> run (terribly well, most of the time; 'wine' creates exceptions
> sometimes) on linux.  The "interpreter" is /bin/ld (on unix at least)
> which loads the binary, resolves symbols to external libraries (the
> runtime support, known as .so in unix and .dll in windows) and then
> locates the "main" symbol and starts execution there.  People still
> need to have that runtime installed before they can run your C
> program.  The only difference is the C runtime (for that OS, namely
> 'libc.so' or 'msvcrt.dll') is bundled with the OS and so people tend
> not to see the simlarities.  The exception is if you are working on an
> embedded system.  In that case you'll need to provide all the hardware
> too since it will be specific to your application.
> 
> 
> Now to be of more use to shey :
> 
> Yes, python is required to run python programs.  There are various
> ways of satisfying that requirement.
> 
> Method 1 (preferred method, IMO):
>     You can tell your friends to install python on their system.  You
>     can provide the installer on a disk, or point them to the web
>     site, or go to their house and do it for them.  This is a one-time
>     step that they can forget about after it is done.
> 
>     Now all you do is send them the .py files for the program you made
>     and they can run it.
> 
> Method 2 :
>     You can bundle the interpreter with your program using Gordon
>     McMillan's "installer" or py2exe.  In both cases you are just
>     doing Method 1 in a slightly different fashion.
> 
>     This requires you to bundle the interpreter with your program
>     every time.  It means that instead of sending a couple of small
>     .py files to your friend, you are sending a big bundle that
>     includes all of python _and_ your program.  It also means you need
>     to go through the (non-trivial, it seems) process of actually
>     creating that bundle.
> 
> 
> If you are only sending 1 program to your friend(s) and you are only
> doing it once, then Method 2 is easiest for them.  Method 1 takes a
> little more up-front effort/knowledge/help on their part, but once
> you've taken care of the prerequisites you don't have to worry about
> it any more.  That's why I prefer Method 1.  (it is also better if you
> want to share you program with someone who doesn't have windows)
> 
> <digressing now>
> Ahh, the miracle of apt-get.  No worrying about triffles like these.
> </digression>
> 
> -D
> 
> -- 
> "Don't use C;  In my opinion,  C is a library programming language
>  not an app programming language."  - Owen Taylor (GTK+ developer)
>  
> http://dman.ddts.net/~dman/
> 



From alan.gauld@bt.com  Tue Jul 23 14:41:41 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 23 Jul 2002 14:41:41 +0100
Subject: [Tutor] Re: Curious newbie
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C76B@mbtlipnt02.btlabs.bt.co.uk>

Bah! I hate CTRL-ENTER on Outlook! It keeps sending messages
as I'm in mid edit!

> > Actually, just to be pedantic, the C compiler generates a file which
> > still needs a runtime environment and "interpreter" to run.  
> 
> Just to be doubly pedantic, some compilers can generate 
> true standalone executable files.
> 
> > why ELF (or a.out) binaries don't run on windows and PE binaries 
> 
> Only partly. The library files in both cases implement the 
> same fuctions but do so in most cases by mapping onto 
> underlying operating system calls. Thus the library 
> depends on the OS.
> 
> However Real Time development systems exist which contain 
> OS independant libraries so that you can compile a file 
> that can be blown to a EPROM and executed directly without 
> any OS per se installed

The executive functions are built into the resultant 
executable "file" (actually since there is no OS there is 
no file concept either, its just a bunch of assembler 
statements in RAM which includes the bootstrap loader 
as well as all the IO drivers etc.)

> > program.  The only difference is the C runtime (for that OS, namely
> > 'libc.so' or 'msvcrt.dll') is bundled with the OS and so people tend
> > not to see the simlarities.  

> > The exception is if you are working on an embedded system.  
> > In that case you'll need to provide all the hardware
> > too since it will be specific to your application.

Ah, I see you have sort of covered embedded systems here with 
an implication of some other mechanism at work..

But you did say you were being pedantic :-)

Alan G.



From marcolinux@linuxbr.com.br  Tue Jul 23 14:52:54 2002
From: marcolinux@linuxbr.com.br (Marc)
Date: Tue, 23 Jul 2002 10:52:54 -0300
Subject: [Tutor] Re: Curious newbie
In-Reply-To: <20020723080408.GA21524@dman.ddts.net>
References: <415C917D807AD411B72C00805FF7330B0383626F@MAILSRV> <3D3CE9B9.FFCCEB1F@netzero.net> <20020723080408.GA21524@dman.ddts.net>
Message-ID: <20020723135254.GA1112@marcolab.proconet>

Derrick 'dman' Hudson (dman@dman.ddts.net) wrote:

> Actually, just to be pedantic, the C compiler generates a file which
> still needs a runtime environment and "interpreter" to run.
[...snip...]
>  The only difference is the C runtime (for that OS, namely
> 'libc.so' or 'msvcrt.dll') is bundled with the OS and so people tend
> not to see the simlarities. 

Great Dman! 
You just turn on a light the size of moon over my head...
What if some good brave soul do a libc for windows? 
Better yet, a msvcrt.dll for linux so that we could run/develop for windows from
linux.
Man, that would be just great.

PS: HOw do u interleave > and | in your mail reply?
Someone should make this a standard. :)

> -- 
> "Don't use C;  In my opinion,  C is a library programming language
>  not an app programming language."  - Owen Taylor (GTK+ developer)
>  
Totally agree.

-- 
I SeE NeRD pEoPle.
.:: MarcoLinux ::.



From einarth@decode.is  Tue Jul 23 15:38:05 2002
From: einarth@decode.is (Einar Th. Einarsson)
Date: Tue, 23 Jul 2002 14:38:05 +0000
Subject: [Tutor] Re: Curious newbie
In-Reply-To: <20020723135254.GA1112@marcolab.proconet>
References: <415C917D807AD411B72C00805FF7330B0383626F@MAILSRV> <20020723080408.GA21524@dman.ddts.net> <20020723135254.GA1112@marcolab.proconet>
Message-ID: <200207231438.07088.einarth@decode.is>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


On Tuesday 23 July 2002 13:52, Marc wrote:
> Derrick 'dman' Hudson (dman@dman.ddts.net) wrote:
> > Actually, just to be pedantic, the C compiler generates a file which
> > still needs a runtime environment and "interpreter" to run.
>
> [...snip...]
>
> >  The only difference is the C runtime (for that OS, namely
> > 'libc.so' or 'msvcrt.dll') is bundled with the OS and so people tend
> > not to see the simlarities.
>
> Great Dman!
> You just turn on a light the size of moon over my head...
> What if some good brave soul do a libc for windows?
> Better yet, a msvcrt.dll for linux so that we could run/develop for windo=
ws
> from linux.
> Man, that would be just great.

As someone who has been doing exactly that, I cuncurr ;)
The C-libraries have become pretty standard over the years, so if one follo=
ws=20
said standard the c code will compile with any complient compiler on any=20
complent os. If you're interested in doing Windows programming on linux,=20
check out cygwin or mingw; they both offer cross-platform c/c++ tools.

- --=20
CONGRESS.SYS Corrupted: Re-boot Washington D.C (Y/n)?

Yours etc.
    Einar Th.
-----BEGIN PGP SIGNATURE-----
Version: PGP 6.5.8

iQA/AwUBPT1qTW1/ORZtyd/tEQIjfwCg6QSTwgHjVNjMJyEt+v5PkB1eUpYAoPbu
OKGBOMNeKoBYupnn96J3xGAU
=3DtoW6
-----END PGP SIGNATURE-----




From glingl@aon.at  Tue Jul 23 15:37:59 2002
From: glingl@aon.at (Gregor Lingl)
Date: Tue, 23 Jul 2002 16:37:59 +0200
Subject: [Tutor] Curious newbie
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C769@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3D3D6A47.7060703@aon.at>

alan.gauld@bt.com schrieb:

>Actually it might be good for python to have a direct 
>equivalent - a runtime only distribution without the docs 
>and .py sources just the interpreter, compiled libraries 
>etc. It would probably only be about 2-3M or so in size...
>
>Just a thought, 
>
>Alan G.
>
>  
>
I suppose with py2exe Python is not far from that!
Some days ago I created an exe from a Python program using py2exe -
incidentally it was snake.exe ;-) - and what I got was the following:

A directory called "snake" containing:
--- snake.exe (205 KB)
--- python22.dll (825 KB)
--- tcl83.dll (472 KB)
--- tk83.dll (928 KB)

plus 2 small files called _sre.pyd and _tkinter.pyd

Additionally there is a subdirectory named tcl containing 2.45 MB
tcl/tk - stuff

These things add to 205 files in 13 directories making up 4.9 MB
Among these files are many bitmaps, gifs and even tcl-demos, which
certainly are not used by my application. Nevertheless, removing this
obviously unnecessary stuff by hand prevents snake.exe from running.

Hmmm!
Not very handy! I think this has to be optimized yet!

Gregor






From glingl@aon.at  Tue Jul 23 15:42:34 2002
From: glingl@aon.at (Gregor Lingl)
Date: Tue, 23 Jul 2002 16:42:34 +0200
Subject: [Tutor] Re: Curious newbie
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C76B@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3D3D6B5A.9050604@aon.at>

alan.gauld@bt.com schrieb:

>Bah! I hate CTRL-ENTER on Outlook! It keeps sending messages
>as I'm in mid edit!
>
>  
>
Try Mozilla!
Gregor





From alan.gauld@bt.com  Tue Jul 23 15:53:14 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 23 Jul 2002 15:53:14 +0100
Subject: [Tutor] Curious newbie
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C771@mbtlipnt02.btlabs.bt.co.uk>

> >equivalent - a runtime only distribution without the docs 
> >
> I suppose with py2exe Python is not far from that!

Not far but not quite either - you still get a copy of 
the material with every 'exe' you create. Plus you don't 
get all the libraries just the ones you use. So its 
neither one thing nor the other.

> Some days ago I created an exe from a Python program using py2exe -
> A directory called "snake" containing:
> --- snake.exe (205 KB)
> --- python22.dll (825 KB)
> --- tcl83.dll (472 KB)
> --- tk83.dll (928 KB)
> 
> plus 2 small files called _sre.pyd and _tkinter.pyd

Yes, wheras I want something that doesn'ty include the 
snake code but does have the interpreter and libraries etc.

> Additionally there is a subdirectory named tcl containing 2.45 MB
> tcl/tk - stuff

Really? I didn't realize it included that stuff too.

> certainly are not used by my application. Nevertheless, removing this
> obviously unnecessary stuff by hand prevents snake.exe from running.

Looks like a wee bit of work to be done there.

Alan g.



From curtis.larsen@covance.com  Tue Jul 23 22:39:05 2002
From: curtis.larsen@covance.com (Curtis Larsen)
Date: Tue, 23 Jul 2002 16:39:05 -0500
Subject: [Tutor] Setting an URLLIB Proxy?
Message-ID: <sd3d86d2.068@madis2.truax.covance.com>

Can someone please give an example of setting a (HTTP) proxy so that
(subsequent) calls using URLLIB/URLLIB2 work?

I'm trying out a script (pyGoogle) that calls URLLIB, and I think I
need to change it to URLLIB2 for proxy use to work.  I'm not positive I
have the proxy syntax right though.  (Does URLLIB support proxies? 
Didn't see it...)

Thanks,
Curtis



-----------------------------------------------------
Confidentiality Notice: This e-mail transmission 
may contain confidential or legally privileged 
information that is intended only for the individual 
or entity named in the e-mail address. If you are not 
the intended recipient, you are hereby notified that 
any disclosure, copying, distribution, or reliance 
upon the contents of this e-mail is strictly prohibited. 

If you have received this e-mail transmission in error, 
please reply to the sender, so that we can arrange 
for proper delivery, and then please delete the message 
from your inbox. Thank you.



From unixguru@mac.com  Tue Jul 23 02:54:28 2002
From: unixguru@mac.com (UNIX Guru)
Date: Mon, 22 Jul 2002 18:54:28 -0700
Subject: [Tutor] string.count in Windows vs UNIX
Message-ID: <1FBE11A8-9DDF-11D6-97FB-00039375444A@mac.com>

I've been dabbling with Python for a bit, and use the following 
script-excerpt to go through a large file checking for specific text. On 
UNIX it finds the correct number of occurances (6665 - double-checked 
with grep -e "Subject: Results:" mail.file | wc -l) but when run on 
Windows (2K/XP) it stops finding, consistently,  after 4195 occurances.

Is there something within this script-excerpt that would break the 
functionality on Windows, or some difference in the Python 
implementations on both OSes that would affect this? WFIW, the mail.file 
is about 72Mb in size.

# imports, and other stuff that works fine...
mailfile = open('mail.file', 'r')
allLines = mailfile.xreadlines()
for eachLine in allLines:
	if eachLine.count("Subject: Results:"):
		count += 1
# other stuff going on
print "Total messages found ", count

Python 2.2.0 is in use on both platforms (2.2.1 on Windows elicited the 
same erroneous result). I also used eachLine.find(...) without any 
differing results. Is there something I'm (not) doing that I should 
(not) be doing?

Thanx
Gareth




From gwatt3@backbonesecurity.com  Tue Jul 23 15:48:37 2002
From: gwatt3@backbonesecurity.com (Watt III, Glenn)
Date: Tue, 23 Jul 2002 10:48:37 -0400
Subject: [Tutor] help debuging cgi
Message-ID: <94FD5825A793194CBF039E6673E9AFE034D609@bbserver1.backbonesecurity.com>

ok im new to python and needed help debugging my cgi file here it is, it
runs fine if there arent any values however whenever i put a value in
the form python trips and says that it cant find global varible title
from the bottom where i call it up in a dictionary, any help would be
apprciated, if you need the form souce code to help the debugging
process feel free to email me at gwatt3@backbonesecurity.com


#!/usr/local/bin/python


import cgi
import sys
print ""





sys.stderr =3D sys.stdout



cgiForm =3D cgi.FieldStorage()

err =3D ""
wrong =3D 0


def reQuire(input, response):
    global wrong
    global err
    if cgiForm.has_key(input):
        input =3D cgiForm[input].value
        return input
    elif wrong =3D=3D 1:
        err =3D err + ',' + ' ' + response
    else:
        err =3D response
        wrong =3D 1

def opTion(input):
    if cgiForm.has_key(input):
        input =3D cgiForm[input].value
        return input
    else:
        input =3D ' '
        return input

def paperChk():
    global err
    global wrong
    if cgiForm.has_key('cot'):
        if cgiForm['cot'].value =3D=3D 'Copy and paste your complete =
paper
here.':
            if wrong =3D=3D 1:
                err =3D err + ',' + ' ' + 'Complete Paper'
            else:
                err =3D 'Complete Paper'
                wrong =3D 1
        else:
            cot =3D cgiForm['cot'].value
            return cot
    elif wrong =3D=3D 1:
        err =3D err + ',' + ' ' + 'Complette Paper'
    else:
        err =3D 'Complete Paper'
        wrong =3D 1

def mainAction():
    reQuire("firstname", "First Name")

    reQuire("lastname", "Last Name")

    reQuire("email", "E-mail Address")

    reQuire("release", "E-mail Release option")

    reQuire("city", "City")

    reQuire("state", "State")

    reQuire("country", "Country")

    reQuire("copyright", "Copyright preclusion")

    reQuire("preclude", "Preclusion")

    reQuire("papertitle", "Paper Title")

    reQuire("abstract", "Abstract")

    paperChk()

    opTion("title")

    opTion("organization")

    if wrong =3D=3D 1:
        novalid =3D  """
<html>
  <head>
  <title>Backbone Security,com</title>
  </head>
  <body>
  <script language =3D "JavaScript">
    alert ("The following required field were left blank please fill
them in %s.");
  history.back();
  </script>
  </body>
</html>"""
        print novalid % (err)
    else:
 newPage =3D '''
<html>
  <head>
  <title>Backbone Security.com</title>
  <link rel=3D"stylesheet" type=3D"text/css" href =3D =
colletcter/return.css>
  </head>
  <h3>Please Verify the following information</h3><br>
    <p>Hello %s %s %s
    <p>We have your organization down as "%s"
    <p>We have your E-mail Address down as "%s"
    <p>We have your E-mail Release preferance down as "%s"
    <p>We have your city down as "%s"
    <p>We have your state down as "%s"
    <p>We have your country down as "%s"
    <p>Would copyright preclude presentation at BackboneSecurity.com or
publication in BackboneSecurtiy.com Proceeding: %s
    <p>Publication precluded: %s
    <p>Paper Title: "%s"
    <p>Your abstract reads as follows:
    <p>"%s"
    <p>Your paper reads as follows:
    <p>"%s"
    <p>
    <form>
    <input type=3Dsubmit value=3D"Submit Paper">
    </form>
    </body>
</html>'''
        print newPage % (title, firstname, lastname, organization,
email, release, city, state, country, copyright, preclude, papertitle,
abstract, cot)

mainAction()



From dyoo@hkn.eecs.berkeley.edu  Tue Jul 23 23:08:58 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 23 Jul 2002 15:08:58 -0700 (PDT)
Subject: [Tutor] string.count in Windows vs UNIX
In-Reply-To: <1FBE11A8-9DDF-11D6-97FB-00039375444A@mac.com>
Message-ID: <Pine.LNX.4.44.0207231452290.4239-100000@hkn.eecs.berkeley.edu>


On Mon, 22 Jul 2002, UNIX Guru wrote:

> I've been dabbling with Python for a bit, and use the following
> script-excerpt to go through a large file checking for specific text. On
> UNIX it finds the correct number of occurances (6665 - double-checked
> with grep -e "Subject: Results:" mail.file | wc -l) but when run on
> Windows (2K/XP) it stops finding, consistently, after 4195 occurances.

Hmmm... this is very odd!


> Is there something within this script-excerpt that would break the
> functionality on Windows, or some difference in the Python
> implementations on both OSes that would affect this? WFIW, the mail.file
> is about 72Mb in size.


There may be some weirdness involved with what "end of line"  means.  In a
Windows system, '\r\n' is considered the line terminator, while in Unix,
'\n' is sufficient.  It may be that some of the lines in mail.file are
terminated only by '\n'.  Macintoshes add to the complication by just
using '\r'.  *grin*


If you have enough free memory, can you try the following:

###
text = mailfile.read()
mailfile.seek(0)
print "This file contains ", text.count("\r'), "carriages"
print "and", text.count("\n"), "newlines"
###

Let's check to see if this is a newline issue.




> 	if eachLine.count("Subject: Results:"):
> 		count += 1


We can simplify this as:

    count += eachLine.count("Subject: Results:")

if we know that this particular string doesn't show up more than once per
line.


Best of wishes to you!



From dyoo@hkn.eecs.berkeley.edu  Tue Jul 23 23:21:19 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 23 Jul 2002 15:21:19 -0700 (PDT)
Subject: [Tutor] help debuging cgi
In-Reply-To: <94FD5825A793194CBF039E6673E9AFE034D609@bbserver1.backbonesecurity.com>
Message-ID: <Pine.LNX.4.44.0207231511200.4239-100000@hkn.eecs.berkeley.edu>


Hi Glenn,

> def reQuire(input, response):
>     global wrong
>     global err
>     if cgiForm.has_key(input):
>         input = cgiForm[input].value
>         return input
>     elif wrong == 1:
>         err = err + ',' + ' ' + response
>     else:
>         err = response
>         wrong = 1

One brief comment: A "Pythonic" way to approach this would be to use
exceptions to signal bad input.  That is, we can have reQuire() raise an
exception here instead of setting to a global "wrong" and "err" variable.
We can talk about exceptions later if you'd like.



> def mainAction():
>     reQuire("firstname", "First Name")
>     reQuire("lastname", "Last Name")
>     reQuire("email", "E-mail Address")
>     reQuire("release", "E-mail Release option")
>     reQuire("city", "City")
>     reQuire("state", "State")
>     reQuire("country", "Country")
>     reQuire("copyright", "Copyright preclusion")
>     reQuire("preclude", "Preclusion")
>     reQuire("papertitle", "Paper Title")
>     reQuire("abstract", "Abstract")

Ah, I see!  The way that you're using return is good, but you need to
capture each value and bind it to a name, like this:

###
     firstname = reQuire("firstname", "First Name")
     lastname = reQuire("lastname", "Last Name")
     email = reQuire("email", "E-mail Address")
     release = reQuire("release", "E-mail Release option")
     city = reQuire("city", "City")
###

Otherwise, without the variable assignment, the returned value just drops
right off; Python won't save it.  By doing the variable assignment, we can
store the return value and use it later with that HTML template filling.


If you have more questions, please feel free to ask.



From tutor@python.org  Tue Jul 23 23:12:14 2002
From: tutor@python.org (Tim Peters)
Date: Tue, 23 Jul 2002 18:12:14 -0400
Subject: [Tutor] string.count in Windows vs UNIX
In-Reply-To: <1FBE11A8-9DDF-11D6-97FB-00039375444A@mac.com>
Message-ID: <BIEJKCLHCIOIHAGOKOLHOEIEDHAA.tim@zope.com>

[UNIX Guru]
> I've been dabbling with Python for a bit, and use the following
> script-excerpt to go through a large file checking for specific text. On
> UNIX it finds the correct number of occurances (6665 - double-checked
> with grep -e "Subject: Results:" mail.file | wc -l) but when run on
> Windows (2K/XP) it stops finding, consistently,  after 4195 occurances.
> ...

> mailfile = open('mail.file', 'r')

Use 'rb' instead.  Python makes the same distinction between text-mode and
binary-mode files as C makes, since Python file objects are just a thin
wrapper around C stdio streams (FILE*).  As a UNIX Guru <wink>, you're used
to systems where text- and binary-mode files act identically.  They don't on
Windows, and some non-printable characters in Windows text-mode files have
meta-meanings (chiefly that for first occurrence of chr(26) acts as an EOF
marker in files opened in text mode on Windows).



From dman@dman.ddts.net  Wed Jul 24 00:00:06 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 23 Jul 2002 18:00:06 -0500
Subject: [Tutor] Re: string.count in Windows vs UNIX
In-Reply-To: <BIEJKCLHCIOIHAGOKOLHOEIEDHAA.tim@zope.com>
References: <1FBE11A8-9DDF-11D6-97FB-00039375444A@mac.com> <BIEJKCLHCIOIHAGOKOLHOEIEDHAA.tim@zope.com>
Message-ID: <20020723230006.GA6952@dman.ddts.net>

--fdj2RfSjLxBAspz7
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 23, 2002 at 06:12:14PM -0400, Tim Peters wrote:
| [UNIX Guru]
=2E..
| > UNIX
=2E..
| > Windows (2K/XP)
=2E..
| > mailfile =3D open('mail.file', 'r')

| some non-printable characters in Windows text-mode files have
| meta-meanings (chiefly that for first occurrence of chr(26) acts as
| an EOF marker in files opened in text mode on Windows).

Double-checking, chr(26) is Ctrl-Z.  If you run the interpreter
interactively in a DOS window (or any other non-cygwin program that
reads from stdin) you'll notice that you need to press "^Z<Enter>" to
signal EOF.  IIRC the ^Z flag is a relic from CP/M, when the disk
didn't record how many actual bytes of the sector were used.  Thus a
sentinel character was used to indicate the end of the data stream.

It never ceases to amaze me how far behind the times MS products are.

-D

--=20
(A)bort, (R)etry, (T)ake down entire network?
=20
http://dman.ddts.net/~dman/

--fdj2RfSjLxBAspz7
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj093/YACgkQO8l8XBKTpRRcuACePUv+0OnLSo5Dcd11ZWCBtpey
dFsAoI64fLXTsYRu1QycFr/3X2OvnXvC
=NwV0
-----END PGP SIGNATURE-----

--fdj2RfSjLxBAspz7--


From dman@dman.ddts.net  Wed Jul 24 00:09:35 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 23 Jul 2002 18:09:35 -0500
Subject: [Tutor] Re: Curious newbie
In-Reply-To: <200207231438.07088.einarth@decode.is>
References: <415C917D807AD411B72C00805FF7330B0383626F@MAILSRV> <20020723080408.GA21524@dman.ddts.net> <20020723135254.GA1112@marcolab.proconet> <200207231438.07088.einarth@decode.is>
Message-ID: <20020723230935.GB6952@dman.ddts.net>

--0eh6TmSyL6TZE2Uz
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 23, 2002 at 02:38:05PM +0000, Einar Th. Einarsson wrote:
| On Tuesday 23 July 2002 13:52, Marc wrote:
| > Derrick 'dman' Hudson (dman@dman.ddts.net) wrote:
| > > Actually, just to be pedantic, the C compiler generates a file which
| > > still needs a runtime environment and "interpreter" to run.
| > [...snip...]
| > >  The only difference is the C runtime (for that OS, namely
| > > 'libc.so' or 'msvcrt.dll') is bundled with the OS and so people tend
| > > not to see the simlarities.
| >
| > Great Dman!
| > You just turn on a light the size of moon over my head...
| > What if some good brave soul do a libc for windows?
| > Better yet, a msvcrt.dll for linux so that we could run/develop for win=
dows
| > from linux.
| > Man, that would be just great.
|=20
| As someone who has been doing exactly that, I cuncurr ;)
| The C-libraries have become pretty standard over the years,

Almost.  The _core_ libraries defined by the ANSI/ISO standard are
indeed standard (AFAIK).  However there are lots and lots of quirks in
each OS (even if you don't get out of unix-land).

| so if one follows said standard the c code will compile with any
| complient compiler on any complent os.

Which gives you source-level compatibility, but that doesn't help you
play Quake or Warcraft on your shiny robust linux system.

| If you're interested in doing Windows programming on linux,

| check out cygwin or mingw; they both offer cross-platform c/c++
| tools.

'libcygwin1.dll' is "libc for windows"

'wine' is "windows for unix"

The two projects are fundamentally different (not just counterparts)
due to the way the target software is structured.

Cygwin provides a source-compatible system and compiler.  It allows
you to compile a lot of unix software (eg mutt or vim or gtk)
out-of-the-box on your windows machine.  It is only source-compatible,
not binary.  The compiler produces PE executables and .dlls just like
Microsoft does.  This tactic is used since all the software you want
to build with this system is freely available in source form.

Wine, however, is a binary-level emulator intended to run PE
executables (and DLLs) intended for windows.  The reason for this is
nearly all windows software (eg Warcraft or MS Office) is available in
binary form only.  It is impossible to "just recompile with the new
library".

-D

PS. as for the interleaved '|' and '>', the '>' is inserted by
    someone else's mailer when they reply to a message.  The '|' is
    inserted by my mailer when I reply.  They are interleaved when we
    reply to each other's messages.  The '>' is most common, but I
    find it distracting and prefer '|'.  Some people even use '%' or
    do wacky indenation and labelling things with their quoting.

--=20
He who belongs to God hears what God says.  The reason you do not hear
is that you do not belong to God.
        John 8:47
=20
http://dman.ddts.net/~dman/

--0eh6TmSyL6TZE2Uz
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj094i8ACgkQO8l8XBKTpRQi6QCfV2TccDlsVMJsS1dhssl5H0za
6msAniO4JPCXhJIpJW7aqWHWWDn0AWuf
=8s9X
-----END PGP SIGNATURE-----

--0eh6TmSyL6TZE2Uz--


From dman@dman.ddts.net  Wed Jul 24 00:15:45 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 23 Jul 2002 18:15:45 -0500
Subject: [Tutor] Re: Curious newbie
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C769@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C769@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020723231545.GC6952@dman.ddts.net>

--s9fJI615cBHmzTOP
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 23, 2002 at 02:28:31PM +0100, alan.gauld@bt.com wrote:

| Actually it might be good for python to have a direct=20
| equivalent - a runtime only distribution without the docs=20
| and .py sources just the interpreter, compiled libraries=20
| etc. It would probably only be about 2-3M or so in size...

Don't we already have that?

    Package: python2.2
    Installed-Size: 6204

    Package: python2.2-doc
    Installed-Size: 10372

    Package: python2.2-dev
    Installed-Size: 2356

In fact, each major non-standard library (and tkinter also) is
available separately ...


Oh, wait a minute, you were talking about Microsoft again, weren't
you?

/me ducks

:-)

-D

--=20
The remote desktop feature of Windows XP is really nice (and *novel*!).
As a Microsoft consultant can *remotely* disable the personal firewall
and control the system.  We'll ignore the fact that this tampering with
the firewall is not logged, and more importantly, that the firewall
isn't restored when the clowns from Redmond are done with their job.
                                                            -- bugtraq
=20
http://dman.ddts.net/~dman/

--s9fJI615cBHmzTOP
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0946EACgkQO8l8XBKTpRSiRgCeLwFrlwVkYFArZjcxUpUkNGWD
CIgAnjF9T0mFw9MQkN+QKVRu7LdsZnqA
=EKyJ
-----END PGP SIGNATURE-----

--s9fJI615cBHmzTOP--


From dman@dman.ddts.net  Wed Jul 24 00:16:56 2002
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Tue, 23 Jul 2002 18:16:56 -0500
Subject: [Tutor] Re: Curious newbie
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C771@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C771@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020723231656.GD6952@dman.ddts.net>

--MAH+hnPXVZWQ5cD/
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jul 23, 2002 at 03:53:14PM +0100, alan.gauld@bt.com wrote:

| > Additionally there is a subdirectory named tcl containing 2.45 MB
| > tcl/tk - stuff
|=20
| Really? I didn't realize it included that stuff too.

Well, if you wrote your program using Tkinter, it had better include
it!  I suspect that it wouldn't include the Tcl/Tk stuff if your
program didn't use it.

-D

--=20
I can do all things through Christ who strengthens me.
        Philippians 4:13
=20
http://dman.ddts.net/~dman/

--MAH+hnPXVZWQ5cD/
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj094+gACgkQO8l8XBKTpRRhtwCgx1LQI43TG7iE2WhMwxMLn3mZ
rjkAn2vOFhpbePuxcvSK9GCS+TTCMBlU
=d3nl
-----END PGP SIGNATURE-----

--MAH+hnPXVZWQ5cD/--


From bjmartin98@pennswoods.net  Wed Jul 24 01:18:19 2002
From: bjmartin98@pennswoods.net (Billie)
Date: Tue, 23 Jul 2002 20:18:19 -0400
Subject: [Tutor] Newbie Question
Message-ID: <000001c232a8$98e90de0$5c38d141@bjmartin98>

This is a multi-part message in MIME format.

------=_NextPart_000_000C_01C23286.15C16EC0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

I am learning Python with the tutorial for non-programmers.

We are asked to write a program to keep track of how many times the user =
has entered the password wrong.  If more than 3 times, print "That must =
have been complicated"

How do you count a string statement?  Everything I've tried asks for =
integers.  I feel really stupid because I can't work this out.

password =3D "foobar"


------=_NextPart_000_000C_01C23286.15C16EC0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 5.50.4522.1800" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>I am learning Python with the tutorial =
for=20
non-programmers.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>We are asked to write a program to keep =
track of=20
how many times the user has entered the password wrong.&nbsp; If more =
than 3=20
times, print "That must have been complicated"</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>How do you count a string =
statement?&nbsp;=20
Everything I've tried asks for integers.&nbsp; I feel really stupid =
because I=20
can't work this out.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>password =3D "foobar"</FONT></DIV>
<DIV>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_000C_01C23286.15C16EC0--



From dyoo@hkn.eecs.berkeley.edu  Wed Jul 24 01:56:42 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 23 Jul 2002 17:56:42 -0700 (PDT)
Subject: [Tutor] Newbie Question
In-Reply-To: <000001c232a8$98e90de0$5c38d141@bjmartin98>
Message-ID: <Pine.LNX.4.44.0207231750220.9148-100000@hkn.eecs.berkeley.edu>


On Tue, 23 Jul 2002, Billie wrote:

> I am learning Python with the tutorial for non-programmers.

Hi Billie, welcome aboard!


> We are asked to write a program to keep track of how many times the user
> has entered the password wrong.  If more than 3 times, print "That must
> have been complicated"

Do you get your user's input by using a raw_input() call?  That would
probably be the way of getting someone to type the password.



> How do you count a string statement?  Everything I've tried asks for
> integers.  I feel really stupid because I can't work this out.

I don't think you need to count the string itself.  Instead, try to count
the number of times it takes for the user to get the password right.  I
think you may need to use something to check the user's input versus the
real password, like an 'if' statement.



If you have more questions, or if a particular answer was more than vague,
please feel free to ask for clarification.  *grin*

Best of wishes to you!




From guillermo.fernandez@epfl.ch  Wed Jul 24 03:58:55 2002
From: guillermo.fernandez@epfl.ch (guillermo.fernandez@epfl.ch)
Date: Wed, 24 Jul 2002 04:58:55 +0200
Subject: [Tutor] Curious newbie
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C768@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C768@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <1027479535.3d3e17ef7e817@imapwww.epfl.ch>

> However if you don't want them to install the whole of 
> Python then they can load a package version of your program 
> which includes just the bits of Python needed to run it. 
> This can then be wrapped up to ook like a windows exe 
> file using py2exe or Gordon McMillans installer.

Hi!

I was looking the Tools directory in the Python-2.2.1 distribution when I 
finded this:
______________
What is Freeze?
Freeze make it possible to ship arbitrary Python programs to people
who don't have Python.
______________

I think it's what you are looking for, so maybe you can also try this 
program (it should be avalaible in the Python Windows distribution as 
well...).

Have fun!

Guille

-------------------------------------------------
This mail sent through IMP: http://horde.org/imp/


From dylan.belsey@baesystems.com  Wed Jul 24 06:50:42 2002
From: dylan.belsey@baesystems.com (BELSEY, Dylan)
Date: Wed, 24 Jul 2002 15:20:42 +0930
Subject: [Tutor] Embedding Python
Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B96320C7@wtntex1.baea.com.au>

Hi,
	I am attempting to try and get the embedding of Python running on my
system (WinNT). I am using VC++ and I copied the code from "5.1 Very High
Level Embedding" within "Extending and Embedding the Python Interpreter"
from the Python docs.  I have also installed the latest release of Python,
version 2.3a0.  The code from the documentation is pasted below:

#include <Python.h>

int
main(int argc, char *argv[])
{
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print 'Today is',ctime(time())\n");
  Py_Finalize();
  return 0;
}

	It compiles OK but when I go to run it I get the following error:

'import site' failed; use -v for traceback
Today is Wed Jul 24 15:39:04 2002
Press any key to continue

	Any ideas why this error is occurring.  Has anyone seen this error
and if so why is it occurring?  The code is compiled in debug mode so maybe
the error is an artefact of that??  I have noticed that when I put the
produced executable in the directory where python.exe lives I don't get the
error.  Unfortunately I don't know enough about the guts of Python to follow
this discovery through.
	Any help would be appreciated.
		Dylan


From ak@silmarill.org  Wed Jul 24 10:30:11 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Wed, 24 Jul 2002 05:30:11 -0400
Subject: [Tutor] Newbie Question
In-Reply-To: <000001c232a8$98e90de0$5c38d141@bjmartin98>
References: <000001c232a8$98e90de0$5c38d141@bjmartin98>
Message-ID: <20020724093011.GA454@ak.silmarill.org>

On Tue, Jul 23, 2002 at 08:18:19PM -0400, Billie wrote:
> I am learning Python with the tutorial for non-programmers.
> 
> We are asked to write a program to keep track of how many times the user has entered the password wrong.  If more than 3 times, print "That must have been complicated"
> 
> How do you count a string statement?  Everything I've tried asks for integers.  I feel really stupid because I can't work this out.
> 
> password = "foobar"
> 

There are several ways.. you can add to the counter:

tries = 0

while 1:
    [ask for pwd]
    if good:
	dosomething
	break
    tries += 1
    if tries == 3:
	print "3 tries!"

You can subtract from tries:

tries = 3

while tries:
    [ask for pwd]
    if good:
	dosomething
	sys.exit()
    tries -= 1
print "3 tries!"

You can loop 3 times:

for i in range(3):
    [ask for pwd]
    if good:
	do something
	sys.exit()
print "3 tries!"
    
The first way shown here is probably better because you don't have to
exit the program.. using other ways, if you need to keep running, you
may set a flag for "got right pwd" and then after loop is done, print
"3 tries" only if the flag is not set.. But that's a bit of a
contraption I guess.

 - Andrei

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org


From alan.gauld@bt.com  Wed Jul 24 10:37:13 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 24 Jul 2002 10:37:13 +0100
Subject: [Tutor] string.count in Windows vs UNIX
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C778@mbtlipnt02.btlabs.bt.co.uk>

> UNIX it finds the correct number of occurances (6665 - double-checked 
> with grep -e "Subject: Results:" mail.file | wc -l) but when run on 
> Windows (2K/XP) it stops finding, consistently,  after 4195 
> occurances.

The most likely thing is the different EOF markers.
If its a Unix file it may have a stray CTRL-Z character 
in there (search with grep or vi to see?).

In Unix that won't affect the search coz CTRL Z is not EOF 
but on Windows/DOS it is...

Thats all I can think of.

Alan G.


From alan.gauld@bt.com  Wed Jul 24 10:45:27 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 24 Jul 2002 10:45:27 +0100
Subject: [Tutor] Re: Curious newbie
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C779@mbtlipnt02.btlabs.bt.co.uk>

> | > Additionally there is a subdirectory named tcl containing 2.45 MB
> | > tcl/tk - stuff
> | Really? I didn't realize it included that stuff too.
> Well, if you wrote your program using Tkinter,...

I expected it to include the two DLLS for Tcl and Tk but 
thats a whole lot less that 2.45MB! It certainly shouldn't 
need to ship the Tk demo program etc...

Alan G.


From lumbricus@gmx.net  Wed Jul 24 11:59:51 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Wed, 24 Jul 2002 12:59:51 +0200 (MEST)
Subject: [Tutor] Re: Why x+=y instead of x=x+y?
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C763@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <4062.1027508391@www40.gmx.net>

> > | It comes from C which was initially implemented on a 
> > | computer which had a different set of assembler instructions 
> > | for generic addition and 'self addition' )
> > 
> > I think it is also related to the complexity of the compiler.  I
> > expect that any modern compiler will turn "x+=1" into INC X.  
> 
> If optimisation is turned off I sincerely hope it doesn't!

Why not?

$ gcc --version
egcs-2.91.66
$ uname
Linux
$ cat inc.c
#include <stdio.h>
int main (void) {
        int i=0;
        i++;
        i+=1;
        i=i+1;
        return 0;
}

$ cc -S inc.c
$ cat inc.s
	[ snip ]
        incl -4(%ebp)
        incl -4(%ebp)
        incl -4(%ebp)
	[ snip ]
$ 

HAND and Greetings, J"o!

-- 


-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net



From terjeja@hotmail.com  Wed Jul 24 16:13:34 2002
From: terjeja@hotmail.com (Terje Johan Abrahamsen)
Date: Wed, 24 Jul 2002 15:13:34 +0000
Subject: [Tutor] Instances
Message-ID: <F197AauNjVuMhvqgStM0000c125@hotmail.com>

> > But, when I include n = test() in there, I tend to get this error
> > message:
> >
> > Traceback (most recent call last):
> >   File "C:\temp\slett2.py", line 3, in test
> >     d = test()
> > NameError: name 'test' is not defined
>
>"Line 3" suggests you have it at the top of your file?
>Put it at the very end, then the definition of test
>will be visible.
>
> > >In fact you can miss the if test out and just put a last line of
> > >
> > >test()
>
>Note that I mentioned putting it as "the last line".

But it still doesn't work. Here is the whole program:

import win32com.client
import win32com.client.dynamic
from win32com.client import Dispatch

class divxl:
    xlApp = Dispatch("Excel.Application")
    xlBook = xlApp.Workbooks(1)
    xlSheet = xlApp.Sheets(1)

    xlrad = 1
    func = 0            #Funksjon man ønsker 1) legg sammen med samme 
policynummer


    def __init__(self):
        print "Function numbers"
        print " 1) Add rows where there are more than one equals in a 
collumn"
        print " 2) Remove rows that contain/not contain bold fields"
        divxl.func = int(raw_input("Type the function # : "))
        n.starter()

    def starter(self):
        if divxl.func == 1:
            n.summer()
        elif divxl.func == 2:
            n.bold()

    def summer(self):
        kolonne1 = int(raw_input("Collumn# where the equals are : "))
        kolonne2 = int(raw_input("Collumn# where addition should be: "))
        xlrad = 1
        while divxl.xlSheet.Cells(xlrad + 1, kolonne1).Value != None:
            pol1 = divxl.xlSheet.Cells(xlrad, kolonne1).Value
            pol2 = divxl.xlSheet.Cells(xlrad + 1, kolonne1).Value
            if pol1 == pol2:
                divxl.xlSheet.Cells(xlrad, kolonne2).Value = 
divxl.xlSheet.Cells(xlrad, kolonne2).Value + divxl.xlSheet.Cells(xlrad + 1, 
kolonne2).Value
                divxl.xlSheet.Rows(xlrad + kolonne1).Delete()
                xlrad = xlrad - 1
            xlrad = xlrad + 1

    def bold(self):
        boldyn = int(raw_input("Remove bold, '1', keep bold, '2' : "))
        rad = 1
        while divxl.xlSheet.Cells(rad, 1).Value != None:
            if boldyn == 1:
                if divxl.xlSheet.Cells(rad, 1).Font.Bold == 1:
                    divxl.xlSheet.Rows(rad).Delete()
            if boldyn == 2:
                if divxl.xlSheet.Cells(rad, 1).Font.Bold == 0:
                    divxl.xlSheet.Rows(rad).Delete()
            rad = rad + 1

    if __name__ == "__main__":
        n = divxl()

And the error message:

Traceback (most recent call last):
  File 
"C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", 
line 301, in RunScript
    exec codeObject in __main__.__dict__
  File "C:\Python22\diverse\divxlkompilert\divxl.py", line 5, in ?
    class divxl:
  File "C:\Python22\diverse\divxlkompilert\divxl.py", line 53, in divxl
    n = divxl()
NameError: name 'divxl' is not defined

I even removed the divxl.pyc to be sure, and restarted Python. Still, I 
cannot get it to work...

Terje

_________________________________________________________________
Chat with friends online, try MSN Messenger: http://messenger.msn.com



From alan.gauld@bt.com  Wed Jul 24 16:17:54 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 24 Jul 2002 16:17:54 +0100
Subject: [Tutor] Instances
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C785@mbtlipnt02.btlabs.bt.co.uk>

> >Put it at the very end, then the definition of test
> >will be visible.
> >
> But it still doesn't work. Here is the whole program:
> 
> import win32com.client
> class divxl:
>     def __init__(self):
>     def starter(self):
>     def summer(self):
>     def bold(self):
> 
>     if __name__ == "__main__":
>         n = divxl()

> 
> And the error message:
> NameError: name 'divxl' is not defined

Notice that your if statement is indented to the same 
level as the class methods therefore Python thoinks 
it is part of the class definition. But its not valid
because the class isn't finished being defined yet...

Move the if out to the first colum - like the import 
statements. Remember indentation in Python determines 
scope.

Alan g.


From tim.one@comcast.net  Wed Jul 24 16:35:12 2002
From: tim.one@comcast.net (Tim Peters)
Date: Wed, 24 Jul 2002 11:35:12 -0400
Subject: [Tutor] Re: Curious newbie
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C779@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <BIEJKCLHCIOIHAGOKOLHCEKEDHAA.tim.one@comcast.net>

[alan.gauld@bt.com]
> I expected it to include the two DLLS for Tcl and Tk but
> thats a whole lot less that 2.45MB! It certainly shouldn't
> need to ship the Tk demo program etc...

There are a few smaller distributions of Python, updated irregularly.  One
of the nicest is PythonWare's (Fredrik Lundh's employer):

    http://www.pythonware.com/products/python/index.htm

If you're a dedicated minimalist <wink>, try the collection of small
Python-for-CGI distributions Marc-Andre Lemburg organizes:

    http://www.egenix.com/files/python/mxCGIPython.html



From alan.gauld@bt.com  Wed Jul 24 17:23:48 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 24 Jul 2002 17:23:48 +0100
Subject: [Tutor] Re: Why x+=y instead of x=x+y?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C786@mbtlipnt02.btlabs.bt.co.uk>

> > > I think it is also related to the complexity of the compiler.  I
> > > expect that any modern compiler will turn "x+=1" into INC X.  
> > 
> > If optimisation is turned off I sincerely hope it doesn't!
> 
> Why not?

Because if I'm writing a time critical program and I have 
a loop that's running just slightly too fast with an x++ 
in it I expect to be able to slow the loop down by changing 
x++ to x+=1

If the compiler treats those two as equivalent then the 
loop won't change. That's the kind of premature optimisation 
that I don't want. (It also affects debugging of complex 
code too, if the assembler is the same for x++ and x+=1 
I'm going to have some strange results when running the 
assembler debugger.)

Alan g.


From sarmstrong13@mac.com  Wed Jul 24 20:28:25 2002
From: sarmstrong13@mac.com (SA)
Date: Wed, 24 Jul 2002 14:28:25 -0500
Subject: [Tutor] Python for Palm?
Message-ID: <B9646A09.9EEB%sarmstrong13@mac.com>

Does anyone know of a good port of Python to the Palm OS?

Not pippy, that seems to be useless and not very well documented.
Why is it I can't find a good python port for Palm OS? There is a tcl port
and a java vm. Why is Python so behind?(I'm not dogging on python by the
way)

Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me



From Doug.Shawhan@gecits.ge.com  Wed Jul 24 21:49:28 2002
From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com)
Date: Wed, 24 Jul 2002 16:49:28 -0400
Subject: [Tutor] Chalkboard morte est?
Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54CE2@msxcvg02itscge.gecits.ge.com>

Is chalkboard gone?

      <http://www.decrem.com:8080/ChalkBoard>

no longer seems to work. If so, too bad. A fine idea.

d


From dyoo@hkn.eecs.berkeley.edu  Wed Jul 24 21:52:21 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 24 Jul 2002 13:52:21 -0700 (PDT)
Subject: [Tutor] Chalkboard morte est?
In-Reply-To: <47B6167F8E69D31194BA0008C7918D4205C54CE2@msxcvg02itscge.gecits.ge.com>
Message-ID: <Pine.LNX.4.44.0207241350050.3110-100000@hkn.eecs.berkeley.edu>


On Wed, 24 Jul 2002 Doug.Shawhan@gecits.ge.com wrote:

> Is chalkboard gone?
>
>       <http://www.decrem.com:8080/ChalkBoard>
>
> no longer seems to work. If so, too bad. A fine idea.


It's off for the moment; I felt I needed to do more work on it before
making it available.  I've just rebuilt my computer at home, so I'll have
more time to work on it for weekends now.


In the meantime, we can use Useless Python:

    http://uselesspython.com


My apologies!



From max_ig@yahoo.com  Wed Jul 24 22:28:01 2002
From: max_ig@yahoo.com (MIG)
Date: Wed, 24 Jul 2002 14:28:01 -0700 (PDT)
Subject: [Tutor] PMW/Tkinter
Message-ID: <20020724212801.85191.qmail@web11302.mail.yahoo.com>

I want to know how can I set up a maximized window with PMW module or
Tkinter.

Tanks in advance,

Max

__________________________________________________
Do You Yahoo!?
Yahoo! Health - Feel better, live better
http://health.yahoo.com


From dyoo@hkn.eecs.berkeley.edu  Thu Jul 25 01:25:16 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 24 Jul 2002 17:25:16 -0700 (PDT)
Subject: [Tutor] Parsing HTML    [Parsing the British open]
In-Reply-To: <20020718223336.GB6188@boora.com>
Message-ID: <Pine.LNX.4.44.0207241648520.7977-100000@hkn.eecs.berkeley.edu>

Hi Michael,


I just double checked on the archives; has anyone responded to your
question about HTML parsing yet?


> Here's my problem.  I want to extract a players score from the live
> leaderboard at the british open.  The URL is
> http://scores.golfweb.com/scoreboards/britishopen/2002/leaderboard/
>
> I have some players listed in a text file. For each player in the text
> file, I need to extract his total score. It appears the total score is 3
> lines below the line that has his name.


Are you still working on this problem?  Parsing structured documents is
a little involved, but not too bad.


For HTML parsing, we can use the 'sgmllib' parser module; there's actually
another module called 'httplib' for html parsing, but I find it's often
too specialized;  I like the fine-grained control I get from sgmllib.




It looks like that british open page has a bunch of table rows.  Here's an
example of one of their rows:

<!------!>
<tr class="bg3"><td colspan="10"><b>Players:</b><b><a
href="leaderboard_rank_1.html">1-50</a></b> | <b><a
href="leaderboard_rank_2.html">51-83</a></b> | <b>Full
Leaderboard</b></td></tr>
<tr align="center" class="bg1">
<td width="35"><b>Pos</b></td>
<td width="227" align="left"><b>Player: <a
href="leaderboard_last.html">Last</a> | <a
href="leaderboard_first.html">First</a></b></td>

<td width="45"><b><a href="leaderboard_today.html">Today</a></b></td>
<td width="50"><b><a href="leaderboard_hole.html">Thru</a></b></td>
<td width="55"><b>To Par</b></td>
<td width="30"><b><a href="leaderboard_r1.html">R1</a></b></td>
<td width="30"><b><a href="leaderboard_r2.html">R2</a></b></td>
<td width="30"><b><a href="leaderboard_r3.html">R3</a></b></td>
<td width="30"><b><a href="leaderboard_r4.html">R4</a></b></td>
<td width="60"><b>Total</b></td></tr>
<!------!>


So the interesting table rows have the following columns:

---
Position
Player
Today
Thru
To Par
R1
R2
R3
R4
Total
---


Let's see how we might parse something like this in sgmllib.  To create a
parser, we can create a subclass of a parser, and tell it to pay close
attention whenever it sees TR and TD tags.  The approach I'll take is to
try parsing every row in any table in the page, and only keep the ones
that look like player records to me.


###
import sgmllib

class OpenCupParser(sgmllib.SGMLParser):
    def __init__(self):
        sgmllib.SGMLParser.__init__(self)
        self._rows = []
        self._new_row = {}
        self._column_names = """position player today thru to_par r1
                           r2 r3 r4 total""".split()
        self._column_index = 0


    def rows(self):
        """Returns the rows we extract from the British Open Cup."""
        return self._rows


    def _is_valid_row(self, some_row):
        """Returns true if the content of some_row looks like a
player's record.  This is just a heuristic."""
        last_column_index = len(self._column_names) - 1
        return (len(some_row.keys()) >= len(self._column_names)
                and is_int(some_row[0])
                and is_int(some_row[last_column_index]))


    def start_tr(self, attributes):
        self._new_row = {}
        self._column_index = 0


    def end_tr(self):
        if self._is_valid_row(self._new_row):
            values = [self._new_row[i]
                      for i in range(len(self._column_names))]
            self._rows.append(zip_dict(self._column_names,
                                       values))

    def start_td(self, attributes): pass


    def end_td(self):
        self._column_index += 1


    def handle_data(self, data):
        self._new_row[self._column_index] = data


def is_int(thing):
    """Returns true if the thing looks like an integer."""
    try:
        int(thing)
    except ValueError:
        return 0
    return 1


def zip_dict(keys, values):
    """Given a sequence of keys and a sequence of values, returns a
dictionary that maps keys[0] to values[0], keys[1] to values[1],
etc."""

    dict = {}
    for k, v in zip(keys, values):
        dict[k] = v
    return dict


if __name__ == '__main__':
    import urllib
    page = urllib.urlopen('http://scores.golfweb.com/'
                          'scoreboards/britishopen/2002/'
                          'leaderboard/').read()
    parser = OpenCupParser()
    parser.feed(page)
    for row in parser.rows():
        print row
###



Hope this helps!




From kyle@sent.com  Thu Jul 25 02:40:40 2002
From: kyle@sent.com (kyle@sent.com)
Date: Thu, 25 Jul 2002 01:40:40 +0000
Subject: [Tutor] newbie question
Message-ID: <20020725014040.8812F6DA1E@www.fastmail.fm>

So far I have a few small programs I wrote to use on my computer, but
expanding what I have learned on web pages if confusing me because
there is one stupid newbie rule that I don't know and can't find.=20
What's the big secret of the content type?  As you can see at
http://sbn.f2o.org/cgi-bin/test2.py I can't even get (literally) the
simplest of scripts to execute because the source gets dumped whenever
I try.  So what is the rule?  I know it's simple, but I searched google
and looked in the docs came out empty handed.

Thank you,
--
Kyle


From troels@kvaksalver.dk  Thu Jul 25 03:10:56 2002
From: troels@kvaksalver.dk (Troels Leth Petersen)
Date: Thu, 25 Jul 2002 04:10:56 +0200
Subject: [Tutor] Splitting a string into a list.
Message-ID: <02b201c23380$82ca6d50$0a01a8c0@allah>

Isn't there a built-in that does the following:

>>> liste = []
>>> for char in thing:
...  liste.append(char)
...  
>>> liste
['l', 'o', 't', 't', 'o']
>>> 

?

Regards,
Troels



From dyoo@hkn.eecs.berkeley.edu  Thu Jul 25 02:59:42 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 24 Jul 2002 18:59:42 -0700 (PDT)
Subject: [Tutor] newbie question
In-Reply-To: <20020725014040.8812F6DA1E@www.fastmail.fm>
Message-ID: <Pine.LNX.4.44.0207241844380.11114-100000@hkn.eecs.berkeley.edu>


On Thu, 25 Jul 2002 kyle@sent.com wrote:

> So far I have a few small programs I wrote to use on my computer, but
> expanding what I have learned on web pages if confusing me because there
> is one stupid newbie rule that I don't know and can't find.  What's the
> big secret of the content type?  As you can see at
> http://sbn.f2o.org/cgi-bin/test2.py I can't even get (literally) the
> simplest of scripts to execute because the source gets dumped whenever I
> try.


Hi Kyle,

The problem probably isn't with the content-type header --- actually, it
looks like it's with the web server configuration.  From what I can tell,
Apache is not recognizing that 'test2.py' should be executed as a cgi
script.

This is somewhat odd, since it does look like you placed the program in
the '/cgi-bin/' directory, and by default, that should have been set up
correctly... hmmm... let's check it.  Here's a link on Apache's web site
on getting CGI's to run:

    http://httpd.apache.org/docs/howto/cgi.html

It mentions that you need to have a ScriptAlias defined for CGI's to run.
Can you check to see that 'ScriptAlias' is defined correctly?


By the way, if you run into problems while getting Apache to accept CGI's,
you may want to ask on the Apache users group list:

    http://httpd.apache.org/userslist.html

since there should be Apache experts there that can help you.


Best of wishes to you!



From dyoo@hkn.eecs.berkeley.edu  Thu Jul 25 03:02:11 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 24 Jul 2002 19:02:11 -0700 (PDT)
Subject: [Tutor] Splitting a string into a list.
In-Reply-To: <02b201c23380$82ca6d50$0a01a8c0@allah>
Message-ID: <Pine.LNX.4.44.0207241859470.11114-100000@hkn.eecs.berkeley.edu>


On Thu, 25 Jul 2002, Troels Leth Petersen wrote:

> Isn't there a built-in that does the following:
>
> >>> liste = []
> >>> for char in thing:
> ...  liste.append(char)
> ...
> >>> liste
> ['l', 'o', 't', 't', 'o']


###
>>> lotto = "youareawinner"
>>> list(lotto)
['y', 'o', 'u', 'a', 'r', 'e', 'a', 'w', 'i', 'n', 'n', 'e', 'r']
###

Yes.  *grin*


The list() builtin will turn any sequence-like thing into a list of its
elements.  To go back, from a list of characters to a string, is a little
weirder: we can use a join, using the empty string:

###
>>> ''.join(list(lotto))
'youareawinner'
###



Hope this helps!



From wolf_binary@hotmail.com  Thu Jul 25 03:13:50 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Wed, 24 Jul 2002 21:13:50 -0500
Subject: [Tutor] newbie question
References: <20020725014040.8812F6DA1E@www.fastmail.fm>
Message-ID: <DAV20sA91E9GQvnbEG10001342f@hotmail.com>

I got your program to run and it gave me just:
Content-type: text/html



<b>Hello World!</b>
<i>Hello World!</i>

for output.  What are you trying to do?

Cameron Stoner
----- Original Message ----- 
From: <kyle@sent.com>
To: "tutor" <tutor@python.org>
Sent: Wednesday, July 24, 2002 8:40 PM
Subject: [Tutor] newbie question


So far I have a few small programs I wrote to use on my computer, but
expanding what I have learned on web pages if confusing me because
there is one stupid newbie rule that I don't know and can't find. 
What's the big secret of the content type?  As you can see at
http://sbn.f2o.org/cgi-bin/test2.py I can't even get (literally) the
simplest of scripts to execute because the source gets dumped whenever
I try.  So what is the rule?  I know it's simple, but I searched google
and looked in the docs came out empty handed.

Thank you,
--
Kyle

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



From alex@halavais.net  Thu Jul 25 03:34:33 2002
From: alex@halavais.net (Alexander C Halavais)
Date: Wed, 24 Jul 2002 22:34:33 -0400
Subject: [Tutor] newbie question
In-Reply-To: <20020725014040.8812F6DA1E@www.fastmail.fm>
Message-ID: <MGEPLJFGPBFECJLBIHLMAEPKDLAA.halavais@buffalo.edu>

This may be obvious: but are you sure you aren't leading with a newline. It
looks like that may be the problem (though it's hard to tell via the
browser). I.e., #! /usr/bin/python must be on the very first line. Again,
I'm sure this is obvious, but are you sure of the location of the
interpreter?

Alex


-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
kyle@sent.com
Sent: Wednesday, July 24, 2002 9:41 PM
To: tutor
Subject: [Tutor] newbie question


So far I have a few small programs I wrote to use on my computer, but
expanding what I have learned on web pages if confusing me because
there is one stupid newbie rule that I don't know and can't find.
What's the big secret of the content type?  As you can see at
http://sbn.f2o.org/cgi-bin/test2.py I can't even get (literally) the
simplest of scripts to execute because the source gets dumped whenever
I try.  So what is the rule?  I know it's simple, but I searched google
and looked in the docs came out empty handed.

Thank you,
--
Kyle

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



From slime@vsnl.net  Wed Jul 24 04:20:57 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Wed, 24 Jul 2002 08:50:57 +0530
Subject: [Tutor] Mail display filter  (WAS Re: Curious newbie)
In-Reply-To: <20020723230935.GB6952@dman.ddts.net>
References: <415C917D807AD411B72C00805FF7330B0383626F@MAILSRV> <20020723080408.GA21524@dman.ddts.net> <20020723135254.GA1112@marcolab.proconet> <200207231438.07088.einarth@decode.is> <20020723230935.GB6952@dman.ddts.net>
Message-ID: <20020724032057.GA8029@localhost.localdomain>

--tKW2IUtsqtDRztdT
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

Hi,

    This is mail is _seriously_ OT, but I just thought it might benefit
some people here ...

On Tue, 23 Jul 2002 Derrick 'dman' Hudson spewed into the ether:
[-- snippity --]
> PS. as for the interleaved '|' and '>', the '>' is inserted by
>     someone else's mailer when they reply to a message.  The '|' is
>     inserted by my mailer when I reply.  They are interleaved when we
>     reply to each other's messages.  The '>' is most common, but I
>     find it distracting and prefer '|'.  Some people even use '%' or
>     do wacky indenation and labelling things with their quoting.

    I personally never liked this, so, with the help of people on the
mutt-users list, I hacked up this script sometime back :

    http://www.symonds.net/~prahladv/files/display_filter.pl

    Yes, I know it is in perl, but it serves it's purpose - Sorry :-)

pv.
--=20
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

Let's send the Russians defective lifestyle accessories!

--tKW2IUtsqtDRztdT
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.4 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE9Ph0ZIKhjOSElu4YRAlljAKC86qQVLhD/X/MEjS0XS0UUoTgxewCfdFFm
vM51DdPCwb3wfP2lLOuM2v8=
=xV3E
-----END PGP SIGNATURE-----

--tKW2IUtsqtDRztdT--


From fgranger@altern.org  Thu Jul 25 09:27:38 2002
From: fgranger@altern.org (Francois Granger)
Date: Thu, 25 Jul 2002 10:27:38 +0200
Subject: [Tutor] Splitting a string into a list.
In-Reply-To: <02b201c23380$82ca6d50$0a01a8c0@allah>
References: <02b201c23380$82ca6d50$0a01a8c0@allah>
Message-ID: <a05100303b96566278d5f@[192.168.1.11]>

At 4:10 +0200 25/07/02, in message [Tutor] Splitting a string into a 
list., Troels Leth Petersen wrote:
>Isn't there a built-in that does the following:
>
>>>>  liste = []
>>>>  for char in thing:
>...  liste.append(char)
>... 
>>>>  liste
>['l', 'o', 't', 't', 'o']
>  >>>

Aside from the list() builtin, you can treat a string as a non mutable list.

for exemple:
>>>  a = 'toto'
>>>  for b in a[:]:
...  print b
...
t
o
t
o
>>>


From gege@nst.pku.edu.cn  Thu Jul 25 11:13:20 2002
From: gege@nst.pku.edu.cn (Ares Liu)
Date: Thu, 25 Jul 2002 18:13:20 +0800
Subject: [Tutor] A question about Mailman soft.
References: <02b201c23380$82ca6d50$0a01a8c0@allah> <a05100303b96566278d5f@[192.168.1.11]>
Message-ID: <00f601c233c3$e8a9b2f0$8300a8c0@jadeite.com>

SGksIGFsbA0KDQpJIGluc3RhbGxlZCBtYWlsbWFuIHNvZnQgZm9yIG1haWxpbmcgbGlzdCBvbiBt
eSBib3gsIGFuZCBtYWtlIGEgbmV3IGxpc3QgbmFtZWQgYXMgdGVzdC4gV2hlbiBJIGRvIHNvbWUg
Y29uZmlndXJhdGlvbiBvZiB0ZXN0IGxpc3QgYXMgdGVzdCBBZG1pbmlzdHJhdGlvbiwgSSBtZXQg
YSBxdWVzdGlvbiBhYm91dCBQcmVmaXggZm9yIHN1YmplY3QgbGluZSBvZiBsaXN0IHBvc3Rpbmdz
LiBJbiB0aGUgT3B0aW9uIG9mICJQcmVmaXggZm9yIHN1YmplY3QgbGluZSBvZiBsaXN0IHBvc3Rp
bmdzIiwgSSBmaWxsIGluICJbVGVzdF0gIi4gdGhlbiBJIGNhbiByZWNlaXZlIGEgbWFpbCB0aGF0
IHN1YmplY3RlZCBhcyAiW1Rlc3RdIFRoaXMgaXMgbXkgdGVzdC4iIHZpYSBNUyBvdXRsb29rIGV4
cHJlc3MuIFdoZW4gSSBwcmVzcyBSZXBseSBidXR0b24gb24gb3V0bG9vb2sgZXhwcmVzcywgdGhl
IHN1YmplY3QgYXBwZWFyIGFzICJSZTogW1Rlc3RdIFRoaXMgaXMgbXkgdGVzdC4iLiBTZW5kIGl0
LiBXaGVuIEkgcmVjZWl2ZSBpdCBhZ2FpbiBmcm9tIG1haWxpbmcgbGlzdC4gVGhlIHN1YmplY3Qg
YmVjb21lIGFzICJbVGVzdF0gUmU6IFtUZXN0XSBUaGlzIGlzIG15IHRlc3QuIi4gSXQgaXMgbm90
IHNvIGdvb2QuIEFzIEkga25vdywgUHl0aG9uIFR1dG9yIGFsc28gdXNlIE1haWxtYW4gYXMgaXRz
IG1haWxpbmcgbGlzdCBzb2Z0LCBhbmQgYWxzbyBhZGQgcHJlZml4IFtUdXRvcl0gdG8gc3ViamVj
dCBsaW5lLiBCdXQgaXQgZG9lc24ndCBhZGQgcHJlZml4IFtUdXRvcl0gYWdhaW4gb24gc3ViamVj
dCB3aGljaCBsaWtlcyAiUmU6IFtUdXRvcl0gc3RoLiIuIFdobyBjYW4gdGVsbCBtZSBob3cgdG8g
aW1wbGVtZW50IGl0PyANCg0KVGhhbmsgdmVyeSBtdWNoLg0KDQotZ2VnZQ0KDQo=



From alan.gauld@bt.com  Thu Jul 25 17:37:51 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 25 Jul 2002 17:37:51 +0100
Subject: [Tutor] Splitting a string into a list.
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C78E@mbtlipnt02.btlabs.bt.co.uk>

> Isn't there a built-in that does the following:
> 
> >>> liste = []
> >>> for char in thing:
> ...  liste.append(char)
> ...  

liste = thing[:]  # make a copy

Should do it.

Alan g.


From alan.gauld@bt.com  Thu Jul 25 17:41:52 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 25 Jul 2002 17:41:52 +0100
Subject: [Tutor] Splitting a string into a list.
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C78F@mbtlipnt02.btlabs.bt.co.uk>

> On Thu, 25 Jul 2002, Troels Leth Petersen wrote:
> > Isn't there a built-in that does the following:
> > >>> liste
> > ['l', 'o', 't', 't', 'o']

Oops my copy solution doesn't work, sorry, 
I should have read the problem statement more slowly.

> The list() builtin will turn any sequence-like thing into a 
> list of its elements.  

Indeed.

map(None, thing)

works too.

Alan g.



From dyoo@hkn.eecs.berkeley.edu  Thu Jul 25 21:25:11 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 25 Jul 2002 13:25:11 -0700 (PDT)
Subject: [Tutor] A question about Mailman soft.
In-Reply-To: <00f601c233c3$e8a9b2f0$8300a8c0@jadeite.com>
Message-ID: <Pine.LNX.4.44.0207251300030.6325-100000@hkn.eecs.berkeley.edu>


On Thu, 25 Jul 2002, Ares Liu wrote:

> I installed mailman soft for mailing list on my box, and make a new list
> named as test. When I do some configuration of test list as test
> Administration, I met a question about Prefix for subject line of list
> postings. In the Option of "Prefix for subject line of list postings", I
> fill in "[Test] ". then I can receive a mail that subjected as "[Test]
> This is my test." via MS outlook express. When I press Reply button on
> outloook express, the subject appear as "Re: [Test] This is my test.".
> Send it. When I receive it again from mailing list. The subject become
> as "[Test] Re: [Test] This is my test.". It is not so good. As I know,
> Python Tutor also use Mailman as its mailing list soft, and also add
> prefix [Tutor] to subject line. But it doesn't add prefix [Tutor] again
> on subject which likes "Re: [Tutor] sth.". Who can tell me how to
> implement it?


Hi Ares,

Hmmm... this seems very specific to Mailman, so you may want to ask on the
Mailman-users mailing list about this one:

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



I've always assumed that the code that prepended the mailing list "subject
prefix" would check to see if it already existed in the message title.
Let me check in the source code...  I'll look in the source code of
Mailman 2.0beta2.


###
$ grep -r subject_prefix *
Handlers/Acknowledge.py:            prefix = mlist.subject_prefix
Handlers/CookHeaders.py:        prefix = mlist.subject_prefix
Handlers/ToDigest.py:    mo = re.match('(re:? *)?(%s)' %
re.escape(mlist.subject_prefix),
Handlers/ToUsenet.py:    subjpref = mlist.subject_prefix
MailList.py:	self.subject_prefix = mm_cfg.DEFAULT_SUBJECT_PREFIX %
self.__dict__
MailList.py:	    ('subject_prefix', mm_cfg.String, WIDTH, 0,
###


Ah, I see.  The code that adds the prefix is in the
Handlers.CookHeaders.process() function.



Here's the chunk of code that puts the prefix in the subject header:

###
        # subject header added by the ToDigest module.
        prefix = mlist.subject_prefix
        # we purposefully leave no space b/w prefix and subject!
        if not subject:
            msg['Subject'] = prefix + '(no subject)'
        elif prefix and not re.search(re.escape(prefix), subject, re.I):
            msg['Subject'] = prefix + subject
###

So, yes, Mailman should not be adding that additional prefix in the
replied message, because Mailman is supposed to search for it before
adding it in.  It's very odd that you're seeing different behavior...



Try asking on the Mailman users list; perhaps someone there knows of a bug
or workaround.  Also, tell them which version of Mailman you've installed,
so that other people can effectively hunt this bug for you.


Hope this helps!



From rob@uselesspython.com  Thu Jul 25 23:26:10 2002
From: rob@uselesspython.com (Rob)
Date: Thu, 25 Jul 2002 17:26:10 -0500
Subject: [Tutor] printing columns
Message-ID: <MPEOIFCOPCIHEDCLBLPBIEBICBAA.rob@uselesspython.com>

This is another one of my odd useless projects. I've written a little Python
code that produces a header file for a C++ program, but I've got a simple
bit of polish I'd like to put on it. Now that I look at it, I'm amazed that
I haven't run into this before, but I'm getting ahead of myself. In any
event, some of the Python newbies should enjoy this one.

I needed to create a simple header file for a C++ program for class, and
noted how utterly repetitive it was going to be. It consisted of nothing but
a series of #define statements. Aha, a chance to take a snake break!

So I made a list of items:

>>> menuItems = ['NEW', 'OPEN', 'CLOSE', 'SAVE', 'SAVEAS', 'PAGESETUP',
'PRINTPREVIEW', 'PRINT', 'EXIT', 'UNDO', 'CUT', 'COPY', 'PASTE', 'SEARCH',
'NORMALVIEW', 'PRINTVIEW', 'ZOOMVIEW', 'STANDARDTB', 'EDITTB', 'STATUSTB',
'CUSTOMTB', 'CASCADE', 'TILE', 'SPLIT']

Then I whipped up a little for loop to print out the list of preprocessor
directives for the header file:

>>> myInt = 1
>>> for item in menuItems:
	print '#define ROB_' + item + '\t\t' + str(myInt)
	myInt = myInt + 1

Now I'm wondering how I could do this a little more neatly, organizing the
output into two columns. The incremented myInt values would be the second
column.

Rob
http://uselesspython.com




From dyoo@hkn.eecs.berkeley.edu  Thu Jul 25 23:46:33 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 25 Jul 2002 15:46:33 -0700 (PDT)
Subject: [Tutor] printing columns
In-Reply-To: <MPEOIFCOPCIHEDCLBLPBIEBICBAA.rob@uselesspython.com>
Message-ID: <Pine.LNX.4.44.0207251539370.13973-100000@hkn.eecs.berkeley.edu>


On Thu, 25 Jul 2002, Rob wrote:

> >>> menuItems = ['NEW', 'OPEN', 'CLOSE', 'SAVE', 'SAVEAS', 'PAGESETUP',
> 'PRINTPREVIEW', 'PRINT', 'EXIT', 'UNDO', 'CUT', 'COPY', 'PASTE', 'SEARCH',
> 'NORMALVIEW', 'PRINTVIEW', 'ZOOMVIEW', 'STANDARDTB', 'EDITTB', 'STATUSTB',
> 'CUSTOMTB', 'CASCADE', 'TILE', 'SPLIT']
>
> Then I whipped up a little for loop to print out the list of preprocessor
> directives for the header file:
>
> >>> myInt = 1
> >>> for item in menuItems:
> 	print '#define ROB_' + item + '\t\t' + str(myInt)
> 	myInt = myInt + 1
>
> Now I'm wondering how I could do this a little more neatly, organizing
> the output into two columns. The incremented myInt values would be the
> second column.


Hi Rob,


We can attach menu item numbers, without a for loop, with some creative
use of the zip() builtin function:

###
>>> menuItems = ['NEW', 'OPEN', 'CLOSE', 'SAVE', 'SAVEAS', 'PAGESETUP',
... 'PRINTPREVIEW', 'PRINT', 'EXIT', 'UNDO', 'CUT', 'COPY', 'PASTE', 'SEARCH',
... 'NORMALVIEW', 'PRINTVIEW', 'ZOOMVIEW', 'STANDARDTB', 'EDITTB', 'STATUSTB',
... 'CUSTOMTB', 'CASCADE', 'TILE', 'SPLIT']
>>>
>>>
>>> numbered_menu_items = zip(menuItems, range(1, len(menuItems)+1))
>>>
>>>
>>> numbered_menu_items
[('NEW', 1), ('OPEN', 2), ('CLOSE', 3), ('SAVE', 4), ('SAVEAS', 5),
 ('PAGESETUP', 6), ('PRINTPREVIEW', 7), ('PRINT', 8), ('EXIT', 9),
 ('UNDO', 10), ('CUT', 11), ('COPY', 12), ('PASTE', 13), ('SEARCH', 14),
 ('NORMALVIEW', 15), ('PRINTVIEW', 16), ('ZOOMVIEW', 17),
 ('STANDARDTB', 18), ('EDITTB', 19), ('STATUSTB', 20), ('CUSTOMTB', 21),
 ('CASCADE', 22), ('TILE', 23), ('SPLIT', 24)]
###


Is this what you were looking for?



Best of wishes to you!



From Kyle Babich" <kb@mm.st  Fri Jul 26 00:32:23 2002
From: Kyle Babich" <kb@mm.st (Kyle Babich)
Date: Thu, 25 Jul 2002 23:32:23 +0000
Subject: [Tutor] (no subject)
Message-ID: <20020725233223.C6CB66DACF@www.fastmail.fm>

This is a multi-part message in MIME format.

--_----------=_1027639943311120
Content-Disposition: inline
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: quoted-printable

This is the error I get when I try to execute my script:

[Thu Jul 25 18:09:24 2002] [error] [client 65.59.106.226] Premature end
of script headers: /home/sites/sbn/www/public_html/index.py
Traceback (most recent call last):
  File "/home/sites/sbn/www/public_html/index.py", line 671, in ?
    print """
KeyError: content
Traceback (most recent call last):
  File "/home/sites/sbn/www/public_html/index.py", line 671, in ?
    print """
KeyError: content
Traceback (most recent call last):
  File "/home/sites/sbn/www/public_html/cgi-bin/index.py", line 671, in
  ?
    print """
KeyError: content

And all that displays in the browser is a blank page.
I have attached the script.

Can someone help me with this?  It seems like it is having a problem
printing content but near the beginning I do have content =3D con.

Thank you,
--
Kyle

--_----------=_1027639943311120
Content-Disposition: attachment; filename="index.py"
Content-Transfer-Encoding: base64
Content-Type: application/unknown; name="index.py"

IyEgL3Vzci9iaW4vcHl0aG9uDQoNCmltcG9ydCBjZ2kNCg0KcHJpbnQgIkNv
bnRlbnQtdHlwZTogdGV4dC9odG1sIg0KcHJpbnQNCg0KZm9ybSA9IGNnaS5G
aWVsZFN0b3JhZ2UoKQ0KdHJ5Og0KICAgIGNvbiA9IGZvcm1bJ2NvbiddLnZh
bHVlDQpleGNlcHQgS2V5RXJyb3I6DQogICAgY29uID0gIiINCiAgICBjb250
ZW50ID0gY29uDQoNCiAgICBpZiBjb24gPT0gImluZGV4IjoNCiAgICAgICAg
Y29udGVudCA9ICIiIg0KICAgICAgICA8aGVhZD4NCiAgICAgICAgPHRpdGxl
Pk9mZmljaWFsIFdlYiBTaXRlIG9mIFN1aWNpZGUgYnkgTnVtYmVyczwvdGl0
bGU+DQogICAgICAgIDxsaW5rIHJlbD0ic3R5bGVzaGVldCIgdHlwZT0idGV4
dC9jc3MiIGhyZWY9ImNzcy9nZW4uY3NzIj4NCiAgICAgICAgPG1ldGEgaHR0
cC1lcXVpdj0iQ29udGVudC10eXBlIiBjb250ZW50PSJ0ZXh0L2h0bWwiPg0K
DQogICAgICAgIDxTQ1JJUFQgTEFOR1VBR0U9IkphdmFTY3JpcHQiPg0KICAg
ICAgICA8IS0tIElkZWEgYnk6ICBOaWMgV29sZmUgKE5pY0BUaW1lbGFwc2VQ
cm9kdWN0aW9ucy5jb20pIC0tPg0KICAgICAgICA8IS0tIFdlYiBVUkw6ICBo
dHRwOi8vZmluZWxpbmUueHMubXcgLS0+DQoNCiAgICAgICAgPCEtLSBUaGlz
IHNjcmlwdCBhbmQgbWFueSBtb3JlIGFyZSBhdmFpbGFibGUgZnJlZSBvbmxp
bmUgYXQgLS0+DQogICAgICAgIDwhLS0gVGhlIEphdmFTY3JpcHQgU291cmNl
ISEgaHR0cDovL2phdmFzY3JpcHQuaW50ZXJuZXQuY29tIC0tPg0KDQogICAg
ICAgIDwhLS0gQmVnaW4NCiAgICAgICAgZnVuY3Rpb24gcG9wVXAoVVJMKSB7
DQogICAgICAgIGRheSA9IG5ldyBEYXRlKCk7DQogICAgICAgIGlkID0gZGF5
LmdldFRpbWUoKTsNCiAgICAgICAgZXZhbCgicGFnZSIgKyBpZCArICIgPSB3
aW5kb3cub3BlbihVUkwsICciICsgaWQgKyAiJywgJ3Rvb2xiYXI9MCxzY3Jv
bGxiYXJzPTAsbG9jYXRpb249MCxzdGF0dXNiYXI9MSxtZW51YmFyPTAscmVz
aXphYmxlPTEsd2lkdGg9ODc1LGhlaWdodD02MjUsbGVmdCA9IDM3LHRvcCA9
IDM0Jyk7Iik7DQogICAgICAgIH0NCiAgICAgICAgLy8gRW5kIC0tPg0KICAg
ICAgICA8L3NjcmlwdD4NCg0KICAgICAgICA8L2hlYWQ+DQoNCiAgICAgICAg
PGJvZHkgYmdjb2xvcj0iIzAwMDAwMCI+DQoNCiAgICAgICAgPHRhYmxlIHdp
ZHRoPSIxMDAlIiBjZWxsc3BhY2luZz0iMCIgY2VsbHBhZGRpbmc9IjEiIGJv
cmRlcj0iMCIgYWxpZ249ImNlbnRlciI+DQogICAgICAgIDx0Ym9keT4NCiAg
ICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUiIGFsaWduPSJs
ZWZ0IiBiZ2NvbG9yPSIjY2MwMDAwIj4NCiAgICAgICAgPGZvbnQgZmFjZT0i
Y2hpbGxlciwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNmZmZm
ZmYiIHNpemU9IjUiPg0KICAgICAgICA8Yj4mbmJzcDsmbmJzcDtPZmZpY2lh
bCBXZWIgU2l0ZSBvZiBTdWljaWRlIGJ5IE51bWJlcnM8L2I+DQogICAgICAg
IDwvZm9udD48L3RkPjwvdHI+PC90Ym9keT48L3RhYmxlPg0KDQogICAgICAg
IDxicj4mbmJzcDs8YnI+DQoNCiAgICAgICAgPGNlbnRlcj4NCiAgICAgICAg
PGEgaHJlZj0iamF2YXNjcmlwdDpwb3BVcCgnaW5kZXgucHk/Y29uPWluZGV4
MicpIiBzdHlsZT0idGV4dC1kZWNvcmF0aW9uOm5vbmUiPg0KICAgICAgICA8
aW1nIHNyYz0iaW1hZ2VzL2Nyb3NzLmdpZiIgYm9yZGVyPSIwIj4NCiAgICAg
ICAgPGJyPg0KICAgICAgICA8Zm9udCBmYWNlPSJjaGlsbGVyLCBhcmlhbCwg
dGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iI2NjMDAwMCIgc2l6ZT0iNyI+DQog
ICAgICAgIDxiPkUmbmJzcDtOJm5ic3A7VEUmbmJzcDtSPC9iPg0KICAgICAg
ICA8L2E+DQogICAgICAgIDwvZm9udD4NCiAgICAgICAgPC9jZW50ZXI+DQoN
CiAgICAgICAgPC9ib2R5PjwvaHRtbD4NCiAgICAgICAgIiIiDQoNCiAgICBl
bGlmIGNvbiA9PSAiaW5kZXgyIjoNCiAgICAgICAgY29udGVudCA9ICIiIg0K
ICAgICAgICA8aGVhZD4NCiAgICAgICAgPHRpdGxlPk9mZmljaWFsIFdlYiBT
aXRlIG9mIFN1aWNpZGUgYnkgTnVtYmVyczwvdGl0bGU+DQogICAgICAgIDxt
ZXRhIGh0dHAtZXF1aXY9IkNvbnRlbnQtdHlwZSIgY29udGVudD0idGV4dC9o
dG1sIj4NCiAgICAgICAgPC9oZWFkPg0KDQogICAgICAgIDxmcmFtZXNldCBy
b3dzPSIxNSUsIDgwJSwgNSUiIGJvcmRlcj0iMCIgZnJhbWVib3JkZXI9IjAi
IGZyYW1lc3BhY2luZz0iMCI+DQogICAgICAgIDxmcmFtZSBuYW1lPSJiYW5u
ZXIiIHNyYz0iaW5kZXgucHk/Y29uPWJhbm5lciIgbm9yZXNpemU9InllcyIg
c2Nyb2xsaW5nPSJubyI+DQoNCiAgICAgICAgPGZyYW1lc2V0IGNvbHM9IjE1
JSwgODUlIiBib3JkZXI9IjAiIGZyYW1lYm9yZGVyPSIwIiBmcmFtZXNwYWNp
bmc9IjAiPg0KICAgICAgICA8ZnJhbWUgbmFtZT0iY29udGVudCIgc3JjPSJp
bmRleC5weT9jb249Y29udGVudCIgc2Nyb2xsaW5nPSJubyIgbm9yZXNpemU9
InllcyI+DQogICAgICAgIDxmcmFtZSBuYW1lPSJtYWluIiBzcmM9ImluZGV4
LnB5P2Nvbj1tYWluIiBub3Jlc2l6ZT0ieWVzIj4NCiAgICAgICAgPC9mcmFt
ZXNldD4NCg0KICAgICAgICA8ZnJhbWUgbmFtZT0iYm90IiBzcmM9ImluZGV4
LnB5P2Nvbj1ib3QiIG5vcmVzaXplPSJ5ZXMiIHNjcm9sbGluZz0ibm8iPg0K
DQogICAgICAgIDwvZnJhbWVzZXQ+DQoNCiAgICAgICAgPC9odG1sPg0KICAg
ICAgICAiIiINCg0KICAgIGVsaWYgY29uID09ICJiYW5uZXIiOg0KICAgICAg
ICBjb250ZW50ID0gIiIiDQogICAgICAgIDxoZWFkPg0KICAgICAgICA8bGlu
ayByZWw9InN0eWxlc2hlZXQiIHR5cGU9InRleHQvY3NzIiBocmVmPSJjc3Mv
Z2VuLmNzcyI+DQogICAgICAgIDxtZXRhIGh0dHAtZXF1aXY9IkNvbnRlbnQt
dHlwZSIgY29udGVudD0idGV4dC9odG1sIj4NCiAgICAgICAgPC9oZWFkPg0K
DQogICAgICAgIDxib2R5IGJnY29sb3I9IiMwMDAwMDAiPg0KDQogICAgICAg
IDx0YWJsZSB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBjZWxsc3BhY2lu
Zz0iMCIgY2VsbHBhZGRpbmc9IjEiIGJvcmRlcj0iMCI+DQogICAgICAgIDx0
Ym9keT4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjEwJSIg
aGVpZ2h0PSIxMDAlIiBhbGlnbj0iY2VudGVyIiB2YWxpZ249Im1pZGRsZSIg
Ymdjb2xvcj0iIzAwMDAwMCI+DQogICAgICAgIDxpbWcgc3JjPSJpbWFnZXMv
c2t1bGwuanBnIiBib3JkZXI9IjAiIHdpZHRoPSI1MCIgaGVpZ2h0PSI2NSI+
DQogICAgICAgIDwvdGQ+DQogICAgICAgIDx0ZCB3aWR0aD0iODAlIiBoZWln
aHQ9IjEwMCUiIGFsaWduPSJjZW50ZXIiIHZhbGlnbj0ibWlkZGxlIiBiZ2Nv
bG9yPSIjMDAwMDAwIj4NCiAgICAgICAgPGZvbnQgZmFjZT0iY2hpbGxlciwg
YXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNjYzAwMDAiIHNpemU9
IjciPg0KICAgICAgICA8Yj5TJm5ic3A7dSZuYnNwO2kmbmJzcDtjJm5ic3A7
aSZuYnNwO2QmbmJzcDtlJm5ic3A7Jm5ic3A7YiZuYnNwO3kmbmJzcDsmbmJz
cDtOJm5ic3A7dSZuYnNwO20mbmJzcDtiJm5ic3A7ZSZuYnNwO3ImbmJzcDtz
PC9iPg0KICAgICAgICA8L2ZvbnQ+DQogICAgICAgIDxicj48Zm9udCBmYWNl
PSJjaGlsbGVyLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iI2Nj
MDAwMCIgc2l6ZT0iNSI+DQogICAgICAgIDxiPk9mZmljaWFsIFdlYiBTaXRl
PC9iPg0KICAgICAgICA8L2ZvbnQ+DQogICAgICAgIDwvdGQ+DQogICAgICAg
IDx0ZCB3aWR0aD0iMTAlIiBoZWlnaHQ9IjEwMCUiIGFsaWduPSJjZW50ZXIi
IHZhbGlnbj0ibWlkZGxlIiBiZ2NvbG9yPSIjMDAwMDAwIj4NCiAgICAgICAg
PGltZyBzcmM9ImltYWdlcy9za3VsbC5qcGciIGJvcmRlcj0iMCIgd2lkdGg9
IjUwIiBoZWlnaHQ9IjY1Ij4NCiAgICAgICAgPC90ZD48L3RyPjwvdGJvZHk+
PC90YWJsZT4NCg0KICAgICAgICA8L2JvZHk+DQogICAgICAgIDwvaHRtbD4N
CiAgICAgICAgIiIiDQoNCiAgICBlbGlmIGNvbiA9PSAiY29udGVudCI6DQog
ICAgICAgIGNvbnRlbnQgPSAiIiINCiAgICAgICAgPGhlYWQ+PGxpbmsgcmVs
PSJzdHlsZXNoZWV0IiB0eXBlPSJ0ZXh0L2NzcyIgaHJlZj0iY3NzL2dlbi5j
c3MiPjxtZXRhIGh0dHAtZXF1aXY9IkNvbnRlbnQiIGNvbnRlbnQ9InRleHQv
aHRtbCI+PC9oZWFkPg0KICAgICAgICA8Ym9keSBiZ2NvbG9yPSIjY2NjY2Nj
Ij4NCiAgICAgICAgPGJyPg0KICAgICAgICA8dGFibGUgd2lkdGg9IjEwMCUi
IGNlbGxzcGFjaW5nPSIwIiBjZWxscGFkZGluZz0iMCIgYWxpZ249ImNlbnRl
ciIgYm9yZGVyPSIwIj4NCiAgICAgICAgPHRib2R5Pg0KICAgICAgICA8dHI+
DQogICAgICAgIDx0ZCB3aWR0aD0iMTAwJSIgYWxpZ249ImNlbnRlciIgYmdj
b2xvcj0iIzY5Njk2OSI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEs
IGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjZmZmZmZmIiBzaXpl
PSIyIj4NCiAgICAgICAgPGEgdGFyZ2V0PSJtYWluIiBocmVmPSJpbmRleC5w
eT9jb249bWFpbiIgc3R5bGU9InRleHQtZGVjb3JhdGlvbjpub25lOyBjb2xv
cjpmZmZmZmYiPkhvbWU8L2E+DQogICAgICAgIDwvZm9udD48L3RkPjwvdHI+
DQogICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIxMDAlIiBiZ2Nv
bG9yPSIjY2NjY2NjIj4mbmJzcDs8L3RkPjwvdHI+DQogICAgICAgIDx0cj4N
CiAgICAgICAgPHRkIHdpZHRoPSIxMDAlIiBhbGlnbj0iY2VudGVyIiBiZ2Nv
bG9yPSIjNjk2OTY5Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVyZGFuYSwg
YXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNmZmZmZmYiIHNpemU9
IjIiPg0KICAgICAgICA8YSB0YXJnZXQ9Im1haW4iIGhyZWY9ImluZGV4LnB5
P2Nvbj1hYm91dHVzIiBzdHlsZT0idGV4dC1kZWNvcmF0aW9uOm5vbmU7IGNv
bG9yOmZmZmZmZiI+QWJvdXQgVXM8L2E+DQogICAgICAgIDwvZm9udD48L3Rk
PjwvdHI+DQogICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIxMDAl
IiBiZ2NvbG9yPSIjY2NjY2NjIj4mbmJzcDs8L3RkPjwvdHI+DQogICAgICAg
IDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIxMDAlIiBhbGlnbj0iY2VudGVy
IiBiZ2NvbG9yPSIjNjk2OTY5Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVy
ZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNmZmZmZmYi
IHNpemU9IjIiPg0KICAgICAgICA8YSB0YXJnZXQ9Im1haW4iIGhyZWY9Imlu
ZGV4LnB5P2Nvbj1waG90b3MiIHN0eWxlPSJ0ZXh0LWRlY29yYXRpb246bm9u
ZTsgY29sb3I6ZmZmZmZmIj5QaG90b3M8L2E+DQogICAgICAgIDwvZm9udD48
L3RkPjwvdHI+DQogICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIx
MDAlIiBiZ2NvbG9yPSIjY2NjY2NjIj4mbmJzcDs8L3RkPjwvdHI+DQogICAg
ICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIxMDAlIiBhbGlnbj0iY2Vu
dGVyIiBiZ2NvbG9yPSIjNjk2OTY5Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0i
dmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNmZmZm
ZmYiIHNpemU9IjIiPg0KICAgICAgICA8YSB0YXJnZXQ9Im1haW4iIGhyZWY9
ImluZGV4LnB5P2Nvbj1seXJpY3MiIHN0eWxlPSJ0ZXh0LWRlY29yYXRpb246
bm9uZTsgY29sb3I6ZmZmZmZmIj5MeXJpY3M8L2E+DQogICAgICAgIDwvZm9u
dD48L3RkPjwvdHI+DQogICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRo
PSIxMDAlIiBiZ2NvbG9yPSIjY2NjY2NjIj4mbmJzcDs8L3RkPjwvdHI+DQog
ICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIxMDAlIiBhbGlnbj0i
Y2VudGVyIiBiZ2NvbG9yPSIjNjk2OTY5Ij4NCiAgICAgICAgPGZvbnQgZmFj
ZT0idmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNm
ZmZmZmYiIHNpemU9IjIiPg0KICAgICAgICA8YSB0YXJnZXQ9Im1haW4iIGhy
ZWY9ImluZGV4LnB5P2Nvbj1iaW9zIiBzdHlsZT0idGV4dC1kZWNvcmF0aW9u
Om5vbmU7IGNvbG9yOmZmZmZmZiI+QmlvczwvYT4NCiAgICAgICAgPC9mb250
PjwvdGQ+PC90cj4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9
IjEwMCUiIGJnY29sb3I9IiNjY2NjY2MiPiZuYnNwOzwvdGQ+PC90cj4NCiAg
ICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUiIGFsaWduPSJj
ZW50ZXIiIGJnY29sb3I9IiM2OTY5NjkiPg0KICAgICAgICA8Zm9udCBmYWNl
PSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iI2Zm
ZmZmZiIgc2l6ZT0iMiI+DQogICAgICAgIDxhIHRhcmdldD0ibWFpbiIgaHJl
Zj0iaW5kZXgucHk/Y29uPWNoYXQiIHN0eWxlPSJ0ZXh0LWRlY29yYXRpb246
bm9uZTsgY29sb3I6ZmZmZmZmIj5DaGF0PC9hPg0KICAgICAgICA8L2ZvbnQ+
PC90ZD48L3RyPg0KICAgICAgICA8dHI+DQogICAgICAgIDx0ZCB3aWR0aD0i
MTAwJSIgYmdjb2xvcj0iI2NjY2NjYyI+Jm5ic3A7PC90ZD48L3RyPg0KICAg
ICAgICA8dHI+DQogICAgICAgIDx0ZCB3aWR0aD0iMTAwJSIgYWxpZ249ImNl
bnRlciIgYmdjb2xvcj0iIzY5Njk2OSI+DQogICAgICAgIDxmb250IGZhY2U9
InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjZmZm
ZmZmIiBzaXplPSIyIj4NCiAgICAgICAgPGEgdGFyZ2V0PSJtYWluIiBocmVm
PSJidXJuaW5nYm9vay8iIHN0eWxlPSJ0ZXh0LWRlY29yYXRpb246bm9uZTsg
Y29sb3I6ZmZmZmZmIj5HdWVzdGJvb2s8L2E+DQogICAgICAgIDwvZm9udD48
L3RkPjwvdHI+DQogICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIx
MDAlIiBiZ2NvbG9yPSIjY2NjY2NjIj4mbmJzcDs8L3RkPjwvdHI+DQogICAg
ICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIxMDAlIiBhbGlnbj0iY2Vu
dGVyIiBiZ2NvbG9yPSIjNjk2OTY5Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0i
dmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNmZmZm
ZmYiIHNpemU9IjIiPg0KICAgICAgICA8YSB0YXJnZXQ9Im1haW4iIGhyZWY9
InBocEJCMi8iIHN0eWxlPSJ0ZXh0LWRlY29yYXRpb246bm9uZTsgY29sb3I6
ZmZmZmZmIj5NZXNzYWdlIEJvYXJkPC9hPg0KICAgICAgICA8L2ZvbnQ+PC90
ZD48L3RyPg0KICAgICAgICA8dHI+PHRkIHdpZHRoPSIxMDAlIiBiZ2NvbG9y
PSIjY2NjY2NjIj4mbmJzcDs8L3RkPjwvdHI+DQogICAgICAgIDx0cj4NCiAg
ICAgICAgPHRkIHdpZHRoPSIxMDAlIiBhbGlnbj0iY2VudGVyIiBiZ2NvbG9y
PSIjNjk2OTY5Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVyZGFuYSwgYXJp
YWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNmZmZmZmYiIHNpemU9IjIi
Pg0KICAgICAgICA8YSB0YXJnZXQ9Im1haW4iIGhyZWY9ImluZGV4LnB5P2Nv
bj1jb250YWN0dXMiIHN0eWxlPSJ0ZXh0LWRlY29yYXRpb246bm9uZTsgY29s
b3I6ZmZmZmZmIj5Db250YWN0IFVzPC9hPg0KICAgICAgICA8L2ZvbnQ+PC90
ZD48L3RyPg0KICAgICAgICA8dHI+DQogICAgICAgIDx0ZCB3aWR0aD0iMTAw
JSIgYmdjb2xvcj0iI2NjY2NjYyI+Jm5ic3A7PC90ZD48L3RyPg0KICAgICAg
ICA8dHI+DQogICAgICAgIDx0ZCB3aWR0aD0iMTAwJSIgYmdjb2xvcj0iI2Nj
Y2NjYyI+Jm5ic3A7PC90ZD48L3RyPjx0cj48dGQgd2lkdGg9IjEwMCUiIGJn
Y29sb3I9IiNjY2NjY2MiPiZuYnNwOzwvdGQ+PC90cj4NCiAgICAgICAgPHRy
Pg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUiIGJnY29sb3I9IiNjY2NjY2Mi
PiZuYnNwOzwvdGQ+PC90cj4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQg
d2lkdGg9IjEwMCUiIGJnY29sb3I9IiNjY2NjY2MiPiZuYnNwOzwvdGQ+PC90
cj4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUiIGFs
aWduPSJjZW50ZXIiIGJnY29sb3I9IiNjYzAwMDAiPg0KICAgICAgICA8Zm9u
dCBmYWNlPSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xv
cj0iI2ZmZmZmZiIgc2l6ZT0iMiI+VmlzaXRvciAjMDAwMDAxDQogICAgICAg
IDwvZm9udD48L3RkPjwvdHI+DQogICAgICAgIDx0cj4NCiAgICAgICAgPHRk
IHdpZHRoPSIxMDAlIiBiZ2NvbG9yPSIjY2NjY2NjIj4mbmJzcDs8L3RkPjwv
dHI+DQogICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIxMDAlIiBh
bGlnbj0iY2VudGVyIiBiZ2NvbG9yPSIjNjk2OTY5Ij4NCiAgICAgICAgPGZv
bnQgZmFjZT0idmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29s
b3I9IiNmZmZmZmYiIHNpemU9IjIiPg0KICAgICAgICA8YSB0YXJnZXQ9Im1h
aW4iIGhyZWY9ImluZGV4LnB5P2Nvbj1jcmVkaXRzIiBzdHlsZT0idGV4dC1k
ZWNvcmF0aW9uOm5vbmU7IGNvbG9yOmZmZmZmZiI+Q3JlZGl0czwvYT4NCiAg
ICAgICAgPC9mb250PjwvdGQ+PC90cj48L3Rib2R5PjwvdGFibGU+DQogICAg
ICAgIDwvYm9keT48L2h0bWw+DQogICAgICAgICIiIg0KDQogICAgZWxpZiBj
b24gPT0gImJvdCI6DQogICAgICAgIGNvbnRlbnQgPSAiIiINCiAgICAgICAg
PGhlYWQ+DQogICAgICAgIDxsaW5rIHJlbD0ic3R5bGVzaGVldCIgdHlwZT0i
dGV4dC9jc3MiIGhyZWY9ImNzcy9nZW4uY3NzIj4NCiAgICAgICAgPG1ldGEg
aHR0cC1lcXVpdj0iQ29udGVudCIgY29udGVudD0idGV4dC9odG1sIj4NCiAg
ICAgICAgPC9oZWFkPg0KICAgICAgICA8Ym9keSBiZ2NvbG9yPSIjMDAwMDAw
Ij4NCg0KICAgICAgICA8dGFibGUgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAw
JSIgYWxpZ249ImNlbnRlciIgdmFsaWduPSJtaWRkbGUiIGJvcmRlcj0iMCI+
DQogICAgICAgIDx0Ym9keT4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQg
d2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgYWxpZ249ImNlbnRlciIgYmdj
b2xvcj0iIzAwMDAwMCI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEs
IGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjY2MwMDAwIiBzaXpl
PSIyIj4NCiAgICAgICAgPGI+RGVzaWduZWQgYnkgS3lsZSAmYW1wOyBKYXNv
biBCYWJpY2ggYW5kIEp1bGlhYW4gQXJhdWpvLjwvYj4NCiAgICAgICAgPC9m
b250Pg0KICAgICAgICA8L3RkPjwvdHI+PC90Ym9keT48L3RhYmxlPg0KDQog
ICAgICAgIDwvYm9keT4NCiAgICAgICAgPC9odG1sPg0KICAgICAgICAiIiIN
Cg0KICAgIGVsaWYgY29uID09ICJtYWluIjoNCiAgICAgICAgY29udGVudCA9
ICIiIg0KICAgICAgICA8IURPQ1RZUEUgSFRNTCBQVUJMSUMgIi0vL1czQy8v
RFREIEhUTUwgNC4xIFRSQU5TSVRJT05BTC8vRU4iPg0KICAgICAgICA8aHRt
bD4NCg0KICAgICAgICA8aGVhZD4NCiAgICAgICAgPGxpbmsgcmVsPSJzdHls
ZXNoZWV0IiB0eXBlPSJ0ZXh0L2NzcyIgaHJlZj0iY3NzL2dlbi5jc3MiPg0K
ICAgICAgICA8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50IiBjb250ZW50PSJ0
ZXh0L2h0bWwiPg0KICAgICAgICA8L2hlYWQ+DQoNCiAgICAgICAgPGJvZHkg
Ymdjb2xvcj0iI2ZmZmZmZiI+DQoNCiAgICAgICAgPGJyPg0KDQogICAgICAg
IDx0YWJsZSB3aWR0aD0iOTUlIiBhbGlnbj0iY2VudGVyIiBjZWxsc3BhY2lu
Zz0iMCIgY2VsbHBhZGRpbmc9IjEiIGJvcmRlcj0iMCI+DQogICAgICAgIDx0
Ym9keT4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUi
IGJnY29sb3I9IiNjY2NjY2MiIGFsaWduPSJjZW50ZXIiPg0KICAgICAgICA8
aW1nIHNyYz0iaW1hZ2VzL3N1aWNpZGUuZ2lmIiBib3JkZXI9IjAiPg0KICAg
ICAgICA8L3RkPjwvdHI+PC90Ym9keT48L3RhYmxlPg0KDQogICAgICAgIDwv
Ym9keT4NCiAgICAgICAgPC9odG1sPg0KICAgICAgICAiIiINCg0KICAgIGVs
aWYgY29uID09ICJhYm91dHVzIjoNCiAgICAgICAgY29udGVudCA9ICIiIg0K
ICAgICAgICA8aGVhZD48bGluayByZWw9InN0eWxlc2hlZXQiIHR5cGU9InRl
eHQvY3NzIiBocmVmPSJjc3MvZ2VuLmNzcyI+PG1ldGEgaHR0cC1lcXVpdj0i
Q29udGVudCIgY29udGVudD0idGV4dC9odG1sIj48L2hlYWQ+PGJvZHkgYmdj
b2xvcj0iI0U1RTVFNSI+PGJyPg0KICAgICAgICA8dGFibGUgd2lkdGg9Ijk1
JSIgYWxpZ249ImNlbnRlciIgY2VsbHNwYWNpbmc9IjEiIGNlbGxwYWRpbmc9
IjEiIGJvcmRlcj0iMCI+DQogICAgICAgIDx0Ym9keT4NCiAgICAgICAgPHRy
Pg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUiIGJnY29sb3I9IiM2OTY5Njki
IGFsaWduPSJjZW50ZXIiPg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJkYW5h
LCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iI2ZmZmZmZiIgc2l6
ZT0iMiI+DQogICAgICAgIDxiPkFib3V0IFVzPC9iPg0KICAgICAgICA8L2Zv
bnQ+PC90ZD48L3RyPjwvdGJvZHk+PC90Ym9keT4NCg0KICAgICAgICA8dGFi
bGUgd2lkdGg9Ijk1JSIgYWxpZ249ImNlbnRlciIgY2VsbHNwYWNpbmc9IjEi
IGNlbGxwYWRkaW5nPSIxIiBib3JkZXI9IjAiPg0KICAgICAgICA8dGJvZHk+
DQogICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIxMDAlIiBiZ2Nv
bG9yPSIjY2NjY2NjIiBhbGlnbj0ibGVmdCI+DQogICAgICAgIDxmb250IGZh
Y2U9InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIj
Njk2OTY5IiBzaXplPSIyIj4NCiAgICAgICAgUy5CLk4gKFN1aWNpZGUgQnkg
TnVtYmVycykgaXMgYSBicmFuZCBzcGFua2luIG5ldyBwdW5rIGJhbmQgY29t
aW4gb3V0IG9mIFJlYWRpbmd0b24uIE5KLiBUaGUgYmFuZCBjb25zaXN0cyBv
ZiBKdWxpYWFuIEFyYXVqbyhWb2NhbHMpLCBTdGV2ZSBIaWNrcyhHdWl0YXIp
LCBKb2huIFpyaXBrbyhCYXNzKSwgYW5kIGxhc3QgYnV0IG5vdCBsZWFzdCBK
b3NoIFRheWxvcihEcnVtcykuIExpa2UgSSBzYWlkLCB3ZSBhcmUgbmV3LCBz
byB3ZSBuZWVkIGFsbCBvZiB0aGUgc3VwcG9ydCB3ZSBjYW4gZ2V0LiBJZiB5
b3UgYXJlIHJpY2gsIGdpdmUgdXMgbW9uZXkuIChKdXN0IEtpZGRpbikgV2Ug
d2lsbCBoYXZlIG1lcmNoIHNvb24gKHN0aWNrZXJzLCBwYXRjaGVzLCB3aGF0
ZXZlciB3ZSBjYW4gYWZmb3JkKS4gV2Ugd2lsbCBiZSBwcmFjdGljaW5nIGFs
bCBzdW1tZXIgYW5kIG9uY2Ugd2UgZ2V0IGdvb2QsIHdlIHdpbGwgdHJ5IHRv
IHJlY29yZC4gQWxzbywgb3VyIENPTFQgcnVsZXMhIE1UViBzdWtzISBbeF0g
bFhsICANCiAgICAgICAgPC9mb250PjwvdGQ+PC90cj48L3Rib2R5PjwvdGFi
bGU+DQoNCiAgICAgICAgPC9ib2R5Pg0KICAgICAgICA8L2h0bWw+PC9ib2R5
PjwvaHRtbD4NCiAgICAgICAgIiIiDQoNCiAgICBlbGlmIGNvbiA9PSAicGhv
dG9zIjoNCiAgICAgICAgY29udGVudCA9ICIiIg0KICAgICAgICA8aGVhZD48
bGluayByZWw9InN0eWxlc2hlZXQiIHR5cGU9InRleHQvY3NzIiBocmVmPSJj
c3MvZ2VuLmNzcyI+PG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudCIgY29udGVu
dD0idGV4dC9odG1sIj48L2hlYWQ+PGJvZHkgYmdjb2xvcj0iI0U1RTVFNSI+
PGJyPg0KICAgICAgICA8dGFibGUgd2lkdGg9Ijk1JSIgYWxpZ249ImNlbnRl
ciIgY2VsbHNwYWNpbmc9IjEiIGNlbGxwYWRpbmc9IjEiIGJvcmRlcj0iMCI+
DQogICAgICAgIDx0Ym9keT4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQg
d2lkdGg9IjEwMCUiIGJnY29sb3I9IiM2OTY5NjkiIGFsaWduPSJjZW50ZXIi
Pg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMg
bmV3IHJvbWFuIiBjb2xvcj0iI2ZmZmZmZiIgc2l6ZT0iMiI+DQogICAgICAg
IDxiPkNvbWluZyBTb29uPC9iPg0KICAgICAgICA8L2ZvbnQ+PC90ZD48L3Ry
PjwvdGJvZHk+PC90YWJsZT4NCiAgICAgICAgPC9ib2R5PjwvaHRtbD4NCiAg
ICAgICAgIiIiDQoNCiAgICBlbGlmIGNvbiA9PSAibHlyaWNzIjoNCiAgICAg
ICAgY29udGVudCA9ICIiIg0KICAgICAgICA8aGVhZD48bGluayByZWw9InN0
eWxlc2hlZXQiIHR5cGU9InRleHQvY3NzIiBocmVmPSJjc3MvZ2VuLmNzcyI+
PG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudCIgY29udGVudD0idGV4dC9odG1s
Ij48L2hlYWQ+PGJvZHkgYmdjb2xvcj0iI0U1RTVFNSI+PGJyPg0KICAgICAg
ICA8dGFibGUgd2lkdGg9Ijk1JSIgYWxpZ249ImNlbnRlciIgY2VsbHNwYWNp
bmc9IjEiIGNlbGxwYWRpbmc9IjEiIGJvcmRlcj0iMCI+DQogICAgICAgIDx0
Ym9keT4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUi
IGJnY29sb3I9IiM2OTY5NjkiIGFsaWduPSJjZW50ZXIiPg0KICAgICAgICA8
Zm9udCBmYWNlPSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBj
b2xvcj0iI2ZmZmZmZiIgc2l6ZT0iMiI+DQogICAgICAgIDxiPkx5cmljczwv
Yj4NCiAgICAgICAgPC9mb250PjwvdGQ+PC90cj4NCiAgICAgICAgPHRyPg0K
ICAgICAgICA8dGQgd2lkdGg9IjEwMCUiIGJnY29sb3I9IiM2OTY5NjkiIGFs
aWduPSJjZW50ZXIiPg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJkYW5hLCBh
cmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iI2ZmZmZmZiIgc2l6ZT0i
MiI+DQogICAgICAgIDxiPiJBbmQgdSBrbm93IHd1dCI8L2I+DQogICAgICAg
IDwvZm9udD48L3RkPjwvdHI+PC90Ym9keT48L3Rib2R5Pg0KDQogICAgICAg
IDx0YWJsZSB3aWR0aD0iOTUlIiBhbGlnbj0iY2VudGVyIiBjZWxsc3BhY2lu
Zz0iMSIgY2VsbHBhZGRpbmc9IjEiIGJvcmRlcj0iMCI+DQogICAgICAgIDx0
Ym9keT4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUi
IGJnY29sb3I9IiNjY2NjY2MiIGFsaWduPSJsZWZ0Ij4NCiAgICAgICAgPGZv
bnQgZmFjZT0idmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29s
b3I9IiM2OTY5NjkiIHNpemU9IjIiPg0KICAgICAgICBUaGV5IHNhaWQgSSB3
YXMgYSBzcG9pbGVkIGJyYXQgYW5kIHRoYXQgSSANCiAgICAgICAgZ290IGV2
ZXJ5IHRoaW5nIHRoYXQgSSB3YW50ZWQgYnV0IHUga25vdyANCiAgICAgICAg
d3V0IHNjcmV3IHUgY2F1c2UgSSBnb3Qgbm90aGluZyB0aGF0IEkgd2FudGVk
IA0KICAgICAgICBhbmQgeWVzIGFsbCBiZWNhdXNlIG9mIHUgLiB1IHBvbWlz
ZSBtZSAxIHRoaW5nIA0KICAgICAgICBhbmQgZG8gYW5vdGhlciBhbmQgdSBu
byB3dXQgaXQgZioqKmluIHBpc3NlcyANCiAgICAgICAgbWUgb2ZmLiBBbmQg
dSBubyB3dXQgdSBkb24ndCBjYXJlIGNhdXNlIHUgDQogICAgICAgIGhhdmUg
dGhpcyBib3kgYnV0IHVyIG9ubHkgZnJpZW5kcyAqcmlnaHQqIA0KICAgICAg
ICB3ZWxsIGFsbCBJIGdvdCB0byBzYXkgYWJvdXQgdGhhdCBpcyBidWxsIHMq
KiogDQogICAgICAgIGJlY2F1c2UgdGhpcyBoYXMgYmVlbiB0aGUgd29yc3Qg
ZGF5IG9mIG15IGxpZmUsIA0KICAgICAgICB5ZXMgaXQgaXMgYW5kIGltIGZl
dCB1cCEhISB5ZXMgSSBhbSBhbmQgaW0geW91bmcgDQogICAgICAgIEkgc2hv
dWxkbid0IGhhdmUgdG8gZGVhbCB3aXRoIGl0IGxpa2UgYSBkZWNrIG9mIA0K
ICAgICAgICBjYXJkcyEhISBObyEhIFRoZXkgc2FpZCBJIHdhcyBhIHNwb2ls
ZWQgYnJhdCANCiAgICAgICAgYW5kIHRoYXQgSSBnb3QgZXZlcnkgdGhpbmcg
dGhhdCBJIHdhbnRlZCBidXQgdSANCiAgICAgICAga25vdyB3dXQgc2NyZXcg
dSBjYXVzZSBJIGdvdCBub3RoaW5nIHRoYXQgSSANCiAgICAgICAgd2FudGVk
IGFuZCB5ZXMgYWxsIGJlY2F1c2Ugb2YgdSBhbGwgYmVjYXVzZSBvZiANCiAg
ICAgICAgdSEhLi4uLiBhbGwgdGhpcyBhbmdlciBJIGdvdCBvdXQgZmVsdCBz
byBnb29kIHllcyBpdCANCiAgICAgICAgZGlkIGJlY2F1c2UgdSBrbm93IHd1
dCBpdCByZWFsbHkgaHVydCBpbnNpZGUgYjQuIA0KICAgICAgICA8L2ZvbnQ+
PC90ZD48L3RyPjwvdGJvZHk+PC90YWJsZT4NCg0KICAgICAgICA8L2JvZHk+
DQogICAgICAgIDwvaHRtbD48L2JvZHk+PC9odG1sPg0KICAgICAgICAiIiIN
Cg0KICAgIGVsaWYgY29uID09ICJiaW9zIjoNCiAgICAgICAgY29udGVudCA9
ICIiIg0KICAgICAgICA8aGVhZD48bGluayByZWw9InN0eWxlc2hlZXQiIHR5
cGU9InRleHQvY3NzIiBocmVmPSJjc3MvZ2VuLmNzcyI+PG1ldGEgaHR0cC1l
cXVpdj0iQ29udGVudCIgY29udGVudD0idGV4dC9odG1sIj48L2hlYWQ+PGJv
ZHkgYmdjb2xvcj0iI0U1RTVFNSI+PGJyPg0KDQogICAgICAgIDx0YWJsZSB3
aWR0aD0iOTUlIiBjZWxsc3BhY2luZz0iMSIgY2VsbHBhZGRpbmc9IjEiIGFs
aWduPSJjZW50ZXIiIGJvcmRlcj0iMCI+DQogICAgICAgIDx0Ym9keT4NCiAg
ICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUiIGJnY29sb3I9
IiM2OTY5NjkiIGFsaWduPSJjZW50ZXIiPg0KICAgICAgICA8Zm9udCBmYWNl
PSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iI2Zm
ZmZmZiIgc2l6ZT0iMiI+DQogICAgICAgIDxiPkJpb3M8L2I+DQogICAgICAg
IDwvZm9udD48L3RkPjwvdHI+PC90Ym9keT48L3RhYmxlPg0KDQogICAgICAg
IDx0YWJsZSB3aWR0aD0iOTUlIiBjZWxsc3BhY2luZz0iMSIgY2VsbHBhZGRp
bmc9IjEiIGFsaWduPSJjZW50ZXIiIGJvcmRlcj0iMCI+DQogICAgICAgIDx0
Ym9keT4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjIwJSIg
Ymdjb2xvcj0iI2U1ZTVlNSI+DQogICAgICAgIDwvdGQ+DQogICAgICAgIDx0
ZCB3aWR0aD0iNDAlIiBiZ2NvbG9yPSIjNjk2OTY5IiBhbGlnbj0iY2VudGVy
Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVyZGFuYSwgYXJpYWwsIHRpbWVz
IG5ldyByb21hbiIgY29sb3I9IiNmZmZmZmYiIHNpemU9IjIiPg0KICAgICAg
ICA8Yj5KdWxpYWFuIEFyYXVqbzwvYj4NCiAgICAgICAgPC9mb250PjwvdGQ+
DQogICAgICAgIDx0ZCB3aWR0aD0iNDAlIiBiZ2NvbG9yPSIjNjk2OTY5IiBh
bGlnbj0iY2VudGVyIj4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVyZGFuYSwg
YXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNmZmZmZmYiIHNpemU9
IjIiPg0KICAgICAgICA8Yj5Kb2huIFpyaXBrbzwvYj4NCiAgICAgICAgPC9m
b250PjwvdGQ+PC90cj48L3Rib2R5PjwvdGFibGU+DQoNCiAgICAgICAgPHRh
YmxlIHdpZHRoPSI5NSUiIGNlbGxzcGFjaW5nPSIxIiBjZWxscGFkZGluZz0i
MCIgYWxpZ249ImNlbnRlciIgc2l6ZT0iMiI+DQogICAgICAgIDx0Ym9keT4N
CiAgICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjIwJSIgYmdjb2xv
cj0iIzY5Njk2OSIgYWxpZ249ImxlZnQiPg0KICAgICAgICA8Zm9udCBmYWNl
PSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iI2Zm
ZmZmZiIgc2l6ZT0iMiI+DQogICAgICAgIEJpcnRoZGF0ZQ0KICAgICAgICA8
L2ZvbnQ+PC90ZD4NCiAgICAgICAgPHRkIHdpZHRoPSI0MCUiIGJnY29sb3I9
IiNjY2NjY2MiIGFsaWduPSJsZWZ0Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0i
dmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiM2OTY5
NjkiIHNpemU9IjIiPg0KICAgICAgICAzLzI2LzAyDQogICAgICAgIDwvZm9u
dD48L3RkPg0KICAgICAgICA8dGQgd2lkdGg9IjQwJSIgYmdjb2xvcj0iI2Nj
Y2NjYyIgYWxpZ249ImxlZnQiPg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJk
YW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iIzY5Njk2OSIg
c2l6ZT0iMiI+DQogICAgICAgIDEvMjAvODkNCiAgICAgICAgPC9mb250Pjwv
dGQ+PC90cj48L3Rib2R5PjwvdGFibGU+DQoNCiAgICAgICAgPHRhYmxlIHdp
ZHRoPSI5NSUiIGNlbGxzcGFjaW5nPSIxIiBjZWxscGFkZGluZz0iMCIgYWxp
Z249ImNlbnRlciIgc2l6ZT0iMiI+DQogICAgICAgIDx0Ym9keT4NCiAgICAg
ICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjIwJSIgYmdjb2xvcj0iIzY5
Njk2OSIgYWxpZ249ImxlZnQiPg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJk
YW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iI2ZmZmZmZiIg
c2l6ZT0iMiI+DQogICAgICAgIEZ1bmN0aW9uIGluIEJhbmQNCiAgICAgICAg
PC9mb250PjwvdGQ+DQogICAgICAgIDx0ZCB3aWR0aD0iNDAlIiBiZ2NvbG9y
PSIjY2NjY2NjIiBhbGlnbj0ibGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9
InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjNjk2
OTY5IiBzaXplPSIyIj4NCiAgICAgICAgTGVhZCBWb2NhbHMNCiAgICAgICAg
PC9mb250PjwvdGQ+DQogICAgICAgIDx0ZCB3aWR0aD0iNDAlIiBiZ2NvbG9y
PSIjY2NjY2NjIiBhbGlnbj0ibGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9
InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjNjk2
OTY5IiBzaXplPSIyIj4NCiAgICAgICAgQmFzcw0KICAgICAgICA8L2ZvbnQ+
PC90ZD48L3RyPjwvdGJvZHk+PC90YWJsZT4NCg0KICAgICAgICA8dGFibGUg
d2lkdGg9Ijk1JSIgY2VsbHNwYWNpbmc9IjEiIGNlbGxwYWRkaW5nPSIwIiBh
bGlnbj0iY2VudGVyIiBzaXplPSIyIj4NCiAgICAgICAgPHRib2R5Pg0KICAg
ICAgICA8dHI+DQogICAgICAgIDx0ZCB3aWR0aD0iMjAlIiBiZ2NvbG9yPSIj
Njk2OTY5IiBhbGlnbj0ibGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9InZl
cmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjZmZmZmZm
IiBzaXplPSIyIj4NCiAgICAgICAgRXF1aXBtZW50DQogICAgICAgIDwvZm9u
dD48L3RkPg0KICAgICAgICA8dGQgd2lkdGg9IjQwJSIgYmdjb2xvcj0iI2Nj
Y2NjYyIgYWxpZ249ImxlZnQiPg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJk
YW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iIzY5Njk2OSIg
c2l6ZT0iMiI+DQogICAgICAgIE5vdGhpbiBidXQgdm9pY2UNCiAgICAgICAg
PC9mb250PjwvdGQ+DQogICAgICAgIDx0ZCB3aWR0aD0iNDAlIiBiZ2NvbG9y
PSIjY2NjY2NjIiBhbGlnbj0ibGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9
InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjNjk2
OTY5IiBzaXplPSIyIj4NCiAgICAgICAgU3F1aWVyIEFmZmluaXR5IFAtQmFz
cywgSGFydGtlIEItMzAgQW1wDQogICAgICAgIDwvZm9udD48L3RkPjwvdHI+
PC90Ym9keT48L3RhYmxlPg0KDQogICAgICAgIDx0YWJsZSB3aWR0aD0iOTUl
IiBjZWxsc3BhY2luZz0iMSIgY2VsbHBhZGRpbmc9IjAiIGFsaWduPSJjZW50
ZXIiIHNpemU9IjIiPg0KICAgICAgICA8dGJvZHk+DQogICAgICAgIDx0cj4N
CiAgICAgICAgPHRkIHdpZHRoPSIyMCUiIGJnY29sb3I9IiM2OTY5NjkiIGFs
aWduPSJsZWZ0Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVyZGFuYSwgYXJp
YWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNmZmZmZmYiIHNpemU9IjIi
Pg0KICAgICAgICBIb2JiaWVzDQogICAgICAgIDwvZm9udD48L3RkPg0KICAg
ICAgICA8dGQgd2lkdGg9IjQwJSIgYmdjb2xvcj0iI2NjY2NjYyIgYWxpZ249
ImxlZnQiPg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJkYW5hLCBhcmlhbCwg
dGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iIzY5Njk2OSIgc2l6ZT0iMiI+DQog
ICAgICAgIHNrYXRlYm9hcmRpbmcsIGdvaW5nIHRvIHB1bmsgc2hvd3MNCiAg
ICAgICAgPC9mb250PjwvdGQ+DQogICAgICAgIDx0ZCB3aWR0aD0iNDAlIiBi
Z2NvbG9yPSIjY2NjY2NjIiBhbGlnbj0ibGVmdCI+DQogICAgICAgIDxmb250
IGZhY2U9InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9y
PSIjNjk2OTY5IiBzaXplPSIyIj4NCiAgICAgICAgZ29pbmcgdG8gcHVuayBz
aG93cywgYmFzcywgc29jY2VyDQogICAgICAgIDwvZm9udD48L3RkPjwvdHI+
PC90Ym9keT48L3RhYmxlPg0KDQogICAgICAgIDx0YWJsZSB3aWR0aD0iOTUl
IiBjZWxsc3BhY2luZz0iMSIgY2VsbHBhZGRpbmc9IjAiIGFsaWduPSJjZW50
ZXIiIHNpemU9IjIiPg0KICAgICAgICA8dGJvZHk+DQogICAgICAgIDx0cj4N
CiAgICAgICAgPHRkIHdpZHRoPSIyMCUiIGJnY29sb3I9IiM2OTY5NjkiIGFs
aWduPSJsZWZ0Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVyZGFuYSwgYXJp
YWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNmZmZmZmYiIHNpemU9IjIi
Pg0KICAgICAgICBGYXZlIFR5cGUgb2YgTXVzaWMNCiAgICAgICAgPC9mb250
PjwvdGQ+DQogICAgICAgIDx0ZCB3aWR0aD0iNDAlIiBiZ2NvbG9yPSIjY2Nj
Y2NjIiBhbGlnbj0ibGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRh
bmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjNjk2OTY5IiBz
aXplPSIyIj4NCiAgICAgICAgUHVuaw0KICAgICAgICA8L2ZvbnQ+PC90ZD4N
CiAgICAgICAgPHRkIHdpZHRoPSI0MCUiIGJnY29sb3I9IiNjY2NjY2MiIGFs
aWduPSJsZWZ0Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVyZGFuYSwgYXJp
YWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiM2OTY5NjkiIHNpemU9IjIi
Pg0KICAgICAgICBQVU5LLi4uZHVoDQogICAgICAgIDwvZm9udD48L3RkPjwv
dHI+PC90Ym9keT48L3RhYmxlPg0KDQogICAgICAgIDx0YWJsZSB3aWR0aD0i
OTUlIiBjZWxsc3BhY2luZz0iMSIgY2VsbHBhZGRpbmc9IjAiIGFsaWduPSJj
ZW50ZXIiIHNpemU9IjIiPg0KICAgICAgICA8dGJvZHk+DQogICAgICAgIDx0
cj4NCiAgICAgICAgPHRkIHdpZHRoPSIyMCUiIGJnY29sb3I9IiM2OTY5Njki
IGFsaWduPSJsZWZ0Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVyZGFuYSwg
YXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNmZmZmZmYiIHNpemU9
IjIiPg0KICAgICAgICBGYXZlIEJhbmRzDQogICAgICAgIDwvZm9udD48L3Rk
Pg0KICAgICAgICA8dGQgd2lkdGg9IjQwJSIgYmdjb2xvcj0iI2NjY2NjYyIg
YWxpZ249ImxlZnQiPg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJkYW5hLCBh
cmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iIzY5Njk2OSIgc2l6ZT0i
MiI+DQogICAgICAgIE14UHgsIE1lc3QsIEJvdW5jaW5nIFNvdWxzLCBMZXNz
IFRoYW4gSmFrZQ0KICAgICAgICA8L2ZvbnQ+PC90ZD4NCiAgICAgICAgPHRk
IHdpZHRoPSI0MCUiIGJnY29sb3I9IiNjY2NjY2MiIGFsaWduPSJsZWZ0Ij4N
CiAgICAgICAgPGZvbnQgZmFjZT0idmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5l
dyByb21hbiIgY29sb3I9IiM2OTY5NjkiIHNpemU9IjIiPg0KICAgICAgICBC
b3VuY2luZyBTb3VscywgUmFuY2lkLCBCaWdXaWcsIENhdGNoIDIyDQogICAg
ICAgIDwvZm9udD48L3RkPjwvdHI+PC90Ym9keT48L3RhYmxlPg0KDQogICAg
ICAgIDx0YWJsZSB3aWR0aD0iOTUlIiBjZWxsc3BhY2luZz0iMSIgY2VsbHBh
ZGRpbmc9IjAiIGFsaWduPSJjZW50ZXIiIHNpemU9IjIiPg0KICAgICAgICA8
dGJvZHk+DQogICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIyMCUi
IGJnY29sb3I9IiM2OTY5NjkiIGFsaWduPSJsZWZ0Ij4NCiAgICAgICAgPGZv
bnQgZmFjZT0idmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29s
b3I9IiNmZmZmZmYiIHNpemU9IjIiPg0KICAgICAgICBRdW90ZQ0KICAgICAg
ICA8L2ZvbnQ+PC90ZD4NCiAgICAgICAgPHRkIHdpZHRoPSI0MCUiIGJnY29s
b3I9IiNjY2NjY2MiIGFsaWduPSJsZWZ0Ij4NCiAgICAgICAgPGZvbnQgZmFj
ZT0idmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiM2
OTY5NjkiIHNpemU9IjIiPg0KICAgICAgICAiWW91ciBtaW5kIGlzIGEgZ29v
ZCB0aGluZyB0byBsb3NlLiINCiAgICAgICAgPC9mb250PjwvdGQ+DQogICAg
ICAgIDx0ZCB3aWR0aD0iNDAlIiBiZ2NvbG9yPSIjY2NjY2NjIiBhbGlnbj0i
bGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFyaWFsLCB0
aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjNjk2OTY5IiBzaXplPSIyIj4NCiAg
ICAgICAgIkRvIG9yIERpZSEiIC1Ecm9wa2ljayBNdXJwaHkncw0KICAgICAg
ICA8L2ZvbnQ+PC90ZD48L3RyPjwvdGJvZHk+PC90YWJsZT4NCg0KICAgICAg
ICA8dGFibGUgd2lkdGg9Ijk1JSIgY2VsbHNwYWNpbmc9IjEiIGNlbGxwYWRk
aW5nPSIxIiBhbGlnbj0iY2VudGVyIiBib3JkZXI9IjAiPg0KICAgICAgICA8
dGJvZHk+DQogICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIyMCUi
IGJnY29sb3I9IiNlNWU1ZTUiPg0KICAgICAgICA8L3RkPg0KICAgICAgICA8
dGQgd2lkdGg9IjQwJSIgYmdjb2xvcj0iIzY5Njk2OSIgYWxpZ249ImNlbnRl
ciI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFyaWFsLCB0aW1l
cyBuZXcgcm9tYW4iIGNvbG9yPSIjZmZmZmZmIiBzaXplPSIyIj4NCiAgICAg
ICAgPGI+U3RldmUgSGlja3M8L2I+DQogICAgICAgIDwvZm9udD48L3RkPg0K
ICAgICAgICA8dGQgd2lkdGg9IjQwJSIgYmdjb2xvcj0iIzY5Njk2OSIgYWxp
Z249ImNlbnRlciI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFy
aWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjZmZmZmZmIiBzaXplPSIy
Ij4NCiAgICAgICAgPGI+Sm9zaCBUYXlsb3I8L2I+DQogICAgICAgIDwvZm9u
dD48L3RkPjwvdHI+PC90Ym9keT48L3RhYmxlPg0KDQogICAgICAgIDx0YWJs
ZSB3aWR0aD0iOTUlIiBjZWxsc3BhY2luZz0iMSIgY2VsbHBhZGRpbmc9IjAi
IGFsaWduPSJjZW50ZXIiIHNpemU9IjIiPg0KICAgICAgICA8dGJvZHk+DQog
ICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIyMCUiIGJnY29sb3I9
IiM2OTY5NjkiIGFsaWduPSJsZWZ0Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0i
dmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiNmZmZm
ZmYiIHNpemU9IjIiPg0KICAgICAgICBCaXJ0aGRheQ0KICAgICAgICA8L2Zv
bnQ+PC90ZD4NCiAgICAgICAgPHRkIHdpZHRoPSI0MCUiIGJnY29sb3I9IiNj
Y2NjY2MiIGFsaWduPSJsZWZ0Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVy
ZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9IiM2OTY5Njki
IHNpemU9IjIiPg0KICAgICAgICAtDQogICAgICAgIDwvZm9udD48L3RkPg0K
ICAgICAgICA8dGQgd2lkdGg9IjQwJSIgYmdjb2xvcj0iI2NjY2NjYyIgYWxp
Z249ImxlZnQiPg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJkYW5hLCBhcmlh
bCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iIzY5Njk2OSIgc2l6ZT0iMiI+
DQogICAgICAgIC0NCiAgICAgICAgPC9mb250PjwvdGQ+PC90cj48L3Rib2R5
PjwvdGFibGU+DQoNCiAgICAgICAgPHRhYmxlIHdpZHRoPSI5NSUiIGNlbGxz
cGFjaW5nPSIxIiBjZWxscGFkZGluZz0iMCIgYWxpZ249ImNlbnRlciIgc2l6
ZT0iMiI+DQogICAgICAgIDx0Ym9keT4NCiAgICAgICAgPHRyPg0KICAgICAg
ICA8dGQgd2lkdGg9IjIwJSIgYmdjb2xvcj0iIzY5Njk2OSIgYWxpZ249Imxl
ZnQiPg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJkYW5hLCBhcmlhbCwgdGlt
ZXMgbmV3IHJvbWFuIiBjb2xvcj0iI2ZmZmZmZiIgc2l6ZT0iMiI+DQogICAg
ICAgIEZ1bmN0aW9uIGluIEJhbmQNCiAgICAgICAgPC9mb250PjwvdGQ+DQog
ICAgICAgIDx0ZCB3aWR0aD0iNDAlIiBiZ2NvbG9yPSIjY2NjY2NjIiBhbGln
bj0ibGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFyaWFs
LCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjNjk2OTY5IiBzaXplPSIyIj4N
CiAgICAgICAgR3VpdGFyDQogICAgICAgIDwvZm9udD48L3RkPg0KICAgICAg
ICA8dGQgd2lkdGg9IjQwJSIgYmdjb2xvcj0iI2NjY2NjYyIgYWxpZ249Imxl
ZnQiPg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJkYW5hLCBhcmlhbCwgdGlt
ZXMgbmV3IHJvbWFuIiBjb2xvcj0iIzY5Njk2OSIgc2l6ZT0iMiI+DQogICAg
ICAgIERydW1zDQogICAgICAgIDwvZm9udD48L3RkPjwvdHI+PC90Ym9keT48
L3RhYmxlPg0KDQogICAgICAgIDx0YWJsZSB3aWR0aD0iOTUlIiBjZWxsc3Bh
Y2luZz0iMSIgY2VsbHBhZGRpbmc9IjAiIGFsaWduPSJjZW50ZXIiIHNpemU9
IjIiPg0KICAgICAgICA8dGJvZHk+DQogICAgICAgIDx0cj4NCiAgICAgICAg
PHRkIHdpZHRoPSIyMCUiIGJnY29sb3I9IiM2OTY5NjkiIGFsaWduPSJsZWZ0
Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVyZGFuYSwgYXJpYWwsIHRpbWVz
IG5ldyByb21hbiIgY29sb3I9IiNmZmZmZmYiIHNpemU9IjIiPg0KICAgICAg
ICBFcXVpcG1lbnQNCiAgICAgICAgPC9mb250PjwvdGQ+DQogICAgICAgIDx0
ZCB3aWR0aD0iNDAlIiBiZ2NvbG9yPSIjY2NjY2NjIiBhbGlnbj0ibGVmdCI+
DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBu
ZXcgcm9tYW4iIGNvbG9yPSIjNjk2OTY5IiBzaXplPSIyIj4NCiAgICAgICAg
LQ0KICAgICAgICA8L2ZvbnQ+PC90ZD4NCiAgICAgICAgPHRkIHdpZHRoPSI0
MCUiIGJnY29sb3I9IiNjY2NjY2MiIGFsaWduPSJsZWZ0Ij4NCiAgICAgICAg
PGZvbnQgZmFjZT0idmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIg
Y29sb3I9IiM2OTY5NjkiIHNpemU9IjIiPg0KICAgICAgICAtDQogICAgICAg
IDwvZm9udD48L3RkPjwvdHI+PC90Ym9keT48L3RhYmxlPg0KDQogICAgICAg
IDx0YWJsZSB3aWR0aD0iOTUlIiBjZWxsc3BhY2luZz0iMSIgY2VsbHBhZGRp
bmc9IjAiIGFsaWduPSJjZW50ZXIiIHNpemU9IjIiPg0KICAgICAgICA8dGJv
ZHk+DQogICAgICAgIDx0cj4NCiAgICAgICAgPHRkIHdpZHRoPSIyMCUiIGJn
Y29sb3I9IiM2OTY5NjkiIGFsaWduPSJsZWZ0Ij4NCiAgICAgICAgPGZvbnQg
ZmFjZT0idmVyZGFuYSwgYXJpYWwsIHRpbWVzIG5ldyByb21hbiIgY29sb3I9
IiNmZmZmZmYiIHNpemU9IjIiPg0KICAgICAgICBIb2JiaWVzDQogICAgICAg
IDwvZm9udD48L3RkPg0KICAgICAgICA8dGQgd2lkdGg9IjQwJSIgYmdjb2xv
cj0iI2NjY2NjYyIgYWxpZ249ImxlZnQiPg0KICAgICAgICA8Zm9udCBmYWNl
PSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iIzY5
Njk2OSIgc2l6ZT0iMiI+DQogICAgICAgIC0NCiAgICAgICAgPC9mb250Pjwv
dGQ+DQogICAgICAgIDx0ZCB3aWR0aD0iNDAlIiBiZ2NvbG9yPSIjY2NjY2Nj
IiBhbGlnbj0ibGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEs
IGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjNjk2OTY5IiBzaXpl
PSIyIj4NCiAgICAgICAgLQ0KICAgICAgICA8L2ZvbnQ+PC90ZD48L3RyPjwv
dGJvZHk+PC90YWJsZT4NCg0KICAgICAgICA8dGFibGUgd2lkdGg9Ijk1JSIg
Y2VsbHNwYWNpbmc9IjEiIGNlbGxwYWRkaW5nPSIwIiBhbGlnbj0iY2VudGVy
IiBzaXplPSIyIj4NCiAgICAgICAgPHRib2R5Pg0KICAgICAgICA8dHI+DQog
ICAgICAgIDx0ZCB3aWR0aD0iMjAlIiBiZ2NvbG9yPSIjNjk2OTY5IiBhbGln
bj0ibGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFyaWFs
LCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjZmZmZmZmIiBzaXplPSIyIj4N
CiAgICAgICAgRmF2ZSBUeXBlIG9mIE11c2ljDQogICAgICAgIDwvZm9udD48
L3RkPg0KICAgICAgICA8dGQgd2lkdGg9IjQwJSIgYmdjb2xvcj0iI2NjY2Nj
YyIgYWxpZ249ImxlZnQiPg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJkYW5h
LCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iIzY5Njk2OSIgc2l6
ZT0iMiI+DQogICAgICAgIFB1bmsNCiAgICAgICAgPC9mb250PjwvdGQ+DQog
ICAgICAgIDx0ZCB3aWR0aD0iNDAlIiBiZ2NvbG9yPSIjY2NjY2NjIiBhbGln
bj0ibGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFyaWFs
LCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjNjk2OTY5IiBzaXplPSIyIj4N
CiAgICAgICAgUHVuaw0KICAgICAgICA8L2ZvbnQ+PC90ZD48L3RyPjwvdGJv
ZHk+PC90YWJsZT4NCg0KICAgICAgICA8dGFibGUgd2lkdGg9Ijk1JSIgY2Vs
bHNwYWNpbmc9IjEiIGNlbGxwYWRkaW5nPSIwIiBhbGlnbj0iY2VudGVyIiBz
aXplPSIyIj4NCiAgICAgICAgPHRib2R5Pg0KICAgICAgICA8dHI+DQogICAg
ICAgIDx0ZCB3aWR0aD0iMjAlIiBiZ2NvbG9yPSIjNjk2OTY5IiBhbGlnbj0i
bGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFyaWFsLCB0
aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjZmZmZmZmIiBzaXplPSIyIj4NCiAg
ICAgICAgRmF2ZSBCYW5kcw0KICAgICAgICA8L2ZvbnQ+PC90ZD4NCiAgICAg
ICAgPHRkIHdpZHRoPSI0MCUiIGJnY29sb3I9IiNjY2NjY2MiIGFsaWduPSJs
ZWZ0Ij4NCiAgICAgICAgPGZvbnQgZmFjZT0idmVyZGFuYSwgYXJpYWwsIHRp
bWVzIG5ldyByb21hbiIgY29sb3I9IiM2OTY5NjkiIHNpemU9IjIiPg0KICAg
ICAgICBCb3VuY2luZyBTb3VscywgUmFtb25lcywgQmlnV2lnLCBBRkkNCiAg
ICAgICAgPC9mb250PjwvdGQ+DQogICAgICAgIDx0ZCB3aWR0aD0iNDAlIiBi
Z2NvbG9yPSIjY2NjY2NjIiBhbGlnbj0ibGVmdCI+DQogICAgICAgIDxmb250
IGZhY2U9InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9y
PSIjNjk2OTY5IiBzaXplPSIyIj4NCiAgICAgICAgQm91bmNpbmcgU291bHMN
CiAgICAgICAgPC9mb250PjwvdGQ+PC90cj48L3Rib2R5PjwvdGFibGU+DQoN
CiAgICAgICAgPHRhYmxlIHdpZHRoPSI5NSUiIGNlbGxzcGFjaW5nPSIxIiBj
ZWxscGFkZGluZz0iMCIgYWxpZ249ImNlbnRlciIgc2l6ZT0iMiI+DQogICAg
ICAgIDx0Ym9keT4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9
IjIwJSIgYmdjb2xvcj0iIzY5Njk2OSIgYWxpZ249ImxlZnQiPg0KICAgICAg
ICA8Zm9udCBmYWNlPSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFu
IiBjb2xvcj0iI2ZmZmZmZiIgc2l6ZT0iMiI+DQogICAgICAgIFF1b3RlDQog
ICAgICAgIDwvZm9udD48L3RkPg0KICAgICAgICA8dGQgd2lkdGg9IjQwJSIg
Ymdjb2xvcj0iI2NjY2NjYyIgYWxpZ249ImxlZnQiPg0KICAgICAgICA8Zm9u
dCBmYWNlPSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xv
cj0iIzY5Njk2OSIgc2l6ZT0iMiI+DQogICAgICAgIC0NCiAgICAgICAgPC9m
b250PjwvdGQ+DQogICAgICAgIDx0ZCB3aWR0aD0iNDAlIiBiZ2NvbG9yPSIj
Y2NjY2NjIiBhbGlnbj0ibGVmdCI+DQogICAgICAgIDxmb250IGZhY2U9InZl
cmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjNjk2OTY5
IiBzaXplPSIyIj4NCiAgICAgICAgLQ0KICAgICAgICA8L2ZvbnQ+PC90ZD48
L3RyPjwvdGJvZHk+PC90YWJsZT4NCg0KICAgICAgICA8L2JvZHk+DQogICAg
ICAgIDwvaHRtbD48L2JvZHk+PC9odG1sPg0KICAgICAgICAiIiINCg0KICAg
IGVsaWYgY29uID09ICJjaGF0IjoNCiAgICAgICAgY29udGVudCA9ICIiIg0K
ICAgICAgICAiIiINCg0KICAgIGVsaWYgY29uID09ICJjb250YWN0dXMiOg0K
ICAgICAgICBjb250ZW50ID0gIiIiDQogICAgICAgIDxoZWFkPjxsaW5rIHJl
bD0ic3R5bGVzaGVldCIgdHlwZT0idGV4dC9jc3MiIGhyZWY9ImNzcy9nZW4u
Y3NzIj48bWV0YSBodHRwLWVxdWl2PSJDb250ZW50IiBjb250ZW50PSJ0ZXh0
L2h0bWwiPg0KICAgICAgICA8L2hlYWQ+DQogICAgICAgIDxib2R5IGJnY29s
b3I9IiNFNUU1RTUiPg0KICAgICAgICA8YnI+DQogICAgICAgIDx0YWJsZSB3
aWR0aD0iOTUlIiBhbGlnbj0iY2VudGVyIiBjZWxsc3BhY2luZz0iMSIgY2Vs
bHBhZGRpbmc9IjEiIGJvcmRlcj0iMCI+DQogICAgICAgIDx0Ym9keT4NCiAg
ICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjEwMCUiIGJnY29sb3I9
IiM2OTY5NjkiIGFsaWduPSJjZW50ZXIiPg0KICAgICAgICA8Zm9udCBmYWNl
PSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0iI2Zm
ZmZmZiIgc2l6ZT0iMiI+DQogICAgICAgIDxiPkNvbnRhY3QgVXM8L2I+DQog
ICAgICAgIDwvdGQ+PC90cj48L3Rib2R5PjwvdGFibGU+DQogICAgICAgIDx0
YWJsZSB3aWR0aD0iOTUlIiBhbGlnbj0iY2VudGVyIiBjZWxsc3BhY2luZz0i
MSIgY2VsbHBhZGRpbmc9IjEiIGJvcmRlcj0iMCI+DQogICAgICAgIDx0Ym9k
eT4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjUwJSIgYmdj
b2xvcj0iIzY5Njk2OSIgYWxpZ249ImNlbnRlciI+DQogICAgICAgIDxmb250
IGZhY2U9InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9y
PSIjZmZmZmZmIiBzaXplPSIyIj4NCiAgICAgICAgPGI+YmFuZCBtZW1iZXIu
Li48L2I+DQogICAgICAgIDwvZm9udD48L3RkPg0KICAgICAgICA8dGQgd2lk
dGg9IjUwJSIgYmdjb2xvcj0iIzY5Njk2OSIgYWxpZ249ImNlbnRlciI+DQog
ICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcg
cm9tYW4iIGNvbG9yPSIjZmZmZmZmIiBzaXplPSIyIj4NCiAgICAgICAgPGI+
YW5kIHRoZWlyIGUtbWFpbCBhZGRyZXNzPC9iPg0KICAgICAgICA8L2ZvbnQ+
PC90ZD48L3RyPg0KICAgICAgICA8dHI+DQogICAgICAgIDx0ZCB3aWR0aD0i
NTAlIiBhbGlnbj0ibGVmdCIgYmdjb2xvcj0iI2NjY2NjYyI+DQogICAgICAg
IDxmb250IGZhY2U9InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9tYW4i
IGNvbG9yPSIjNjk2OTY5IiBzaXplPSIyIj4NCiAgICAgICAgSnVsaWFhbiBB
cmF1am8NCiAgICAgICAgPC9mb250PjwvdGQ+DQogICAgICAgIDx0ZCB3aWR0
aD0iNTAlIiBhbGlnbj0ibGVmdCIgYmdjb2xvcj0iI2NjY2NjYyI+DQogICAg
ICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFyaWFsLCB0aW1lcyBuZXcgcm9t
YW4iIGNvbG9yPSIjNjk2OTY5IiBzaXplPSIyIj4NCiAgICAgICAgPGEgaHJl
Zj0ibWFpbHRvOmJteG9mYWRvd24xc2s4MkBhb2wuY29tIiBzdHlsZT0idGV4
dC1kZWNvcmF0aW9uOnVuZGVybGluZTsgY29sb3I6Njk2OTY5Ij5ibXhvZmFk
b3duMXNrODJAYW9sLmNvbTwvYT4NCiAgICAgICAgPC9mb250PjwvdGQ+PC90
cj4NCiAgICAgICAgPHRyPg0KICAgICAgICA8dGQgd2lkdGg9IjUwJSIgYWxp
Z249ImxlZnQiIGJnY29sb3I9IiNjY2NjY2MiPg0KICAgICAgICA8Zm9udCBm
YWNlPSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0i
IzY5Njk2OSIgc2l6ZT0iMiI+DQogICAgICAgIEpvaG4gWnJpcGtvDQogICAg
ICAgIDwvZm9udD48L3RkPg0KICAgICAgICA8dGQgd2lkdGg9IjUwJSIgYWxp
Z249ImxlZnQiIGJnY29sb3I9IiNjY2NjY2MiPg0KICAgICAgICA8Zm9udCBm
YWNlPSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMgbmV3IHJvbWFuIiBjb2xvcj0i
IzY5Njk2OSIgc2l6ZT0iMiI+DQogICAgICAgIDxhIGhyZWY9Im1haWx0bzpp
enJpcGtvOUBob3RtYWlsLmNvbSIgc3R5bGU9InRleHQtZGVjb3JhdGlvbjp1
bmRlcmxpbmU7IGNvbG9yOjY5Njk2OSI+aXpyaXBva285QGhvdG1haWwuY29t
PC9hPg0KICAgICAgICA8L2ZvbnQ+PC90ZD48L3RyPg0KICAgICAgICA8dHI+
DQogICAgICAgIDx0ZCB3aWR0aD0iNTAlIiBhbGlnbj0ibGVmdCIgYmdjb2xv
cj0iI2NjY2NjYyI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFy
aWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjNjk2OTY5IiBzaXplPSIy
Ij4NCiAgICAgICAgU3RldmUgSGlja3MNCiAgICAgICAgPC9mb250PjwvdGQ+
DQogICAgICAgIDx0ZCB3aWR0aD0iNTAlIiBhbGlnbj0ibGVmdCIgYmdjb2xv
cj0iI2NjY2NjYyI+DQogICAgICAgIDxmb250IGZhY2U9InZlcmRhbmEsIGFy
aWFsLCB0aW1lcyBuZXcgcm9tYW4iIGNvbG9yPSIjNjk2OTY5IiBzaXplPSIy
Ij4tPC9mb250PjwvdGQ+PC90cj4NCiAgICAgICAgPHRyPg0KICAgICAgICA8
dGQgd2lkdGg9IjUwJSIgYWxpZ249ImxlZnQiIGJnY29sb3I9IiNjY2NjY2Mi
Pg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMg
bmV3IHJvbWFuIiBjb2xvcj0iIzY5Njk2OSIgc2l6ZT0iMiI+DQogICAgICAg
IEpvc2ggVGF5bG9yDQogICAgICAgIDwvZm9udD48L3RkPg0KICAgICAgICA8
dGQgd2lkdGg9IjUwJSIgYWxpZ249ImxlZnQiIGJnY29sb3I9IiNjY2NjY2Mi
Pg0KICAgICAgICA8Zm9udCBmYWNlPSJ2ZXJkYW5hLCBhcmlhbCwgdGltZXMg
bmV3IHJvbWFuIiBjb2xvcj0iIzY5Njk2OSIgc2l6ZT0iMiI+LTwvZm9udD48
L3RkPjwvdHI+PC90Ym9keT48L3RhYmxlPg0KICAgICAgICA8L2JvZHk+PC9o
dG1sPg0KICAgICAgICAiIiINCg0KICAgIGVsaWYgY29uID09ICJjcmVkaXRz
IjoNCiAgICAgICAgY29udGVudCA9ICIiIg0KICAgICAgICAiIiINCg0KICAg
IGVsc2U6DQogICAgICAgIHByaW50ICJlcnJvcjogIGNvbnRlbnQgZmFpbGVk
XG4iDQoNCnByaW50ICIiIg0KPCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9X
M0MvL0RURCBIVE1MIDQuMSBUUkFOU0lUSU9OQUwvL0VOIj4NCjxIVE1MPg0K
DQolKGNvbnRlbnQpcyIiIiAlIHZhcnMoKQ0K

--_----------=_1027639943311120--



From dyoo@hkn.eecs.berkeley.edu  Fri Jul 26 00:48:45 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 25 Jul 2002 16:48:45 -0700 (PDT)
Subject: [Tutor] (no subject)
In-Reply-To: <20020725233223.C6CB66DACF@www.fastmail.fm>
Message-ID: <Pine.LNX.4.44.0207251645110.15914-100000@hkn.eecs.berkeley.edu>


On Thu, 25 Jul 2002, Kyle Babich wrote:

> This is the error I get when I try to execute my script:
>
> [Thu Jul 25 18:09:24 2002] [error] [client 65.59.106.226] Premature end
> of script headers: /home/sites/sbn/www/public_html/index.py
> Traceback (most recent call last):
>   File "/home/sites/sbn/www/public_html/index.py", line 671, in ?
>     print """
> KeyError: content
> Traceback (most recent call last):
>   File "/home/sites/sbn/www/public_html/index.py", line 671, in ?
>     print """
> KeyError: content
> Traceback (most recent call last):
>   File "/home/sites/sbn/www/public_html/cgi-bin/index.py", line 671, in
>   ?
>     print """
> KeyError: content
>
> And all that displays in the browser is a blank page.
> I have attached the script.
>
> Can someone help me with this?  It seems like it is having a problem
> printing content but near the beginning I do have content = con.

Hi Kyle,


But it only assigns to content if an exception was raised:

###
try:
	con = form['con'].value
except KeyError:
    con = ""
    content = con

    ## [humongous except block omitted for clarity.]
###


If there were no KeyError, 'content' isn't assigned to.  From looking at
your code, I think you mean to take the rest of the except block and bring
it back to the left column: I think you want that block to execute,
regardless of the exception handling.



Hope this helps!



From rob@uselesspython.com  Fri Jul 26 01:46:39 2002
From: rob@uselesspython.com (Rob)
Date: Thu, 25 Jul 2002 19:46:39 -0500
Subject: [Tutor] printing columns
In-Reply-To: <Pine.LNX.4.44.0207251539370.13973-100000@hkn.eecs.berkeley.edu>
Message-ID: <MPEOIFCOPCIHEDCLBLPBIEBKCBAA.rob@uselesspython.com>

Actually, what I had in mind was to have output I could paste directly into
a C++ header file. The output from my original code should compile without
error, but I thought it would be a nice touch to display it in pretty
columns.

Rob

> -----Original Message-----
> From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu]
> Sent: Thursday, July 25, 2002 5:47 PM
> To: Rob
> Cc: 'Tutor@Python. Org'
> Subject: Re: [Tutor] printing columns
>
>
>
>
> On Thu, 25 Jul 2002, Rob wrote:
>
> > >>> menuItems = ['NEW', 'OPEN', 'CLOSE', 'SAVE', 'SAVEAS', 'PAGESETUP',
> > 'PRINTPREVIEW', 'PRINT', 'EXIT', 'UNDO', 'CUT', 'COPY',
> 'PASTE', 'SEARCH',
> > 'NORMALVIEW', 'PRINTVIEW', 'ZOOMVIEW', 'STANDARDTB', 'EDITTB',
> 'STATUSTB',
> > 'CUSTOMTB', 'CASCADE', 'TILE', 'SPLIT']
> >
> > Then I whipped up a little for loop to print out the list of
> preprocessor
> > directives for the header file:
> >
> > >>> myInt = 1
> > >>> for item in menuItems:
> > 	print '#define ROB_' + item + '\t\t' + str(myInt)
> > 	myInt = myInt + 1
> >
> > Now I'm wondering how I could do this a little more neatly, organizing
> > the output into two columns. The incremented myInt values would be the
> > second column.
>
>
> Hi Rob,
>
>
> We can attach menu item numbers, without a for loop, with some creative
> use of the zip() builtin function:
>
> ###
> >>> menuItems = ['NEW', 'OPEN', 'CLOSE', 'SAVE', 'SAVEAS', 'PAGESETUP',
> ... 'PRINTPREVIEW', 'PRINT', 'EXIT', 'UNDO', 'CUT', 'COPY',
> 'PASTE', 'SEARCH',
> ... 'NORMALVIEW', 'PRINTVIEW', 'ZOOMVIEW', 'STANDARDTB',
> 'EDITTB', 'STATUSTB',
> ... 'CUSTOMTB', 'CASCADE', 'TILE', 'SPLIT']
> >>>
> >>>
> >>> numbered_menu_items = zip(menuItems, range(1, len(menuItems)+1))
> >>>
> >>>
> >>> numbered_menu_items
> [('NEW', 1), ('OPEN', 2), ('CLOSE', 3), ('SAVE', 4), ('SAVEAS', 5),
>  ('PAGESETUP', 6), ('PRINTPREVIEW', 7), ('PRINT', 8), ('EXIT', 9),
>  ('UNDO', 10), ('CUT', 11), ('COPY', 12), ('PASTE', 13), ('SEARCH', 14),
>  ('NORMALVIEW', 15), ('PRINTVIEW', 16), ('ZOOMVIEW', 17),
>  ('STANDARDTB', 18), ('EDITTB', 19), ('STATUSTB', 20), ('CUSTOMTB', 21),
>  ('CASCADE', 22), ('TILE', 23), ('SPLIT', 24)]
> ###
>
>
> Is this what you were looking for?
>
>
>
> Best of wishes to you!
>
>




From bjmartin98@pennswoods.net  Fri Jul 26 01:58:16 2002
From: bjmartin98@pennswoods.net (Billie)
Date: Thu, 25 Jul 2002 20:58:16 -0400
Subject: [Tutor] Newbie Question Again
Message-ID: <000c01c2343f$878ddb00$f938d141@bjmartin98>

This is a multi-part message in MIME format.

------=_NextPart_000_0009_01C2341D.FF6FAD00
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

First of all I would like to thank all the people who have answered my =
first question...Andrei, Kirk, and Danny.
My question was not asked correctly.  So bear with me while I ask again, =
OK?
I am using Python 2.2 for windows.  I am using Josh C.'s  =
Non-Programmers Tutorial for Python. We have only studied the While and =
the If statements so far.  We haven't studied lists yet.
We are given the following exercise:
# Modify the password guessing program to keep track of=20
# how many times the user has entered the password
# wrong.  If it is more than 3 times, print "That must have=20
# been complicated."

Password.py
# Note that this must not be the password so that the
# while loop runs at least once.
password =3D "foobar"
while password !=3D "unicorn":
     password =3D raw_input("Password:")
print "Welcome in"

 I don't understand how to count the users input, I've tried to do a few =
things but I either get can't add strings and integers, or asks for =
integers.
We were shown the fibonnacci sequence which has a counter in it but it =
is for integers.
I am not asking for you guys to solve the problem only but maybe explain =
why your way works.
I hope I'm not asking too much, I just want to understand.
Thanks in advance,
Billie



------=_NextPart_000_0009_01C2341D.FF6FAD00
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 5.50.4522.1800" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>First of all I would like to thank all =
the people=20
who have answered my first question...Andrei, Kirk, and =
Danny.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>My question was not asked =
correctly.&nbsp; So bear=20
with me while I ask again, OK?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I am using Python 2.2 for =
windows.&nbsp; I am using=20
Josh C.'s&nbsp; Non-Programmers Tutorial for Python. We have =
only&nbsp;studied=20
the While and the If statements so far.&nbsp; We haven't studied lists=20
yet.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>We are given the following =
exercise:</FONT></DIV>
<DIV><FONT face=3DArial size=3D2># Modify the password guessing program =
to keep=20
track of </FONT></DIV>
<DIV><FONT face=3DArial size=3D2># how many times the user has entered =
the=20
password</FONT></DIV>
<DIV><FONT face=3DArial size=3D2># wrong.&nbsp; If it is more than 3 =
times, print=20
"That must have </FONT></DIV>
<DIV><FONT face=3DArial size=3D2># been complicated."</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Password.py</FONT></DIV>
<DIV><FONT face=3DArial size=3D2># Note that this must not be the =
password so that=20
the</FONT></DIV>
<DIV><FONT face=3DArial size=3D2># while loop runs at least =
once.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>password =3D "foobar"</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>while password !=3D =
"unicorn":</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp;&nbsp; password =3D=20
raw_input("Password:")</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>print "Welcome in"</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;I don't understand how to count =
the users=20
input, I've tried to do a few things but I either get can't add strings =
and=20
integers, or asks for integers.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>We were shown the fibonnacci sequence =
which has a=20
counter in it but it is for integers.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I am not asking for you guys to solve =
the problem=20
only but maybe explain why your way works.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I hope I'm not asking too much, I just =
want to=20
understand.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Thanks in advance,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Billie</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_0009_01C2341D.FF6FAD00--



From dyoo@hkn.eecs.berkeley.edu  Fri Jul 26 02:15:09 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 25 Jul 2002 18:15:09 -0700 (PDT)
Subject: [Tutor] printing columns
In-Reply-To: <MPEOIFCOPCIHEDCLBLPBIEBKCBAA.rob@uselesspython.com>
Message-ID: <Pine.LNX.4.44.0207251756570.18074-100000@hkn.eecs.berkeley.edu>


On Thu, 25 Jul 2002, Rob wrote:

> Actually, what I had in mind was to have output I could paste directly
> into a C++ header file.

(By the way, if the outputted code is meant for C++, we should avoid the
'#define' directive, and instead use a 'constant int' declaration.)



> The output from my original code should compile without error, but I
> thought it would be a nice touch to display it in pretty columns.

Oh, I see now!  Some entries won't look good because the names extend
beyond the tab region, like:

###
#define PRINTVIEW	16
###

vs:

###
#define new	1
###

Even though both of these have a single tab between the name and number,
they don't line up the same way.


Hmmm... this is a little tricky, just because tab spacing can be
potentially different on other systems; a potential solution should use
spaces instead to guarantee that things look correct on all systems.

###
def layoutColumns(columns1, columns2, spacing=8):
    width_of_first_column = max([len(c) + spacing for c in columns1])
    lines = []
    for col1, col2 in zip(columns1, columns2):
        lines.append(col1
                     + " " * (width_of_first_column - len(col1))
                     + col2)
    return lines
###



Here's an example of how we might use it:

###
>>> print '\n'.join(layoutColumns(['NEW', 'PRINTVIEW'], ['1', '16']))
NEW              1
PRINTVIEW        16
###

However, I'd recommend not worrying about it, and delegate to a source
code prettifier instead.  For example, the 'indent' program on Unix
systems is specifically designed to make C/C++ source code look cuter.



Hope this helps!



From kalle@lysator.liu.se  Fri Jul 26 02:16:47 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Fri, 26 Jul 2002 03:16:47 +0200
Subject: [Tutor] printing columns
In-Reply-To: <MPEOIFCOPCIHEDCLBLPBIEBKCBAA.rob@uselesspython.com>
References: <Pine.LNX.4.44.0207251539370.13973-100000@hkn.eecs.berkeley.edu> <MPEOIFCOPCIHEDCLBLPBIEBKCBAA.rob@uselesspython.com>
Message-ID: <20020726011647.GD1054@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Rob]
> Actually, what I had in mind was to have output I could paste
> directly into a C++ header file. The output from my original code
> should compile without error, but I thought it would be a nice touch
> to display it in pretty columns.

Something like

    print "#define ROB_%s%s%s" % (item, " " * (20 - len(item)), myInt)

maybe?

Maybe 20 is to much or too little.  First, do something like

   lens = [len(x) for x in menuItems]
   lens.sort()
   maxlen = lens[-1]

and then use (maxlen + 1) instead of 20 above.

If you had a function sort() like this:

def sort(lst):
    x = lst[:]
    x.sort()
    return x

the second code snippet could be written

    maxlen = sort([len(x) for x in menuItems])[-1]

as well.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9QKL0dNeA1787sd0RAh9cAKCaT2tXYjaN3oSqWHut+gryHDCHXACfXcO5
31sY0qiD9pOFX0ltxtSE53k=
=DQmR
-----END PGP SIGNATURE-----


From rob@uselesspython.com  Fri Jul 26 02:21:27 2002
From: rob@uselesspython.com (Rob)
Date: Thu, 25 Jul 2002 20:21:27 -0500
Subject: [Tutor] Newbie Question Again
In-Reply-To: <000c01c2343f$878ddb00$f938d141@bjmartin98>
Message-ID: <MPEOIFCOPCIHEDCLBLPBIEBLCBAA.rob@uselesspython.com>

Is this a little closer to what you had in mind?

password = 'foobar' # set password as 'foobar'
attempts = 0        # create counter to keep track of number of user
attempts
userguess = 'nothing entered yet' # the user hasn't guessed anything yet
print               # just to keep it pretty
while userguess != password:
    userguess = raw_input('enter password: ')
    attempts += 1   # increments the counter
    if attempts > 2:
        print
        print 'too complicated for you, eh?'
        print
        break

I confess that I haven't read the thread up to this point in incredible
detail, though.

Rob


-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Billie
Sent: Thursday, July 25, 2002 7:58 PM
To: tutor@python.org
Subject: [Tutor] Newbie Question Again


First of all I would like to thank all the people who have answered my first
question...Andrei, Kirk, and Danny.
My question was not asked correctly.  So bear with me while I ask again, OK?
I am using Python 2.2 for windows.  I am using Josh C.'s  Non-Programmers
Tutorial for Python. We have only studied the While and the If statements so
far.  We haven't studied lists yet.
We are given the following exercise:
# Modify the password guessing program to keep track of
# how many times the user has entered the password
# wrong.  If it is more than 3 times, print "That must have
# been complicated."

Password.py
# Note that this must not be the password so that the
# while loop runs at least once.
password = "foobar"
while password != "unicorn":
     password = raw_input("Password:")
print "Welcome in"

 I don't understand how to count the users input, I've tried to do a few
things but I either get can't add strings and integers, or asks for
integers.
We were shown the fibonnacci sequence which has a counter in it but it is
for integers.
I am not asking for you guys to solve the problem only but maybe explain why
your way works.
I hope I'm not asking too much, I just want to understand.
Thanks in advance,
Billie




From guillermo.fernandez@epfl.ch  Fri Jul 26 02:21:15 2002
From: guillermo.fernandez@epfl.ch (Guillermo Fernandez)
Date: Fri, 26 Jul 2002 10:51:15 +0930
Subject: [Tutor] printing columns
References: <MPEOIFCOPCIHEDCLBLPBIEBKCBAA.rob@uselesspython.com>
Message-ID: <3D40A40A.2B3B3FF@epfl.ch>

Rob wrote:
> 
> Actually, what I had in mind was to have output I could paste directly into
> a C++ header file. The output from my original code should compile without
> error, but I thought it would be a nice touch to display it in pretty
> columns.

I think I get your point (I'm also a maniac of the two columns #define
;-)

Here is a proposed solution. Unfortunately, it only works in cases where
your name plus the #define is less that... 4*number of equivalent spaces
per tabulation.

Each tabulation is equivalent to a number of spaces (is what the
variable of tab_space represents) so you'll have to add plus or less
tabulations depending of how much "equivalent spaces" your #define
ROB_name uses. It's what I try to do in the following program.

If it's not very clear, please told me and I'll try to make it clearer.

menuItems = ['NEW', 'OPEN', 'CLOSE', 'SAVE', 'SAVEAS',
             'PAGESETUP', 'PRINTPREVIEW', 'PRINT', 'EXIT',
             'UNDO', 'CUT', 'COPY', 'PASTE', 'SEARCH',
             'NORMALVIEW', 'PRINTVIEW', 'ZOOMVIEW', 'STANDARDTB',
             'EDITTB', 'STATUSTB', 'CUSTOMTB', 'CASCADE', 'TILE',
             'SPLIT']

myInt=1

tab_space=8

for item in menuItems:
    define='#define ROB_' + item
    if len(define) < (2*tab_space):
	define+='\t\t\t' + str(myInt)
    elif len(define) > (3*tab_space-1):
	define+='\t' + str(myInt)
    else:
	define+='\t\t' + str(myInt)
    print define
    myInt = myInt + 1


with this we have a two columns output of:

guille/scripts> python test.py
#define ROB_NEW                 1
#define ROB_OPEN                2
#define ROB_CLOSE               3
#define ROB_SAVE                4
#define ROB_SAVEAS              5
#define ROB_PAGESETUP           6
#define ROB_PRINTPREVIEW        7
#define ROB_PRINT               8
#define ROB_EXIT                9
#define ROB_UNDO                10
#define ROB_CUT                 11
#define ROB_COPY                12
#define ROB_PASTE               13
#define ROB_SEARCH              14
#define ROB_NORMALVIEW          15
#define ROB_PRINTVIEW           16
#define ROB_ZOOMVIEW            17
#define ROB_STANDARDTB          18
#define ROB_EDITTB              19
#define ROB_STATUSTB            20
#define ROB_CUSTOMTB            21
#define ROB_CASCADE             22
#define ROB_TILE                23
#define ROB_SPLIT               24


From rob@uselesspython.com  Fri Jul 26 02:23:56 2002
From: rob@uselesspython.com (Rob)
Date: Thu, 25 Jul 2002 20:23:56 -0500
Subject: [Tutor] printing columns
In-Reply-To: <Pine.LNX.4.44.0207251756570.18074-100000@hkn.eecs.berkeley.edu>
Message-ID: <MPEOIFCOPCIHEDCLBLPBAEBMCBAA.rob@uselesspython.com>

>
> However, I'd recommend not worrying about it, and delegate to a source
> code prettifier instead.  For example, the 'indent' program on Unix
> systems is specifically designed to make C/C++ source code look cuter.
>

Definitely not worth worrying about in the literal sense. Merely a diversion
from my studies for the test I'll be taking in the morning. And more fun
stuff for the newbies to play with.

Rob




From kalle@lysator.liu.se  Fri Jul 26 02:25:42 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Fri, 26 Jul 2002 03:25:42 +0200
Subject: [Tutor] printing columns
In-Reply-To: <20020726011647.GD1054@i92.ryd.student.liu.se>
References: <Pine.LNX.4.44.0207251539370.13973-100000@hkn.eecs.berkeley.edu> <MPEOIFCOPCIHEDCLBLPBIEBKCBAA.rob@uselesspython.com> <20020726011647.GD1054@i92.ryd.student.liu.se>
Message-ID: <20020726012542.GE1054@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Me]
> the second code snippet could be written
> 
>     maxlen = sort([len(x) for x in menuItems])[-1]
> 
> as well.

Or, if I had read the Library Reference, as

    maxlen = max([len(x) for x in menuItems])

which is better, of course.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9QKUQdNeA1787sd0RAouXAKDQNf15SYVO6ImWukVh4XxOoCSHwgCff9cD
hnbfXfRrV/7PFpcAntOvCcE=
=/GQT
-----END PGP SIGNATURE-----


From ckasso@sprynet.com  Fri Jul 26 03:27:21 2002
From: ckasso@sprynet.com (Chris Kassopulo)
Date: Thu, 25 Jul 2002 22:27:21 -0400
Subject: [Tutor] printing columns
In-Reply-To: <MPEOIFCOPCIHEDCLBLPBIEBKCBAA.rob@uselesspython.com>
References: <Pine.LNX.4.44.0207251539370.13973-100000@hkn.eecs.berkeley.edu>
 <MPEOIFCOPCIHEDCLBLPBIEBKCBAA.rob@uselesspython.com>
Message-ID: <20020725222721.51da606f.ckasso@sprynet.com>

On Thu, 25 Jul 2002 19:46:39 -0500
"Rob" <rob@uselesspython.com> wrote:

> Actually, what I had in mind was to have output I could paste directly
> into a C++ header file. The output from my original code should
> compile without error, but I thought it would be a nice touch to
> display it in pretty columns.
> 
> Rob
> 

Greetings,

This is my first post to the list.  I'm new to python and my programming
experience is very limited (poking around in fortran and c 15 years
ago).

By coincidence, the first python script I decided to write is a program
to output a list in columns, so I'll throw my hat in the ring.  Already,
my script has benefitted from this thread.  Here is my solution to the
script at hand:

#! /usr/bin/env python

import string
import sys
	
menuItems = (sys.builtin_module_names)

# find longest string
i = 0
longestLength = len(menuItems[i])
while i < len(menuItems):
	x = len(menuItems[i])
	i = i + 1
	if x > longestLength:
		longestLength = x
		
# field width for ljust
fieldWidth = longestLength + 2		

# output the list
myInt = 1
numberofColumns = 1
currentColumn = 1
for item in menuItems:
	if currentColumn < numberofColumns:
		print '#define ROB_' + string.ljust(item,fieldWidth) +
str(myInt),
		currentColumn = currentColumn + 1
		if myInt == len(menuItems):
			print
	else:
		print '#define ROB_' + string.ljust(item,fieldWidth) +
str(myInt)
		currentColumn = 1
	myInt = myInt + 1		
	
-- 
Chris Kassopulo _/\_ Linux User #199893 _/\_ Slackware



From unixguru@mac.com  Tue Jul 23 23:47:25 2002
From: unixguru@mac.com (UNIX Guru)
Date: Tue, 23 Jul 2002 15:47:25 -0700
Subject: [Tutor] string.count in Windows vs UNIX
In-Reply-To: <BIEJKCLHCIOIHAGOKOLHOEIEDHAA.tim@zope.com>
Message-ID: <28A7A323-9E8E-11D6-97FB-00039375444A@mac.com>

On Tuesday, July 23, 2002, at 03:12 , Tim Peters wrote:

> [UNIX Guru]
>> I've been dabbling with Python for a bit, and use the following
>> script-excerpt to go through a large file checking for specific text. 
>> On
>> UNIX it finds the correct number of occurances (6665 - double-checked
>> with grep -e "Subject: Results:" mail.file | wc -l) but when run on
>> Windows (2K/XP) it stops finding, consistently,  after 4195 occurances.
>> ...
>
>> mailfile = open('mail.file', 'r')
>
> Use 'rb' instead.  Python makes the same distinction between text-mode 
> and
> binary-mode files as C makes, since Python file objects are just a thin
> wrapper around C stdio streams (FILE*).  As a UNIX Guru <wink>, you're 
> used
> to systems where text- and binary-mode files act identically.  They 
> don't on
> Windows, and some non-printable characters in Windows text-mode files 
> have
> meta-meanings (chiefly that for first occurrence of chr(26) acts as an 
> EOF
> marker in files opened in text mode on Windows).

Yep, that appears to have done the trick. Thanks! It would never have 
dawned on me that Windows, which was generating the file that would be 
parsed, would insert non-printable characters, even though the source 
was plain-text, too.

That'll teach me to develop scripts on UNIX and deploy on Windows. :-/



From tutor@python.org  Wed Jul 24 00:08:30 2002
From: tutor@python.org (Tim Peters)
Date: Tue, 23 Jul 2002 19:08:30 -0400
Subject: [Tutor] string.count in Windows vs UNIX
In-Reply-To: <28A7A323-9E8E-11D6-97FB-00039375444A@mac.com>
Message-ID: <BIEJKCLHCIOIHAGOKOLHOEIKDHAA.tim@zope.com>

[UNIX Guru, upon discovering the joy of binary-mode on Windows]
> Yep, that appears to have done the trick. Thanks! It would never have
> dawned on me that Windows, which was generating the file that would be
> parsed, would insert non-printable characters, even though the source
> was plain-text, too.

Actually, Windows wouldn't do that.  If there was a chr(26) in your file,
and you created it, something you did put it there.  On output to a
text-mode file, the only trick Windows plays is converting \n (LF) to a \r\n
(CRLF) pair.  So you've still got A Mystery to solve here.

> That'll teach me to develop scripts on UNIX and deploy on Windows. :-/

Watch out for fork() too <wink>.



From gege@nst.pku.edu.cn  Fri Jul 26 06:43:05 2002
From: gege@nst.pku.edu.cn (Ares Liu)
Date: Fri, 26 Jul 2002 13:43:05 +0800
Subject: [Tutor] =?utf-8?Q?Re:_=5BTutor=5D_=E6=B5=8B=E8=AF=95_for_test_pls_igno?=
 =?utf-8?Q?re.?=
References: <BIEJKCLHCIOIHAGOKOLHOEIKDHAA.tim@zope.com>
Message-ID: <004b01c2346a$12c7fff0$8300a8c0@jadeite.com>

anVzdCBmb3IgdGVzdGluZyBtYWlsaW5nIGxpc3QgaGVhZGVyIGRlY29kZS4NCg==



From guillermo.fernandez@epfl.ch  Fri Jul 26 07:16:56 2002
From: guillermo.fernandez@epfl.ch (Guillermo Fernandez)
Date: Fri, 26 Jul 2002 15:46:56 +0930
Subject: [Tutor] List initialisation
References: <BIEJKCLHCIOIHAGOKOLHOEIKDHAA.tim@zope.com> <004b01c2346a$12c7fff0$8300a8c0@jadeite.com>
Message-ID: <3D40E958.DBAD3D2B@epfl.ch>

Hi!

I've been trying to initialise a list containing a number 'size' of
zeros. After looking in the doc and tutorials, I've done it like this:

def zero(x): return 0
list=map(zero, range(0,size))

But I find this way pretty ugly. Is there a more 'beautiful' or
'standard' way to do it that I've missed?

Thanks,

Guille


From fgranger@altern.org  Fri Jul 26 07:37:18 2002
From: fgranger@altern.org (Francois Granger)
Date: Fri, 26 Jul 2002 08:37:18 +0200
Subject: [Tutor] List initialisation
In-Reply-To: <3D40E958.DBAD3D2B@epfl.ch>
References: <BIEJKCLHCIOIHAGOKOLHOEIKDHAA.tim@zope.com>
 <004b01c2346a$12c7fff0$8300a8c0@jadeite.com> <3D40E958.DBAD3D2B@epfl.ch>
Message-ID: <a05100300b9669e23da49@[192.168.1.11]>

At 15:46 +0930 on 26/07/02, in message [Tutor] List initialisation, 
Guillermo Fernandez wrote:
>
>def zero(x): return 0
>list=map(zero, range(0,size))

range(0,size) == range(size)

>But I find this way pretty ugly. Is there a more 'beautiful' or
>'standard' way to do it that I've missed?

What about:

list = [0] * size


From rob@uselesspython.com  Fri Jul 26 13:45:21 2002
From: rob@uselesspython.com (Rob)
Date: Fri, 26 Jul 2002 07:45:21 -0500
Subject: [Tutor] printing columns
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C794@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <MPEOIFCOPCIHEDCLBLPBAECACBAA.rob@uselesspython.com>

Using the two tabs does create two columns after a fashion, they're just not
evenly laid out. Quite functional, of course, but part of our grade in this
class is based on how the code looks to someone who has to read it.

Of course this would have been far easier to just type than to script in
Python in this case, but I felt like a bit of a diversion from the studies.

As far as using #define instead of const, these are preprocessor directives
in a header file for a Windows GUI in a class dedicated simultaneously to
the Win32 API and to more advanced OOP concepts in C++ (probably more
intermediate than advanced, but I'm not quibbling over symantics too much in
this case). The instructor wants to see it coded this way. Also, and I'm not
sure how ultimately relevant this is, but the header file consists of
nothing but this list of #define statements. This is then included in a .rc
resource file.

Rob
http://uselesspython.com

> -----Original Message-----
> From: alan.gauld@bt.com [mailto:alan.gauld@bt.com]
> Sent: Friday, July 26, 2002 6:07 AM
> To: rob@uselesspython.com; tutor@python.org
> Subject: RE: [Tutor] printing columns
>
>
> > code that produces a header file for a C++ program, but I've
> > got a simple bit of polish I'd like to put on it.
>
> > >>> menuItems = ['NEW', 'OPEN', 'CLOSE', 'SAVE', 'SAVEAS',
> > ...
> > 'CUSTOMTB', 'CASCADE', 'TILE', 'SPLIT']
>
> > >>> myInt = 1
> > >>> for item in menuItems:
> > 	print '#define ROB_' + item + '\t\t' + str(myInt)
> > 	myInt = myInt + 1
> >
> > Now I'm wondering how I could do this a little more neatly,
> > organizing the output into two columns.
>
> Doesn't your two tabs do exactly that? The other way of
> course would be to create a format string with fixed
> length fields...
>
>
> The other issue of course is why you are using #defines
> in a C++ program? Surely const would be better?
>
> Or since you are assigning a series of integer values
> use an enum which will do that automatically.
>
> enum codes {NEW=1,
>            OPEN,  // automatically assigned 2 etc...
>            ...
>            TILE,
>            SPLIT};
>
> Saves a mite of typing and you can now add new values
> easily without worrying about maintaining the numeric
> values etc. And its typesafe, nobody can kid the compiler
> by passing a raw integer pretending to be a code to a
> function which expects a code as input...
>
> Altogether safer and more idiomatic C++.
>
> Alan G.
>




From gege@nst.pku.edu.cn  Fri Jul 26 14:40:34 2002
From: gege@nst.pku.edu.cn (Ares Liu)
Date: Fri, 26 Jul 2002 21:40:34 +0800
Subject: [Tutor] A question about Mailman soft.  [hacking Mailman for fun and profit]
References: <Pine.LNX.4.44.0207260128400.27692-100000@hkn.eecs.berkeley.edu>
Message-ID: <010001c234aa$07448190$8300a8c0@jadeite.com>

VGhlIG1haWwgSSBzZW50IHRvIHR1dG9yIHdhcyB3aXRoIGEgVW5pY29kZSBlbmNvZGVkIFN1Ympl
Y3QgbGluZSBhcyBmb2xsb3c6DQoNClN1YmplY3Q6ID0/dXRmLTg/UT9SZTpfPTVCVHV0b3I9NURf
PUU2PUI1PThCPUU4PUFGPTk1X2Zvcl90ZXN0X3Bsc19pZ25vPz0NCiA9P3V0Zi04P1E/cmUuPz0N
CkRhdGU6IEZyaSwgMjYgSnVsIDIwMDIgMTM6NDM6MDUgKzA4MDANCk1JTUUtVmVyc2lvbjogMS4w
DQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW47DQogY2hhcnNldD0idXRmLTgiDQpDb250ZW50LVRy
YW5zZmVyLUVuY29kaW5nOiBiYXNlNjQNCg0KWW91ciBtb2R1bGUgZGlkIG5vdCBoYW5kbGUgdXRm
LTggZW5jb2RlIG1hcmtlciA/dXRmLTg/IDotKSBEZWNvZGVkIHN1YmplY3QgaXMNCj0/dXRmLTg/
UT9SZTpfW1R1dG9yXV9ceGU2XHhiNVx4OGJceGU4XHhhZlx4OTVfZm9yX3Rlc3RfcGxzX2lnbm8/
ID0/dXRmLTg/UT9yZS4/DQogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIF5e
Xl5eXl5eXl5eXl5eXl5eXl4gMiBjaGluZXNlIHdvcmRzIGRpc3BsYXllZCBpbiBJZGxlLiBJdCdz
IG5vcm1hbC4NCg0KVGhlIG1haWwgSSBzZW50IHRvIG15IGxpc3Qgd2FzIHdpdGggYmFzZTY0IGVu
Y29kZWQgU3ViamVjdCBsaW5lIGFzIGZvbGxvdzoNCg0KU3ViamVjdDogPT9nYjIzMTI/Qj9VbVU2
SUZ0VVpYTjBYU0N5NHNyVXN1TEsxQT09Pz0NCkRhdGU6IEZyaSwgMjYgSnVsIDIwMDIgMTg6NDM6
NTMgKzA4MDANCk1JTUUtVmVyc2lvbjogMS4wDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW47DQog
Y2hhcnNldD0iZ2IyMzEyIg0KQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzogYmFzZTY0DQoNCldo
ZW4gSSBjaGFuZ2VkIHlvdXIgbW9kdWxlIGZyb20gDQogICAgICAgIG1pbWV0b29scy5lbmNvZGUo
U3RyaW5nSU8uU3RyaW5nSU8ocyksIG91dHB1dGZpbGUsICdxdW90ZWQtcHJpdGFibGUnKSANCnRv
IA0KICAgICAgICBtaW1ldG9vbHMuZW5jb2RlKFN0cmluZ0lPLlN0cmluZ0lPKHMpLCBvdXRwdXRm
aWxlLCAnYmFzZTY0JykNCg0KSSBnZXQgYW4gZXJyb3I6IGluY29ycmVjdCBwYWRkaW5nLiANClRo
ZW4gSSBkZWxldGUgIj9nYjIzMTI/Qj8iIGZyb20gc3RyaW5nLiBJIGdldCByZWFsIHN0cmluZy4g
DQoNCidSZTogW1Rlc3RdIFx4YjJceGUyXHhjYVx4ZDRceGIyXHhlMlx4Y2FceGQ0Jw0KICAgICAg
ICAgICAgICAgICBeXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl4gNCBjaGluZXNlIHdvcmRzIGRp
c3BsYXllZCBpbiBJZGxlLg0KDQpTbyBhIHdvcmtpbmcgbW9kdWxlIG11c3QgaGFuZGxlIGVuY29k
ZSBtYXJrZXIgZmlyc3RseSwgIGFuZCB0aGVuIGRlY29kZSB0aGUgc3ViamVjdC4NCg0KLUFyZXMN
Cg0KLS0tLS0gT3JpZ2luYWwgTWVzc2FnZSAtLS0tLSANCkZyb206ICJEYW5ueSBZb28iIDxkeW9v
QGhrbi5lZWNzLmJlcmtlbGV5LmVkdT4NClRvOiAiQXJlcyBMaXUiIDxnZWdlQG5zdC5wa3UuZWR1
LmNuPg0KQ2M6IDx0dXRvckBweXRob24ub3JnPjsgPG1haWxtYW4tdXNlcnNAcHl0aG9uLm9yZz4N
ClNlbnQ6IEZyaWRheSwgSnVseSAyNiwgMjAwMiA1OjIyIFBNDQpTdWJqZWN0OiBSZTogW1R1dG9y
XSBBIHF1ZXN0aW9uIGFib3V0IE1haWxtYW4gc29mdC4gW2hhY2tpbmcgTWFpbG1hbiBmb3IgZnVu
IGFuZCBwcm9maXRdDQoNCg0KPiBbTm90ZTogSSdtIENDJ2luZyBtYWlsbWFuLXVzZXJzIGFzIHRo
aXMgbWlnaHQgYmUgdXNlZnVsIGZvciB0aGVtLg0KPiBIb3BlZnVsbHksIHRoZXknbGwgY29ycmVj
dCBteSBoYWNrIGJ5IHRlbGxpbmcgbWUgdGhlIHJpZ2h0IHdheSB0byBkbyB0aGlzLg0KPiAqZ3Jp
bipdDQo+IA0KPiANCj4gDQo+IE9uIEZyaSwgMjYgSnVsIDIwMDIsIEFyZXMgTGl1IHdyb3RlOg0K
PiANCj4gPiBJIGNoZWNrZWQgdGhlIGFyY2hpdmUgbWFpbCBvbiBtYWlsbWFuIGxpc3QuIFNvbWUg
b25lIGhhZCBkaXNjdXNzZWQgdGhpcw0KPiA+IHF1ZXN0aW9uIGJlZm9yZS4NCj4gDQo+IERvIHlv
dSBoYXZlIGEgbGluayB0byB0aGF0IGFyY2hpdmVkIG1lc3NhZ2U/ICBJJ20gaW50ZXJlc3RlZCBp
biBsb29raW5nIGF0DQo+IHRoaXMsIGp1c3QgZm9yIGN1cmlvc2l0eSdzIHNha2UuDQo+IA0KPiAN
Cj4gDQo+IA0KPiA+IFRoZSByZWFzb24gaXMgaWYgSSB1c2Ugbm8gRW5nbGlzaCB3b3JkcyBpbiB0
aGUgU3ViamVjdCBMaW5lLCBUaGUNCj4gPiBsYW5ndWFnZSBjb2RlIG1hcmtlciB3aWxsIGFkZGVk
IGluIGZvcm50IG9mICJSZToiYW5kIGVuY29kaW5nIHRoZQ0KPiA+IFN1YmplY3QgYXMgc3RoIGxp
a2UgIj0/Z2IyMzEyP0IyeHh4eHh4eHg/PSIuDQo+IA0KPiBZZXMsIGl0IGxvb2tzIGxpa2UgaXQg
d3JhcHMgaXQgaW4gc29tZSBraW5kIG9mIGVuY29kaW5nLi4uIHV0Zi04PyAgSSB3aXNoDQo+IEkg
a25ldyBtb3JlIGFib3V0IFVuaWNvZGUuDQo+IA0KPiANCj4gDQo+ID4gSXQgaXMgc3VyZWx5IHRo
YXQgbWFpbG1hbiBjb3VsZCBub3Qgc2VhcmNoIGFueSByZXBseSBrZXl3b3JkLiBTbywgYWRkZWQN
Cj4gPiBwcmVmaXggYWdhaW4uDQo+IA0KPiANCj4gSSB0aGluayBJIHVuZGVyc3RhbmQgYmV0dGVy
IG5vdy4gIFRoZSBwcm9ibGVtIGlzIHRoYXQgdGhlIGVuY29kaW5nIGxlYXZlcw0KPiBtYW55IG9m
IHRoZSBjaGFyYWN0ZXJzIGFsb25lLCBidXQgdHJhbnNmb3JtcyB0aGUgYnJhY2VzIGluOg0KPiAN
Cj4gICAgICdbVHV0b3JdJw0KPiANCj4gdG8gc29tZXRoaW5nIGxpa2U6DQo+IA0KPiAgICAgJz01
QlR1dG9yPTVEJw0KPiANCj4gSSdtIGd1ZXNzaW5nIHRoaXMgYmVjYXVzZSAweDViIGFuZCAweDVE
IGFyZSB0aGUgYXNjaWkgY29kZXMgZm9yIGJyYWNlczoNCj4gDQo+ICMjIw0KPiA+Pj4gY2hyKDB4
NWIpDQo+ICdbJw0KPiA+Pj4gY2hyKDB4NWQpDQo+ICddJw0KPiAjIyMNCj4gDQo+IA0KPiANCj4g
SG1tbW0uICBXYWl0LiAgSSd2ZSBzZWVuIHRoZXNlIGNoYXJhY3RlcnMgYmVmb3JlLiAgSXMgdGhp
cyBNSU1FIGVuY29kaW5nPw0KPiBNSU1FIGVuY29kaW5nIGlzIG9mdGVuIHVzZWQgaW4gcmVwcmVz
ZW50aW5nIGxhbmd1YWdlIHN0cmluZ3MgaW4gZW1haWwNCj4gYmVjYXVzZSBhbG1vc3QgYWxsIHN5
c3RlbXMgY2FuIGhhbmRsZSBpdC4NCj4gDQo+ICMjIw0KPiA+Pj4gZGVmIG15ZGVjb2RlKHMpOg0K
PiAuLi4gICAgIG91dHB1dGZpbGUgPSBTdHJpbmdJTy5TdHJpbmdJTygpDQo+IC4uLiAgICAgbWlt
ZXRvb2xzLmRlY29kZShTdHJpbmdJTy5TdHJpbmdJTyhzKSwgb3V0cHV0ZmlsZSwNCj4gJ3F1b3Rl
ZC1wcmludGFibGUnKQ0KPiAuLi4gICAgIHJldHVybiBvdXRwdXRmaWxlLmdldHZhbHVlKCkNCj4g
Li4uDQo+ID4+PiBteWRlY29kZSgnPTVCVHV0b3I9NUQnKQ0KPiAnW1R1dG9yXScNCj4gIyMjDQo+
IA0KPiBBaCBoYSEgIEl0IGxvb2tzIGxpa2UgaXQhICBHb29kIQ0KPiANCj4gDQo+IA0KPiBJbiB0
aGlzIGNhc2UsIG1heWJlIHdlIGNhbiBleHRlbmQgdGhhdCBjaGVjayBpbg0KPiBIYW5kbGVycy5D
b29rSGVhZGVycy5wcm9jZXNzKCkgdG8gdGFrZSB0aGlzIHBhcnRpY3VsYXIgZW5jb2RpbmcgaW50
bw0KPiBjb25zaWRlcmF0aW9uOiBpZiB3ZSBkZWNvZGUgdGhlIGhlYWRlciBiYWNrIHRvIG5vcm1h
bCwgdGhlbiB0aGUgcHJlZml4DQo+IGNoZWNrIHdpbGwgd29yay4NCj4gDQo+IA0KPiANCj4gSWYg
eW91J3JlIGZlZWxpbmcgYWR2ZW50dXJvdXMsIGFuZCBpZiB5b3UncmUgY29tZm9ydGFibGUgZWRp
dGluZyBQeXRob24sDQo+IHlvdSBjYW4gYWRkIHRoaXMgZmlsZSwgJ3F1b3RlZF9wcmludGFibGVf
ZGVjb2Rlci5weScgaW4gdGhlDQo+ICdNYWlsbWFuL0hhbmRsZXJzLycgZGlyZWN0b3J5IG9mIE1h
aWxtYW46DQo+IA0KPiAjIyMjIyMNCj4gIyMgcXVvdGVkX3ByaW50YWJsZV9kZWNvZGVyLnB5DQo+
IA0KPiBpbXBvcnQgU3RyaW5nSU8sIG1pbWV0b29scw0KPiBkZWYgZGVjb2RlX3F1b3RlZF9wcmlu
dGFibGUocyk6DQo+ICAgICAiIiJHaXZlbiBhIG1pbWUgJ3F1b3RlZC1wcmludGFibGUnIHN0cmlu
ZyBzLCByZXR1cm5zIGl0cyBkZWNvZGluZy4NCj4gSWYgYW55dGhpbmcgYmFkIGhhcHBlbnMsIHJl
dHVybnMgcy4iIiINCj4gICAgIHRyeToNCj4gICAgICAgICBvdXRwdXRmaWxlID0gU3RyaW5nSU8u
U3RyaW5nSU8oKQ0KPiAgICAgICAgIG1pbWV0b29scy5kZWNvZGUoU3RyaW5nSU8uU3RyaW5nSU8o
cyksIG91dHB1dGZpbGUsDQo+ICAgICAgICAgICAgICAgICAgICAgICAgICAncXVvdGVkLXByaW50
YWJsZScpDQo+ICAgICAgICAgcmV0dXJuIG91dHB1dGZpbGUuZ2V0dmFsdWUoKQ0KPiAgICAgZXhj
ZXB0Og0KPiAgICAgICAgIHJldHVybiBzDQo+ICMjIw0KPiANCj4gVGhpcyBuZXcgbW9kdWxlIHdp
bGwgY29udmVydCB0aGUgaGVhZGVyIGFuZCBjaGFuZ2UgYWxsIHRoZSAnPTVCJyBhbmQgJz01RCcN
Cj4gY2hhcmFjdGVycyBiYWNrIGludG8gYnJhY2VzIGlmIGl0IGNhbiBkbyBzbyBzYWZlbHkuICBX
ZSdsbCBiZSB1c2luZyBpdCBpbg0KPiBhIG1vbWVudC4NCj4gDQo+IA0KPiANCj4gDQo+IE9uY2Ug
eW91J3ZlIGFkZGVkIHRoaXMgbW9kdWxlLCB3aXRoaW4gdGhlIHNhbWUgZGlyZWN0b3J5LCBsZXQn
cyBtb2RpZnkNCj4gQ29va0hlYWRlcnMucHkgdG8gdXNlIHRoaXMgZnVuY3Rpb24uDQo+IA0KPiBB
bmQgbWFrZSBiYWNrdXBzLCBiZWNhdXNlIEkgaGF2ZSBub3QgdGVzdGVkIHRoaXMgeWV0ISAgKmdy
aW4qDQo+IA0KPiANCj4gDQo+IEFkZCBhdCB0aGUgdG9wIG9mIHRoZSBDb29rSGVhZGVycyBtb2R1
bGU6DQo+IA0KPiAjIyMNCj4gZnJvbSBxdW90ZWRfcHJpbnRhYmxlX2RlY29kZXIgaW1wb3J0IGRl
Y29kZV9xdW90ZWRfcHJpbnRhYmxlDQo+ICMjIw0KPiANCj4gc28gdGhhdCBDb29raGVhZGVycyBr
bm93cyBhYm91dCBvdXIgbmV3IGZ1bmN0aW9uLiAgRmluYWxseSwgbW9kaWZ5IHRoZQ0KPiBjaGVj
ayBpbiB0aGUgQ29va2hlYWRlcnMucHJvY2VzcygpIGZ1bmN0aW9uOg0KPiANCj4gIyMjDQo+ICAg
ICAgICAgZWxpZiBwcmVmaXggYW5kIG5vdCByZS5zZWFyY2gocmUuZXNjYXBlKHByZWZpeCksIHN1
YmplY3QsIHJlLkkpOg0KPiAjIyMNCj4gDQo+IA0KPiBpbnRvOg0KPiANCj4gIyMjDQo+ICAgICAg
ICAgZWxpZiBwcmVmaXhcDQo+ICAgICAgICAgICAgICBhbmQgbm90IHJlLnNlYXJjaChyZS5lc2Nh
cGUocHJlZml4KSwgc3ViamVjdCwgcmUuSSlcDQo+ICAgICAgICAgICAgICBhbmQgbm90IHJlLnNl
YXJjaChyZS5lc2NhcGUocHJlZml4KSwNCj4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
IGRlY29kZV9xdW90ZWRfcHJpbnRhYmxlKHN1YmplY3QpLCByZS5JKQ0KPiAjIyMNCj4gDQo+IA0K
PiBJJ3ZlIG1vZGlmaWVkIHRoZSBsb2dpYyB0byBpbmNsdWRlIHRoZSBwcmVmaXggY2hlY2sgb24g
dGhlIGRlY29kZWQgc3ViamVjdA0KPiBoZWFkZXIuICBBcmVzLCBpZiB0aGlzIHdvcmtzLCBJJ2xs
IHNlbmQgdGhlIHBhdGNoIG92ZXIgdG8gdGhlIE1haWxtYW4NCj4gZm9sa3MuICBXaG8ga25vd3M7
IGl0IG1pZ2h0IGJlIHVzZWZ1bCBmb3Igc29tZW9uZSBlbHNlIG91dCB0aGVyZS4gICpncmluKg0K
PiANCj4gDQo+IA0KPiBCZXN0IG9mIHdpc2hlcyB0byB5b3UhDQo=



From gege@nst.pku.edu.cn  Fri Jul 26 13:28:13 2002
From: gege@nst.pku.edu.cn (Ares Liu)
Date: Fri, 26 Jul 2002 20:28:13 +0800
Subject: [Tutor] A question about Mailman soft.  [hacking Mailman for fun and profit]
References: <Pine.LNX.4.44.0207260226160.27692-100000@hkn.eecs.berkeley.edu>
Message-ID: <00e001c2349f$ea889820$8300a8c0@jadeite.com>

VGhhbmtzIGFnYWluIERhbm55LA0KDQpQYXRjaCBmcm9tIHRoZSBzZWNvbmQgVVJMIHdvcmtzIE9L
Lg0KDQotQXJlcw0KLS0tLS0gT3JpZ2luYWwgTWVzc2FnZSAtLS0tLSANCkZyb206ICJEYW5ueSBZ
b28iIDxkeW9vQGhrbi5lZWNzLmJlcmtlbGV5LmVkdT4NClRvOiAiQXJlcyBMaXUiIDxnZWdlQG5z
dC5wa3UuZWR1LmNuPg0KQ2M6IDx0dXRvckBweXRob24ub3JnPg0KU2VudDogRnJpZGF5LCBKdWx5
IDI2LCAyMDAyIDU6MzIgUE0NClN1YmplY3Q6IFJlOiBbVHV0b3JdIEEgcXVlc3Rpb24gYWJvdXQg
TWFpbG1hbiBzb2Z0LiBbaGFja2luZyBNYWlsbWFuIGZvciBmdW4gYW5kIHByb2ZpdF0NCg0KDQo+
IA0KPiANCj4gT24gRnJpLCAyNiBKdWwgMjAwMiwgRGFubnkgWW9vIHdyb3RlOg0KPiANCj4gPiBb
Tm90ZTogSSdtIENDJ2luZyBtYWlsbWFuLXVzZXJzIGFzIHRoaXMgbWlnaHQgYmUgdXNlZnVsIGZv
ciB0aGVtLg0KPiA+IEhvcGVmdWxseSwgdGhleSdsbCBjb3JyZWN0IG15IGhhY2sgYnkgdGVsbGlu
ZyBtZSB0aGUgcmlnaHQgd2F5IHRvIGRvDQo+ID4gdGhpcy4gKmdyaW4qXQ0KPiA+DQo+ID4NCj4g
Pg0KPiA+IE9uIEZyaSwgMjYgSnVsIDIwMDIsIEFyZXMgTGl1IHdyb3RlOg0KPiA+DQo+ID4gPiBJ
IGNoZWNrZWQgdGhlIGFyY2hpdmUgbWFpbCBvbiBtYWlsbWFuIGxpc3QuIFNvbWUgb25lIGhhZCBk
aXNjdXNzZWQgdGhpcw0KPiA+ID4gcXVlc3Rpb24gYmVmb3JlLg0KPiA+DQo+ID4gRG8geW91IGhh
dmUgYSBsaW5rIHRvIHRoYXQgYXJjaGl2ZWQgbWVzc2FnZT8gIEknbSBpbnRlcmVzdGVkIGluIGxv
b2tpbmcgYXQNCj4gPiB0aGlzLCBqdXN0IGZvciBjdXJpb3NpdHkncyBzYWtlLg0KPiANCj4gDQo+
IE9oLg0KPiANCj4gaHR0cDovL3NvdXJjZWZvcmdlLm5ldC90cmFja2VyL2luZGV4LnBocD9mdW5j
PWRldGFpbCZhaWQ9NDk4NzY2Jmdyb3VwX2lkPTEwMyZhdGlkPTMwMDEwMw0KPiBodHRwOi8vc291
cmNlZm9yZ2UubmV0L3RyYWNrZXIvaW5kZXgucGhwP2Z1bmM9ZGV0YWlsJmFpZD01MjgwMzEmZ3Jv
dXBfaWQ9MTAzJmF0aWQ9MzAwMTAzDQo+IA0KPiANCj4gU29tZW9uZSBlbHNlIGhhcyBkb25lIHRo
aXMgYWxyZWFkeS4gIEFjdHVhbGx5LCBhdCBsZWFzdCB0d28gcGVvcGxlIGhhdmUNCj4gZG9uZSBp
dCBhbHJlYWR5LiAgRG9oIQ0KPiANCj4gDQo+IEZvcmdpdmUgbWUgZm9yIHJlaW52ZW50aW5nIHRo
ZSB3aGVlbCB5ZXQgYWdhaW4uICAqZ3JpbioNCg==



From gege@nst.pku.edu.cn  Fri Jul 26 07:55:10 2002
From: gege@nst.pku.edu.cn (Ares Liu)
Date: Fri, 26 Jul 2002 14:55:10 +0800
Subject: [Tutor] A question about Mailman soft.
References: <Pine.LNX.4.44.0207251300030.6325-100000@hkn.eecs.berkeley.edu>
Message-ID: <005001c23471$6791c370$8300a8c0@jadeite.com>

VGhhbmsgZm9yIHlvdXIgaGVscC4NCg0KSSBjaGVja2VkIHRoZSBhcmNoaXZlIG1haWwgb24gbWFp
bG1hbiBsaXN0LiBTb21lIG9uZSBoYWQgZGlzY3Vzc2VkIHRoaXMgcXVlc3Rpb24gYmVmb3JlLiBU
aGUgcmVhc29uIGlzIGlmIEkgdXNlIG5vIEVuZ2xpc2ggd29yZHMgaW4gdGhlIFN1YmplY3QgTGlu
ZSwgVGhlIGxhbmd1YWdlIGNvZGUgbWFya2VyIHdpbGwgYWRkZWQgaW4gZm9ybnQgb2YgIlJlOiJh
bmQgZW5jb2RpbmcgdGhlIFN1YmplY3QgYXMgc3RoIGxpa2UgIj0/Z2IyMzEyP0IyeHh4eHh4eHg/
PSIuIEl0IGlzIHN1cmVseSB0aGF0IG1haWxtYW4gY291bGQgbm90IHNlYXJjaCBhbnkgcmVwbHkg
a2V5d29yZC4gU28sIGFkZGVkIHByZWZpeCBhZ2Fpbi4gDQoNCkp1c3Qgbm93LCBJIHNlbmQgYSB0
ZXN0IG1haWwgdG8gaGVyZS4gc3ViamVjdCBsaWtlIHRoaXM6ICJSZTogW1R1dG9yXSAodHdvIGNo
aW5lc2Ugd29yZHMpIGZvciB0ZXN0IHBscyBpZ25vcmUiIC4gV2hhdCBJIHJlY2VpdmVkIGlzIGFk
ZGVkIGFkZGl0aW9uYWwgcHJlZml4IGFzIHlvdSd2ZSBzZWVuLiANCi0tLS0tIE9yaWdpbmFsIE1l
c3NhZ2UgLS0tLS0gDQpGcm9tOiAiRGFubnkgWW9vIiA8ZHlvb0Boa24uZWVjcy5iZXJrZWxleS5l
ZHU+DQpUbzogIkFyZXMgTGl1IiA8Z2VnZUBuc3QucGt1LmVkdS5jbj4NCkNjOiA8dHV0b3JAcHl0
aG9uLm9yZz4NClNlbnQ6IEZyaWRheSwgSnVseSAyNiwgMjAwMiA0OjI1IEFNDQpTdWJqZWN0OiBS
ZTogW1R1dG9yXSBBIHF1ZXN0aW9uIGFib3V0IE1haWxtYW4gc29mdC4NCg0KDQo+IA0KPiANCj4g
T24gVGh1LCAyNSBKdWwgMjAwMiwgQXJlcyBMaXUgd3JvdGU6DQo+IA0KPiA+IEkgaW5zdGFsbGVk
IG1haWxtYW4gc29mdCBmb3IgbWFpbGluZyBsaXN0IG9uIG15IGJveCwgYW5kIG1ha2UgYSBuZXcg
bGlzdA0KPiA+IG5hbWVkIGFzIHRlc3QuIFdoZW4gSSBkbyBzb21lIGNvbmZpZ3VyYXRpb24gb2Yg
dGVzdCBsaXN0IGFzIHRlc3QNCj4gPiBBZG1pbmlzdHJhdGlvbiwgSSBtZXQgYSBxdWVzdGlvbiBh
Ym91dCBQcmVmaXggZm9yIHN1YmplY3QgbGluZSBvZiBsaXN0DQo+ID4gcG9zdGluZ3MuIEluIHRo
ZSBPcHRpb24gb2YgIlByZWZpeCBmb3Igc3ViamVjdCBsaW5lIG9mIGxpc3QgcG9zdGluZ3MiLCBJ
DQo+ID4gZmlsbCBpbiAiW1Rlc3RdICIuIHRoZW4gSSBjYW4gcmVjZWl2ZSBhIG1haWwgdGhhdCBz
dWJqZWN0ZWQgYXMgIltUZXN0XQ0KPiA+IFRoaXMgaXMgbXkgdGVzdC4iIHZpYSBNUyBvdXRsb29r
IGV4cHJlc3MuIFdoZW4gSSBwcmVzcyBSZXBseSBidXR0b24gb24NCj4gPiBvdXRsb29vayBleHBy
ZXNzLCB0aGUgc3ViamVjdCBhcHBlYXIgYXMgIlJlOiBbVGVzdF0gVGhpcyBpcyBteSB0ZXN0LiIu
DQo+ID4gU2VuZCBpdC4gV2hlbiBJIHJlY2VpdmUgaXQgYWdhaW4gZnJvbSBtYWlsaW5nIGxpc3Qu
IFRoZSBzdWJqZWN0IGJlY29tZQ0KPiA+IGFzICJbVGVzdF0gUmU6IFtUZXN0XSBUaGlzIGlzIG15
IHRlc3QuIi4gSXQgaXMgbm90IHNvIGdvb2QuIEFzIEkga25vdywNCj4gPiBQeXRob24gVHV0b3Ig
YWxzbyB1c2UgTWFpbG1hbiBhcyBpdHMgbWFpbGluZyBsaXN0IHNvZnQsIGFuZCBhbHNvIGFkZA0K
PiA+IHByZWZpeCBbVHV0b3JdIHRvIHN1YmplY3QgbGluZS4gQnV0IGl0IGRvZXNuJ3QgYWRkIHBy
ZWZpeCBbVHV0b3JdIGFnYWluDQo+ID4gb24gc3ViamVjdCB3aGljaCBsaWtlcyAiUmU6IFtUdXRv
cl0gc3RoLiIuIFdobyBjYW4gdGVsbCBtZSBob3cgdG8NCj4gPiBpbXBsZW1lbnQgaXQ/DQo+IA0K
PiANCj4gSGkgQXJlcywNCj4gDQo+IEhtbW0uLi4gdGhpcyBzZWVtcyB2ZXJ5IHNwZWNpZmljIHRv
IE1haWxtYW4sIHNvIHlvdSBtYXkgd2FudCB0byBhc2sgb24gdGhlDQo+IE1haWxtYW4tdXNlcnMg
bWFpbGluZyBsaXN0IGFib3V0IHRoaXMgb25lOg0KPiANCj4gICAgIGh0dHA6Ly9tYWlsLnB5dGhv
bi5vcmcvbWFpbG1hbi9saXN0aW5mby9tYWlsbWFuLXVzZXJzDQo+IA0KPiANCj4gDQo+IEkndmUg
YWx3YXlzIGFzc3VtZWQgdGhhdCB0aGUgY29kZSB0aGF0IHByZXBlbmRlZCB0aGUgbWFpbGluZyBs
aXN0ICJzdWJqZWN0DQo+IHByZWZpeCIgd291bGQgY2hlY2sgdG8gc2VlIGlmIGl0IGFscmVhZHkg
ZXhpc3RlZCBpbiB0aGUgbWVzc2FnZSB0aXRsZS4NCj4gTGV0IG1lIGNoZWNrIGluIHRoZSBzb3Vy
Y2UgY29kZS4uLiAgSSdsbCBsb29rIGluIHRoZSBzb3VyY2UgY29kZSBvZg0KPiBNYWlsbWFuIDIu
MGJldGEyLg0KPiANCj4gDQo+ICMjIw0KPiAkIGdyZXAgLXIgc3ViamVjdF9wcmVmaXggKg0KPiBI
YW5kbGVycy9BY2tub3dsZWRnZS5weTogICAgICAgICAgICBwcmVmaXggPSBtbGlzdC5zdWJqZWN0
X3ByZWZpeA0KPiBIYW5kbGVycy9Db29rSGVhZGVycy5weTogICAgICAgIHByZWZpeCA9IG1saXN0
LnN1YmplY3RfcHJlZml4DQo+IEhhbmRsZXJzL1RvRGlnZXN0LnB5OiAgICBtbyA9IHJlLm1hdGNo
KCcocmU6PyAqKT8oJXMpJyAlDQo+IHJlLmVzY2FwZShtbGlzdC5zdWJqZWN0X3ByZWZpeCksDQo+
IEhhbmRsZXJzL1RvVXNlbmV0LnB5OiAgICBzdWJqcHJlZiA9IG1saXN0LnN1YmplY3RfcHJlZml4
DQo+IE1haWxMaXN0LnB5OiBzZWxmLnN1YmplY3RfcHJlZml4ID0gbW1fY2ZnLkRFRkFVTFRfU1VC
SkVDVF9QUkVGSVggJQ0KPiBzZWxmLl9fZGljdF9fDQo+IE1haWxMaXN0LnB5OiAgICAgKCdzdWJq
ZWN0X3ByZWZpeCcsIG1tX2NmZy5TdHJpbmcsIFdJRFRILCAwLA0KPiAjIyMNCj4gDQo+IA0KPiBB
aCwgSSBzZWUuICBUaGUgY29kZSB0aGF0IGFkZHMgdGhlIHByZWZpeCBpcyBpbiB0aGUNCj4gSGFu
ZGxlcnMuQ29va0hlYWRlcnMucHJvY2VzcygpIGZ1bmN0aW9uLg0KPiANCj4gDQo+IA0KPiBIZXJl
J3MgdGhlIGNodW5rIG9mIGNvZGUgdGhhdCBwdXRzIHRoZSBwcmVmaXggaW4gdGhlIHN1YmplY3Qg
aGVhZGVyOg0KPiANCj4gIyMjDQo+ICAgICAgICAgIyBzdWJqZWN0IGhlYWRlciBhZGRlZCBieSB0
aGUgVG9EaWdlc3QgbW9kdWxlLg0KPiAgICAgICAgIHByZWZpeCA9IG1saXN0LnN1YmplY3RfcHJl
Zml4DQo+ICAgICAgICAgIyB3ZSBwdXJwb3NlZnVsbHkgbGVhdmUgbm8gc3BhY2UgYi93IHByZWZp
eCBhbmQgc3ViamVjdCENCj4gICAgICAgICBpZiBub3Qgc3ViamVjdDoNCj4gICAgICAgICAgICAg
bXNnWydTdWJqZWN0J10gPSBwcmVmaXggKyAnKG5vIHN1YmplY3QpJw0KPiAgICAgICAgIGVsaWYg
cHJlZml4IGFuZCBub3QgcmUuc2VhcmNoKHJlLmVzY2FwZShwcmVmaXgpLCBzdWJqZWN0LCByZS5J
KToNCj4gICAgICAgICAgICAgbXNnWydTdWJqZWN0J10gPSBwcmVmaXggKyBzdWJqZWN0DQo+ICMj
Iw0KPiANCj4gU28sIHllcywgTWFpbG1hbiBzaG91bGQgbm90IGJlIGFkZGluZyB0aGF0IGFkZGl0
aW9uYWwgcHJlZml4IGluIHRoZQ0KPiByZXBsaWVkIG1lc3NhZ2UsIGJlY2F1c2UgTWFpbG1hbiBp
cyBzdXBwb3NlZCB0byBzZWFyY2ggZm9yIGl0IGJlZm9yZQ0KPiBhZGRpbmcgaXQgaW4uICBJdCdz
IHZlcnkgb2RkIHRoYXQgeW91J3JlIHNlZWluZyBkaWZmZXJlbnQgYmVoYXZpb3IuLi4NCj4gDQo+
IA0KPiANCj4gVHJ5IGFza2luZyBvbiB0aGUgTWFpbG1hbiB1c2VycyBsaXN0OyBwZXJoYXBzIHNv
bWVvbmUgdGhlcmUga25vd3Mgb2YgYSBidWcNCj4gb3Igd29ya2Fyb3VuZC4gIEFsc28sIHRlbGwg
dGhlbSB3aGljaCB2ZXJzaW9uIG9mIE1haWxtYW4geW91J3ZlIGluc3RhbGxlZCwNCj4gc28gdGhh
dCBvdGhlciBwZW9wbGUgY2FuIGVmZmVjdGl2ZWx5IGh1bnQgdGhpcyBidWcgZm9yIHlvdS4NCj4g
DQo+IA0KPiBIb3BlIHRoaXMgaGVscHMhDQo=



From alan.gauld@bt.com  Fri Jul 26 12:20:00 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 26 Jul 2002 12:20:00 +0100
Subject: [Tutor] (no subject)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C795@mbtlipnt02.btlabs.bt.co.uk>

> This is the error I get when I try to execute my script:
> Traceback (most recent call last):
>   File "/home/sites/sbn/www/public_html/index.py", line 671, in ?
>     print """
> KeyError: content


You have a try/except with this:
try:
   ....
except KeyError:
   con = ""
   content = con

   if con == "index": 
      #very long if/elif chain here

But this can never be true since you are still 
inside the exception handler(indentation) and 
you have just set con = "" not "index"...

I suspect you need to check the indentation of 
the if statement?

Otherwise content only gets set if a Keyerror occurs
and when you try to print it at the end you get the error...

Also you might find it easier to maintain to put all 
the HTML stuff in separate files and then read it in.

Something like:

if con == "index":
   content = open("index.htm").read()
elif con == "index2):
   content = open("index2.htm").read()
elif....

That splits the maintenance of the HTML/Javacript 
away from maintaining the Python code.

Just a thought,

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld


From Doug.Shawhan@gecits.ge.com  Fri Jul 26 15:42:05 2002
From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com)
Date: Fri, 26 Jul 2002 10:42:05 -0400
Subject: [Tutor] Splitting a string into a list.
Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54CF4@msxcvg02itscge.gecits.ge.com>

I must have misread the question. I thought he meant:

>>> judeanpeoplesfront='this is a string filled with different things that
makes me sing'
>>> peoplesfrontofjudea=frap.split(' ') #splitters!
>>> peoplesfrontofjudea
['this', 'is', 'a', 'string', 'filled', 'with', 'different', 'things',
'that', 'makes', 'me', 'sing']


From alan.gauld@bt.com  Fri Jul 26 12:06:31 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 26 Jul 2002 12:06:31 +0100
Subject: [Tutor] printing columns
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C794@mbtlipnt02.btlabs.bt.co.uk>

> code that produces a header file for a C++ program, but I've 
> got a simple bit of polish I'd like to put on it. 

> >>> menuItems = ['NEW', 'OPEN', 'CLOSE', 'SAVE', 'SAVEAS', 
> ...
> 'CUSTOMTB', 'CASCADE', 'TILE', 'SPLIT']

> >>> myInt = 1
> >>> for item in menuItems:
> 	print '#define ROB_' + item + '\t\t' + str(myInt)
> 	myInt = myInt + 1
> 
> Now I'm wondering how I could do this a little more neatly, 
> organizing the output into two columns. 

Doesn't your two tabs do exactly that? The other way of 
course would be to create a format string with fixed 
length fields...


The other issue of course is why you are using #defines 
in a C++ program? Surely const would be better?

Or since you are assigning a series of integer values 
use an enum which will do that automatically.

enum codes {NEW=1,
           OPEN,  // automatically assigned 2 etc...
           ...
           TILE,
           SPLIT};

Saves a mite of typing and you can now add new values
easily without worrying about maintaining the numeric 
values etc. And its typesafe, nobody can kid the compiler 
by passing a raw integer pretending to be a code to a 
function which expects a code as input...

Altogether safer and more idiomatic C++.

Alan G.


From alan.gauld@bt.com  Fri Jul 26 14:21:27 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 26 Jul 2002 14:21:27 +0100
Subject: [Tutor] printing columns
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C799@mbtlipnt02.btlabs.bt.co.uk>

 
> Hmmm... this is a little tricky, just because tab spacing can be
> potentially different on other systems; a potential solution 
> should use spaces instead to guarantee that things look 
> correct on all systems.
> def layoutColumns(columns1, columns2, spacing=8):
>     width_of_first_column = max([len(c) + spacing for c in columns1])
>     lines = []
>     for col1, col2 in zip(columns1, columns2):
>         lines.append(col1
>                      + " " * (width_of_first_column - len(col1))
>                      + col2)
>     return lines

Or use format strings:

fmt = "#define %20s\t%3d"

Or similar...

Alan G.



From alan.gauld@bt.com  Fri Jul 26 14:18:28 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 26 Jul 2002 14:18:28 +0100
Subject: [Tutor] Newbie Question Again
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C798@mbtlipnt02.btlabs.bt.co.uk>

>  We have only studied the While and the If statements so far.   
>  We haven't studied lists yet.

# Modify the password guessing program to keep track of 
# ...If it is more than 3 times, print "That must have 
# been complicated."

Password.py
> password = "foobar"
count = 0 # initialise to zero
> while (password != "unicorn") \
        and (count < 3):   # did you do compound expressions yet?

>     password = raw_input("Password:")

      count = count + 1  # add one each time round the loop

if count == 3: # we ran out of guesses
    print "That must have been complicated"
else: # we must have guessed it

>   print "Welcome in"

> I don't understand how to count the users input
Just increment a counter inside the loop
You effectively count the number of iterations rather 
than the number of guesses, but since we only have 
one guess per iteration thats OK...

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld@bt.com  Fri Jul 26 16:53:56 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 26 Jul 2002 16:53:56 +0100
Subject: [Tutor] printing columns
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C79A@mbtlipnt02.btlabs.bt.co.uk>

> Using the two tabs does create two columns after a fashion, 
> they're just not evenly laid out. 

OK, so use the format string trick...

> As far as using #define instead of const, these are 
> preprocessor directives in a header file for a 
> Windows GUI in a class dedicated simultaneously to
> the Win32 API and to more advanced OOP concepts in C++ 

I guessed they were Windows message IDs or somesuch.
But the use of an enum is stiill preferable sonce the 
enum items translate directly to the same ints you 
have in the #define.

For the Win API stuff they are treaded as ints, for 
the C++ stuff they are typechecked...


> The instructor wants to see it coded this way. 

Ah well, we can't do much about the instructors ;-)

> ... but the header file consists of
> nothing but this list of #define statements. 
> This is then included in a .rc resource file.

That might make a difference, I can't remember how
resource file compilers work but they may well use the 
same syntax as the preprocessor #define in which 
case you do need to use it. Bummer!

Alan g.


From fgranger@altern.org  Fri Jul 26 16:42:12 2002
From: fgranger@altern.org (Francois Granger)
Date: Fri, 26 Jul 2002 17:42:12 +0200
Subject: [Tutor] os.rename() on Win 98
Message-ID: <a05100300b9671c9a90c2@[192.168.1.11]>

I got serious difficulties with something apparently  simple. so I 
simplified it to trace it back as follow.

I have the following script:

=================================================Start
def saveWithBackup(data, fileName, backup = 2):
     import os
     dir,file = os.path.split(fileName)
     parts = file.split('.')
     i = 0
     #filebak = os.path.join(dir, '.'.join(parts[0:-1]) + '.bak')
     filebak = os.path.join(dir, 
parts[0]+str(i)+'.'+'.'.join(parts[1:-1])+'.bak')
     os.rename(fileName, filebak)

fileName = 'default.fr.txt'
fp = open(fileName)
data = fp.read()
fp.close
result = saveWithBackup(data, fileName, backup = 2)
print result
=================================================End

It runs fine on a Mac with MacOS 9

I run it on Windows 98: transcript of the dos session follows.

=================================================Start
C:\toto>dir

  Le volume dans le lecteur C est REALPC
  Le numÈro de sÈrie du volume est F400-4086
  RÈpertoire de C:\toto

.              <REP>        26/07/02  17:00 .
..             <REP>        26/07/02  17:00 ..
DEFAUL~1 BAK        16 908  26/07/02  11:19 default.fr.bak
DEFAUL~1 TXT        16 908  26/07/02  11:27 default.fr.txt
SAVE     PY          1 456  26/07/02  16:44 save.py
SAVE1    PY            474  26/07/02  17:14 save1.py
          4 fichier(s)             35 746 octets
          2 rÈpertoire(s)     690 978 816 octets libres

C:\toto>c:\Python22\python save1.py
Traceback (most recent call last):
   File "save1.py", line 14, in ?
     result = saveWithBackup(data, fileName, backup = 2)
   File "save1.py", line 8, in saveWithBackup
     os.rename(fileName, filebak)
OSError: [Errno 13] Permission denied

C:\toto>
=================================================End

Not understanding what is happening, I created a simple brute force 
rename wich works.

def rename(a,b):
     data = open(a, 'rb').read()
     open(b, 'wb').write(data)

My guess is that os.rename() does not handle properly the long name 
to short name under W98 because the filebak name I creat would 
produce the same short name as the one already existing ?????



From tutor@python.org  Fri Jul 26 17:25:56 2002
From: tutor@python.org (Tim Peters)
Date: Fri, 26 Jul 2002 12:25:56 -0400
Subject: [Tutor] os.rename() on Win 98
In-Reply-To: <a05100300b9671c9a90c2@[192.168.1.11]>
Message-ID: <LNBBLJKPBEHFEDALKOLCIELHAHAB.tim.one@comcast.net>

[Francois Granger]
> I got serious difficulties with something apparently  simple. so I
> simplified it to trace it back as follow.
>
> I have the following script:
>
> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3DStart
> def saveWithBackup(data, fileName, backup =3D 2):
>      import os
>      dir,file =3D os.path.split(fileName)
>      parts =3D file.split('.')
>      i =3D 0
>      #filebak =3D os.path.join(dir, '.'.join(parts[0:-1]) + '.bak')
>      filebak =3D os.path.join(dir,
> parts[0]+str(i)+'.'+'.'.join(parts[1:-1])+'.bak')
>      os.rename(fileName, filebak)
>
> fileName =3D 'default.fr.txt'
> fp =3D open(fileName)
> data =3D fp.read()
> fp.close

Note that you didn't close the file here:  you want fp.close() instea=
d.
Windows will not allow you to delete or rename a file that's still op=
en.
That's deep in the operating system, and there's nothing Python can d=
o about
that.


> result =3D saveWithBackup(data, fileName, backup =3D 2)
> print result
> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3DEnd
>
> It runs fine on a Mac with MacOS 9
>
> I run it on Windows 98: transcript of the dos session follows.
>
> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3DStart
> C:\toto>dir
>
>   Le volume dans le lecteur C est REALPC
>   Le num=C8ro de s=C8rie du volume est F400-4086
>   R=C8pertoire de C:\toto
>
> .              <REP>        26/07/02  17:00 .
> ..             <REP>        26/07/02  17:00 ..
> DEFAUL~1 BAK        16 908  26/07/02  11:19 default.fr.bak
> DEFAUL~1 TXT        16 908  26/07/02  11:27 default.fr.txt
> SAVE     PY          1 456  26/07/02  16:44 save.py
> SAVE1    PY            474  26/07/02  17:14 save1.py
>           4 fichier(s)             35 746 octets
>           2 r=C8pertoire(s)     690 978 816 octets libres
>
> C:\toto>c:\Python22\python save1.py
> Traceback (most recent call last):
>    File "save1.py", line 14, in ?
>      result =3D saveWithBackup(data, fileName, backup =3D 2)
>    File "save1.py", line 8, in saveWithBackup
>      os.rename(fileName, filebak)
> OSError: [Errno 13] Permission denied

That's the usual error you get from Windows if you try to delete or r=
ename a
file that's still open.

> C:\toto>
> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3DEnd
>
> Not understanding what is happening, I created a simple brute force
> rename wich works.
>
> def rename(a,b):
>      data =3D open(a, 'rb').read()
>      open(b, 'wb').write(data)
>
> My guess is that os.rename() does not handle properly the long name
> to short name under W98 because the filebak name I creat would
> produce the same short name as the one already existing ?????

That shouldn't be an issue.  The Windows "short name" business is
certifiably insane, but Windows creates unique short names "by magic"=
 as
needed.  For example,

C:\Code>echo test > abcdefghijklmnop

C:\Code>echo test > abcdefghijklmnopq

C:\Code>dir abc*

ABCDEF~1                 7  07-26-02 12:21p abcdefghijklmnop
ABCDEF~2                 7  07-26-02 12:22p abcdefghijklmnopq

C:\Code>rename abcdefghijklmnop abcdefghij

C:\Code>dir abc*
ABCDEF~2                 7  07-26-02 12:22p abcdefghijklmnopq
ABCDEF~3                 7  07-26-02 12:21p abcdefghij

Windows stuffs "~" and an integer onto the end of the short names it
generates, trying bigger and bigger integers until it gets a unique s=
hort
name.  The mapping from long name to short name thus depends on the n=
ames of
the files that already exist!  As I said, it's certifiably insane <wi=
nk>.




From sarmstrong13@mac.com  Fri Jul 26 17:47:38 2002
From: sarmstrong13@mac.com (SA)
Date: Fri, 26 Jul 2002 11:47:38 -0500
Subject: [Tutor] Newbie Help on reading files.
Message-ID: <B966E75A.A012%sarmstrong13@mac.com>

Hi Everyone-

I would like to read a text file that has multiple lines like the following:

# filewho: to show file system usage (to see what is causing disk activity)
alias filewho 'sudo fs_usage'


I would like it to ignore all lines beginning with pound. I would then like
it to it to break up the alias lines ,there are only three items, into:
alias
command
''

I would then do work on each of the three items in the alias line
individually.


Would I need to use the re module or is there a better way to do this?


Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me



From dyoo@hkn.eecs.berkeley.edu  Fri Jul 26 10:39:01 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 26 Jul 2002 02:39:01 -0700 (PDT)
Subject: [Tutor] List initialisation
In-Reply-To: <3D40E958.DBAD3D2B@epfl.ch>
Message-ID: <Pine.LNX.4.44.0207260235510.28744-100000@hkn.eecs.berkeley.edu>


On Fri, 26 Jul 2002, Guillermo Fernandez wrote:

> I've been trying to initialise a list containing a number 'size' of
> zeros. After looking in the doc and tutorials, I've done it like this:
>
> def zero(x): return 0
> list=map(zero, range(0,size))

Hi Guillermo,

Here's an alterative way of making a presized list:

    mylist = [0] * size


By the way, be careful about using the name 'list' as a variable name ---
there's a very useful builtin function named 'list()' already, and it's
not usually a good idea to mask it.  Other ones to try avoid are things
like 'int', 'float', and 'range'.


If you have more questions, please feel free to ask.  Good luck!



From dyoo@hkn.eecs.berkeley.edu  Fri Jul 26 10:32:49 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 26 Jul 2002 02:32:49 -0700 (PDT)
Subject: [Tutor] A question about Mailman soft.  [hacking Mailman for
 fun and profit]
In-Reply-To: <Pine.LNX.4.44.0207260128400.27692-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0207260226160.27692-100000@hkn.eecs.berkeley.edu>


On Fri, 26 Jul 2002, Danny Yoo wrote:

> [Note: I'm CC'ing mailman-users as this might be useful for them.
> Hopefully, they'll correct my hack by telling me the right way to do
> this. *grin*]
>
>
>
> On Fri, 26 Jul 2002, Ares Liu wrote:
>
> > I checked the archive mail on mailman list. Some one had discussed this
> > question before.
>
> Do you have a link to that archived message?  I'm interested in looking at
> this, just for curiosity's sake.


Oh.

http://sourceforge.net/tracker/index.php?func=detail&aid=498766&group_id=103&atid=300103
http://sourceforge.net/tracker/index.php?func=detail&aid=528031&group_id=103&atid=300103


Someone else has done this already.  Actually, at least two people have
done it already.  Doh!


Forgive me for reinventing the wheel yet again.  *grin*



From dyoo@hkn.eecs.berkeley.edu  Fri Jul 26 10:22:16 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 26 Jul 2002 02:22:16 -0700 (PDT)
Subject: [Tutor] A question about Mailman soft.  [hacking Mailman for
 fun and profit]
In-Reply-To: <005001c23471$6791c370$8300a8c0@jadeite.com>
Message-ID: <Pine.LNX.4.44.0207260128400.27692-100000@hkn.eecs.berkeley.edu>

[Note: I'm CC'ing mailman-users as this might be useful for them.
Hopefully, they'll correct my hack by telling me the right way to do this.
*grin*]



On Fri, 26 Jul 2002, Ares Liu wrote:

> I checked the archive mail on mailman list. Some one had discussed this
> question before.

Do you have a link to that archived message?  I'm interested in looking at
this, just for curiosity's sake.




> The reason is if I use no English words in the Subject Line, The
> language code marker will added in fornt of "Re:"and encoding the
> Subject as sth like "=?gb2312?B2xxxxxxxx?=".

Yes, it looks like it wraps it in some kind of encoding... utf-8?  I wish
I knew more about Unicode.



> It is surely that mailman could not search any reply keyword. So, added
> prefix again.


I think I understand better now.  The problem is that the encoding leaves
many of the characters alone, but transforms the braces in:

    '[Tutor]'

to something like:

    '=5BTutor=5D'

I'm guessing this because 0x5b and 0x5D are the ascii codes for braces:

###
>>> chr(0x5b)
'['
>>> chr(0x5d)
']'
###



Hmmmm.  Wait.  I've seen these characters before.  Is this MIME encoding?
MIME encoding is often used in representing language strings in email
because almost all systems can handle it.

###
>>> def mydecode(s):
...     outputfile = StringIO.StringIO()
...     mimetools.decode(StringIO.StringIO(s), outputfile,
'quoted-printable')
...     return outputfile.getvalue()
...
>>> mydecode('=5BTutor=5D')
'[Tutor]'
###

Ah ha!  It looks like it!  Good!



In this case, maybe we can extend that check in
Handlers.CookHeaders.process() to take this particular encoding into
consideration: if we decode the header back to normal, then the prefix
check will work.



If you're feeling adventurous, and if you're comfortable editing Python,
you can add this file, 'quoted_printable_decoder.py' in the
'Mailman/Handlers/' directory of Mailman:

######
## quoted_printable_decoder.py

import StringIO, mimetools
def decode_quoted_printable(s):
    """Given a mime 'quoted-printable' string s, returns its decoding.
If anything bad happens, returns s."""
    try:
        outputfile = StringIO.StringIO()
        mimetools.decode(StringIO.StringIO(s), outputfile,
                         'quoted-printable')
        return outputfile.getvalue()
    except:
        return s
###

This new module will convert the header and change all the '=5B' and '=5D'
characters back into braces if it can do so safely.  We'll be using it in
a moment.




Once you've added this module, within the same directory, let's modify
CookHeaders.py to use this function.

And make backups, because I have not tested this yet!  *grin*



Add at the top of the CookHeaders module:

###
from quoted_printable_decoder import decode_quoted_printable
###

so that Cookheaders knows about our new function.  Finally, modify the
check in the Cookheaders.process() function:

###
        elif prefix and not re.search(re.escape(prefix), subject, re.I):
###


into:

###
        elif prefix\
             and not re.search(re.escape(prefix), subject, re.I)\
             and not re.search(re.escape(prefix),
                               decode_quoted_printable(subject), re.I)
###


I've modified the logic to include the prefix check on the decoded subject
header.  Ares, if this works, I'll send the patch over to the Mailman
folks.  Who knows; it might be useful for someone else out there.  *grin*



Best of wishes to you!



From terjeja@hotmail.com  Fri Jul 26 20:43:13 2002
From: terjeja@hotmail.com (Terje Johan Abrahamsen)
Date: Fri, 26 Jul 2002 19:43:13 +0000
Subject: [Tutor] Self
Message-ID: <F204Z9rWjAKYVpMmOlb00000133@hotmail.com>

How does really the self thing work?

Will these two examples actually work the same way, and is the only reason 
why one would use self is so one don't have to write the class name again 
and again?

class smurf:
    variable = 15

    def write(self):
        smurf.variable = smurf.variable + 1
        print smurf.variable

and:

class smurf:
    variable = 15

    def write(self):
        self.variable = self.variable + 1
        print self.variable

Is there any reason why to use the first over the second or opposite? And, 
in the first one, why do I have to write the self in 'def write(self):', or 
don't I have to?

Thanks in advance,
Terje

_________________________________________________________________
MSN Photos is the easiest way to share and print your photos: 
http://photos.msn.com/support/worldwide.aspx



From cmhowe@patriot.net  Fri Jul 26 21:33:01 2002
From: cmhowe@patriot.net (Charles M Howe)
Date: Fri, 26 Jul 2002 16:33:01 -0400
Subject: [Tutor] Subscribing; Colorizing print
Message-ID: <3D41B1FD.B449E16C@patriot.net>

(1) Is it appropriate to subscribe to this mailing list? If so, how do I
do so?

(2) Is it possible to do printing in colors?

Charlie -- Charles M Howe




From rob@uselesspython.com  Fri Jul 26 21:03:05 2002
From: rob@uselesspython.com (Rob)
Date: Fri, 26 Jul 2002 15:03:05 -0500
Subject: [Tutor] Subscribing; Colorizing print
In-Reply-To: <3D41B1FD.B449E16C@patriot.net>
Message-ID: <MPEOIFCOPCIHEDCLBLPBIEDACBAA.rob@uselesspython.com>

If you receive this reply, it would appear you are most definitely
subscribed to the list. It's appropriate to subscribe if you are learning or
considering learning about python programming (or if you are already
knowledgeable and would like to help others, of course).

Can you fill in a few more details on your printing question?

Rob
http://uselesspython.com

> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Charles M Howe
> Sent: Friday, July 26, 2002 3:33 PM
> To: tutor@python.org
> Subject: [Tutor] Subscribing; Colorizing print
>
>
> (1) Is it appropriate to subscribe to this mailing list? If so, how do I
> do so?
>
> (2) Is it possible to do printing in colors?
>
> Charlie -- Charles M Howe
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From shalehperry@attbi.com  Fri Jul 26 21:20:55 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 26 Jul 2002 13:20:55 -0700 (PDT)
Subject: [Tutor] Self
In-Reply-To: <F204Z9rWjAKYVpMmOlb00000133@hotmail.com>
Message-ID: <XFMail.20020726132055.shalehperry@attbi.com>

On 26-Jul-2002 Terje Johan Abrahamsen wrote:
> How does really the self thing work?
> 
> Will these two examples actually work the same way, and is the only reason 
> why one would use self is so one don't have to write the class name again 
> and again?
> 
> class smurf:
>     variable = 15
> 
>     def write(self):
>         smurf.variable = smurf.variable + 1
>         print smurf.variable
> 

'variable' in this case belongs to the *CLASS* not the *INSTANCE*.

>>> s = smurf()
>>> other = smurf()
>>> s.write()
16
>>> other.write()
17


this is why smurf.variable works.  You are referencing a global class variable.

> and:
> 
> class smurf:
>     variable = 15
> 
>     def write(self):
>         self.variable = self.variable + 1
>         print self.variable
> 
> Is there any reason why to use the first over the second or opposite? And, 
> in the first one, why do I have to write the self in 'def write(self):', or 
> don't I have to?
> 

since self will refer to an instance of class this works just like above. 
However:

class smurf:
  def __init__(self):
    self.variable = 15

  def write(self):
    smurf.variable = smurf.variable + 1
    print smurf.variable

will fail.  You need to define 'write' as:

def write(self):
  self.variable = self.variable + 1
  print self.variable

and now

s = smurf()
s.write()
16
other = smurf()
other.write()
16


From dyoo@hkn.eecs.berkeley.edu  Fri Jul 26 21:32:27 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 26 Jul 2002 13:32:27 -0700 (PDT)
Subject: [Tutor] Self
In-Reply-To: <F204Z9rWjAKYVpMmOlb00000133@hotmail.com>
Message-ID: <Pine.LNX.4.44.0207261257200.7955-100000@hkn.eecs.berkeley.edu>


On Fri, 26 Jul 2002, Terje Johan Abrahamsen wrote:

> How does really the self thing work?

We can think of 'self' as the instance itself: we often use it as a
container to save our "own" state.



> Will these two examples actually work the same way, and is the only
> reason why one would use self is so one don't have to write the class
> name again and again?
>
> class smurf:
>     variable = 15
>
>     def write(self):
>         smurf.variable = smurf.variable + 1
>         print smurf.variable
>
> and:
>
>
> class smurf:
>     variable = 15
>
>     def write(self):
>         self.variable = self.variable + 1
>         print self.variable

No, they actually have subtly different behavior: the first will always
use the class's understanding of 'variable'.  So the write() method on a
smurf will always use the 'smurf.variable' to display.


The second case behaves like the first... at least initially, that is. As
soon as we call the write() method, the picture changes because of the
assignment to 'self.variable'.  From that point onward, a smurf instance's
idea of 'variable' diverges from the class --- it becomes part of the
individual instance's identity.



Let's do some stuff in the interpreter just to show what's going on with
the second smurf definition, because the second version is subtly tricky!
First, let's create two smurfs.

###
>>> papa = smurf()
>>> hefty = smurf()
>>> papa.variable
15
>>> hefty.variable
15
###

At the moment, both smurfs don't themselves have a customized 'variable'
in themselves, so they look up to the class's 'variable'.  Sorta like how
children look up to parents.

Any changes to the classes 'variable' will appear to affect 'papa' and
'hefty':

###
>>> smurf.variable = 42
>>> papa.variable
42
>>> hefty.variable
42
###


However, as soon as some instance assigns to itself, to it's
'self.variable', it becomes rebellious.  Hefty doesn't want to have his
'variable' tied up with that of all the smurfs: he wants independence, so
he keeps his own 'variable' close to his heart.

###
>>> hefty.variable = 'heart'
>>> papa.variable
42
>>> hefty.variable
'heart'
###


So 'self' is actually meant to keep the individual's state of mind: it's
meant to be able to distinguish instances from each other, while the class
definition tells us what the instances have in common.  That's how we can
distinguish the difference between 'smurf.variable' and 'hefty.variable'.


Hope this helps!



From ak@silmarill.org  Fri Jul 26 21:42:16 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 26 Jul 2002 16:42:16 -0400
Subject: [Tutor] Newbie Help on reading files.
In-Reply-To: <B966E75A.A012%sarmstrong13@mac.com>
References: <B966E75A.A012%sarmstrong13@mac.com>
Message-ID: <20020726204215.GA4077@ak.silmarill.org>

On Fri, Jul 26, 2002 at 11:47:38AM -0500, SA wrote:
> Hi Everyone-
> 
> I would like to read a text file that has multiple lines like the following:
> 
> # filewho: to show file system usage (to see what is causing disk activity)
> alias filewho 'sudo fs_usage'
> 
> 
> I would like it to ignore all lines beginning with pound. I would then like
> it to it to break up the alias lines ,there are only three items, into:
> alias
> command
> ''
> 
> I would then do work on each of the three items in the alias line
> individually.
> 
> 
> Would I need to use the re module or is there a better way to do this?

No re, split.. if line.strip().startswith('#'): continue
then split the rest and word[0] will be 'alias', word[1] will be
filewho and then the rest will be 'sudo fs_usage'

> 
> 
> Thanks.
> SA
> 
> 
> -- 
> "I can do everything on my Mac I used to on my PC. Plus a lot more ..."
> -Me
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org


From ak@silmarill.org  Fri Jul 26 21:45:54 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 26 Jul 2002 16:45:54 -0400
Subject: [Tutor] Self
In-Reply-To: <F204Z9rWjAKYVpMmOlb00000133@hotmail.com>
References: <F204Z9rWjAKYVpMmOlb00000133@hotmail.com>
Message-ID: <20020726204554.GB4077@ak.silmarill.org>

On Fri, Jul 26, 2002 at 07:43:13PM +0000, Terje Johan Abrahamsen wrote:
> How does really the self thing work?
> 
> Will these two examples actually work the same way, and is the only reason 
> why one would use self is so one don't have to write the class name again 
> and again?
> 
> class smurf:
>    variable = 15
> 
>    def write(self):
>        smurf.variable = smurf.variable + 1
>        print smurf.variable
> 
> and:
> 
> class smurf:
>    variable = 15
> 
>    def write(self):
>        self.variable = self.variable + 1
>        print self.variable

These are not the same - smurf is the name of class; self refers to
instance. For example, a class may be "tree" and instance may be
"willow in my back yard". Setting my_willow.alive = 0 will kill your
willow, setting tree.alive = 0 is gonna kill all trees on earth. 

> 
> Is there any reason why to use the first over the second or opposite? And, 
> in the first one, why do I have to write the self in 'def write(self):', or 
> don't I have to?

You have to..

>
> 
> Thanks in advance,
> Terje
> 
> _________________________________________________________________
> MSN Photos is the easiest way to share and print your photos: 
> http://photos.msn.com/support/worldwide.aspx
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org


From ak@silmarill.org  Fri Jul 26 21:46:39 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 26 Jul 2002 16:46:39 -0400
Subject: [Tutor] Subscribing; Colorizing print
In-Reply-To: <3D41B1FD.B449E16C@patriot.net>
References: <3D41B1FD.B449E16C@patriot.net>
Message-ID: <20020726204639.GC4077@ak.silmarill.org>

On Fri, Jul 26, 2002 at 04:33:01PM -0400, Charles M Howe wrote:
> (1) Is it appropriate to subscribe to this mailing list? If so, how do I
> do so?
> 
> (2) Is it possible to do printing in colors?

Printing in GUI or windows or unix terminal?

> 
> Charlie -- Charles M Howe
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org


From fgranger@altern.org  Fri Jul 26 21:33:17 2002
From: fgranger@altern.org (Francois Granger)
Date: Fri, 26 Jul 2002 22:33:17 +0200
Subject: [Tutor] os.rename() on Win 98
In-Reply-To: <LNBBLJKPBEHFEDALKOLCIELHAHAB.tim.one@comcast.net>
References: <LNBBLJKPBEHFEDALKOLCIELHAHAB.tim.one@comcast.net>
Message-ID: <a05100306b9676258f39a@[192.168.1.11]>

At 12:25 -0400 on 26/07/02, in message RE: [Tutor] os.rename() on Win 
98, Tim Peters wrote:
>[Francois Granger]
>  > fp.close
>
>Note that you didn't close the file here:  you want fp.close() instead.

I knew it was stupid. I was wrong. I am stupid.

Thanks a lot.



From tutor@python.org  Fri Jul 26 21:59:17 2002
From: tutor@python.org (Tim Peters)
Date: Fri, 26 Jul 2002 16:59:17 -0400
Subject: [Tutor] os.rename() on Win 98
In-Reply-To: <a05100306b9676258f39a@[192.168.1.11]>
Message-ID: <LNBBLJKPBEHFEDALKOLCKENEAHAB.tim.one@comcast.net>

[Tim]
> Note that you didn't close the file here:  you want fp.close() instead.

[Francois Granger]
> I knew it was stupid. I was wrong. I am stupid.

Not as stupid as me.  I'm currently working on a high-powered replacement
for Python's list.sort() routine, and within the last week I created at
least 50 errors in the C code severe enough to crash my machine.  It's
called being human <wink>.

> Thanks a lot.

You're weclome, Francois -- *everyone* makes a "function" versus
"function()" mistake sooner or later.  You're only stupid if you do it twice
<wink>.



From dyoo@hkn.eecs.berkeley.edu  Fri Jul 26 22:02:59 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 26 Jul 2002 14:02:59 -0700 (PDT)
Subject: [Tutor] Subscribing; Colorizing print
In-Reply-To: <MPEOIFCOPCIHEDCLBLPBIEDACBAA.rob@uselesspython.com>
Message-ID: <Pine.LNX.4.44.0207261332330.7955-100000@hkn.eecs.berkeley.edu>


On Fri, 26 Jul 2002, Rob wrote:

> If you receive this reply, it would appear you are most definitely
> subscribed to the list.

Actually, he's not subscribed yet.  Charles, if you visit this URL:

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

you can subscribe to Tutor.


Best of wishes to you!



From rseguin@shaw.ca  Fri Jul 26 22:30:43 2002
From: rseguin@shaw.ca (Richard Seguin)
Date: Fri, 26 Jul 2002 17:30:43 -0400
Subject: [Tutor] (no subject)
Message-ID: <200207261730.43335.rseguin@shaw.ca>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hey does anyone out there have any ideas for projects?  Im sitting way up here 
in the middle of no where (Canada) and have this awsome programming language 
that I am trying to learn.... but can't think of anything to do with it....

Rich
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)

iD8DBQE9Qb+Dn9670YZTFEcRAs4WAJ953TdcW3zcQabNxTbaRl1WAC4h3QCgiFuO
59a0ATkHaPArlISZ8fWhsQ0=
=Fo3H
-----END PGP SIGNATURE-----



From billintucson@yahoo.com  Sat Jul 27 02:42:50 2002
From: billintucson@yahoo.com (Bill Gillespie)
Date: Fri, 26 Jul 2002 18:42:50 -0700 (PDT)
Subject: [Tutor] Newbie termios setup help for serial line opening.
Message-ID: <20020727014250.57804.qmail@web11801.mail.yahoo.com>

Hi Folks,

I'm trying to open a serial line on a SunOs using python 2.2.
I'm new to programming, and fairly new to unix/linux. I have the two
pink Oreilly Python books and have read a couple of tutorials - but I
am a newbie.

I've done several hours of google searches on serial comms and the set
up and opening of serial lines in unix - based on those serches - this
is what I think I should be doing....

-----------------------
1) Open the serial line
-----------------------
I do the following:

 >>>    import os
 >>>    os.open('/dev/ttyC43', 0600)

Question: is the line actually open now?

No exceptions are raised - but I do not believe the line is
actually open - as I can open it via another terminal with
a tip command to the controller that uses the line.

Question: what is the 0600 integer value and what is it for?

---------------------------------------------------------------
2.) Next I've read that I have to set up the line using termios.
---------------------------------------------------------------
If this is correct -
Can someone possibly walk me through the basics of setting up termios
for
a serial line that I just want to read ASCII characters off - and write
ASCII charachters to?



Some supplemental notes:

The serial line accesses a controller that controls two other devices.
The normal way to interact with the controller is to use the commands:

  sun> tip oftc

That sets up the communication so taht you can ask the device for
current settings and change them if you like. This is a first
programming project for me at work, and what I am trying to do is build
a program that will allow you to pop open a gui - and it will query
these settings and allow you to simply place new settings into a
dialogue box - or select them from a pull down menu.

Bill


__________________________________________________
Do You Yahoo!?
Yahoo! Health - Feel better, live better
http://health.yahoo.com


From yduppen@xs4all.nl  Sat Jul 27 09:41:43 2002
From: yduppen@xs4all.nl (Yigal Duppen)
Date: Sat, 27 Jul 2002 10:41:43 +0200
Subject: [Tutor] (no subject)
In-Reply-To: <200207261730.43335.rseguin@shaw.ca>
References: <200207261730.43335.rseguin@shaw.ca>
Message-ID: <200207271041.46267.yduppen@xs4all.nl>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Friday 26 July 2002 23:30, Richard Seguin wrote:
> Hey does anyone out there have any ideas for projects?  Im sitting way up
> here in the middle of no where (Canada) and have this awsome programming
> language that I am trying to learn.... but can't think of anything to do
> with it....

Well, you can get a good headstart by toying around with the ACM Programming 
Contests. Since they are mainly about difficult _algorithms_ (as opposed to 
datastructures or just vast amounts of work), Python just seems to be the 
most logical choice.

http://acm.uva.es/cgi-bin/OnlineJudge?Volume:1

And if you want to do more with it, you can always wrap the problems in nice 
GUIs, using different toolkits (such as Tkinter, wxPython or PyQT). That 
should keep you occupied for some time :-)

YDD
- -- 
.sigmentation Fault
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE9QlzJLsKMuCf5EdwRAs9NAKDMp8V+7S/RxnB4Fu17JXMAGBDU6ACfcBt4
5dAFTKBU1ekQJ/sWSD42hFQ=
=mMPd
-----END PGP SIGNATURE-----



From rob@uselesspython.com  Sat Jul 27 14:20:52 2002
From: rob@uselesspython.com (Rob)
Date: Sat, 27 Jul 2002 08:20:52 -0500
Subject: [Tutor] Ideas for programming projects
In-Reply-To: <200207271041.46267.yduppen@xs4all.nl>
Message-ID: <MPEOIFCOPCIHEDCLBLPBOEDJCBAA.rob@uselesspython.com>

Useless Python has collections of links to such online programming contests,
ideas for Python Challenges we came up with ourselves, and a bunch of other
ideas.

Rob
http://uselesspython.com

> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Yigal Duppen
> Sent: Saturday, July 27, 2002 3:42 AM
> To: Richard Seguin; tutor@python.org
> Subject: Re: [Tutor] (no subject)
>
>
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> On Friday 26 July 2002 23:30, Richard Seguin wrote:
> > Hey does anyone out there have any ideas for projects?  Im
> sitting way up
> > here in the middle of no where (Canada) and have this awsome programming
> > language that I am trying to learn.... but can't think of anything to do
> > with it....
>
> Well, you can get a good headstart by toying around with the ACM
> Programming
> Contests. Since they are mainly about difficult _algorithms_ (as
> opposed to
> datastructures or just vast amounts of work), Python just seems to be the
> most logical choice.
>
> http://acm.uva.es/cgi-bin/OnlineJudge?Volume:1
>
> And if you want to do more with it, you can always wrap the
> problems in nice
> GUIs, using different toolkits (such as Tkinter, wxPython or PyQT). That
> should keep you occupied for some time :-)
>
> YDD
> - --
> .sigmentation Fault
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.0.6 (GNU/Linux)
> Comment: For info see http://www.gnupg.org
>
> iD8DBQE9QlzJLsKMuCf5EdwRAs9NAKDMp8V+7S/RxnB4Fu17JXMAGBDU6ACfcBt4
> 5dAFTKBU1ekQJ/sWSD42hFQ=
> =mMPd
> -----END PGP SIGNATURE-----
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From printers@sendme.cz  Sat Jul 27 15:51:25 2002
From: printers@sendme.cz (A)
Date: Sat, 27 Jul 2002 16:51:25 +0200
Subject: [Tutor] How to redirect output to browser
Message-ID: <3D42CF8D.9280.1C2E23@localhost>

Hi,
Is it possible to send output continuously to a web browser?. 
For example I have the following code
>>> import httplib
>>> h = httplib.HTTP('www.cwi.nl')
>>> h.putrequest('GET', '/index.html')
>>> h.putheader('Accept', 'text/html')
>>> h.putheader('Accept', 'text/plain')
>>> h.endheaders()
I would like to send coming bytes ( here coming bytes of 
/index.html file)  directly to web browser in the same 
way as I use a web browser on my computer to open a 
webpage where I can see a progress how webpage is being 
opened.
In other words I do NOT want to wait for downloading the 
whole file and only after that open that downloaded file 
in a web browser. 

Thank you for help
Ladislav



From lumbricus@gmx.net  Sat Jul 27 16:30:41 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Sat, 27 Jul 2002 17:30:41 +0200 (MEST)
Subject: [Tutor] Re: Why x+=y instead of x=x+y?
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C786@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3417.1027783841@www22.gmx.net>

> > > > I think it is also related to the complexity of the compiler.  I
> > > > expect that any modern compiler will turn "x+=1" into INC X.  
> > > 
> > > If optimisation is turned off I sincerely hope it doesn't!
> > 
> > Why not?
> 
> Because if I'm writing a time critical program and I have 
> a loop that's running just slightly too fast with an x++ 
> in it I expect to be able to slow the loop down by changing 
> x++ to x+=1

I cant get any of my compilers (Digital UNIX Compiler Driver 3.11
and gcc) to compile (with -O0 to turn off all optimization)
 i=i+1, i+=i and i++ differently.
One (on x86) always codes "incl " the other one
(on alpha) always says "addl $1, 1, $1".
 
> If the compiler treats those two as equivalent then the 

But they _are_ equivalent IIRC. 
But I don't have a copy of the
Standard at hand to look it up *wink*.

> loop won't change. That's the kind of premature optimisation 
> that I don't want. (It also affects debugging of complex 
> code too, if the assembler is the same for x++ and x+=1 
> I'm going to have some strange results when running the 
> assembler debugger.)

Now I am really courious what compilers You use.
 
> Alan g.

Greetings, J"o!

-- 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net



From lumbricus@gmx.net  Sat Jul 27 17:30:44 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Sat, 27 Jul 2002 18:30:44 +0200 (MEST)
Subject: [Tutor] os.rename() on Win 98
References: <LNBBLJKPBEHFEDALKOLCKENEAHAB.tim.one@comcast.net>
Message-ID: <26729.1027787444@www22.gmx.net>

Hello!

[ snip ]

> and within the last week I created at
> least 50 errors in the C code severe enough to crash my machine.  It's
> called being human <wink>.

I call it having the wrong machine.
SCNR

> > Thanks a lot.

[ snip ]

Greetings, J"o!

-- 
 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net



From lumbricus@gmx.net  Sat Jul 27 17:52:39 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Sat, 27 Jul 2002 18:52:39 +0200 (MEST)
Subject: [Tutor] Newbie termios setup help for serial line opening.
References: <20020727014250.57804.qmail@web11801.mail.yahoo.com>
Message-ID: <2064.1027788759@www9.gmx.net>

> Hi Folks,

Hello!

[ snip ]

> -----------------------
> 1) Open the serial line
> -----------------------
> I do the following:
> 
>  >>>    import os
>  >>>    os.open('/dev/ttyC43', 0600)
> 
> Question: is the line actually open now?

If UNIX doesn't say anything it usually means that everything
is OK.
You can use the UNIX manpages in section 2 and 3.
man 2 open
man fopen

> No exceptions are raised - but I do not believe the line is
> actually open - as I can open it via another terminal with
> a tip command to the controller that uses the line.
> 
> Question: what is the 0600 integer value and what is it for?
The permissions of the file (here: rw-------)
man chmod 
man ls
 
> ---------------------------------------------------------------
> 2.) Next I've read that I have to set up the line using termios.
> ---------------------------------------------------------------
> If this is correct -
> Can someone possibly walk me through the basics of setting up termios
> for
> a serial line that I just want to read ASCII characters off - and write
> ASCII charachters to?

try read and write.
http://www.dodgies.demon.co.uk/Software/RRRR2/linux_serial.txt 
 
> Some supplemental notes:
> 
> The serial line accesses a controller that controls two other devices.
> The normal way to interact with the controller is to use the commands:
> 
>   sun> tip oftc
> 
> That sets up the communication so taht you can ask the device for
> current settings and change them if you like. This is a first
> programming project for me at work, and what I am trying to do is build
> a program that will allow you to pop open a gui - and it will query
> these settings and allow you to simply place new settings into a
> dialogue box - or select them from a pull down menu.

man tcgetattr
man tcsetattr

> Bill

HTH, HAND
and Greetings, J"o!

-- 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net



From runsun@bilbo.bio.purdue.edu  Sun Jul 28 01:42:02 2002
From: runsun@bilbo.bio.purdue.edu (runsun)
Date: Sat, 27 Jul 2002 19:42:02 -0500
Subject: [Tutor] What file is calling the cgi ???
In-Reply-To: <20020727160003.6064.44233.Mailman@mail.python.org>
Message-ID: <HNEOKHJLEPAHPMJCIDCMMEDPCCAA.runsun@bilbo.bio.purdue.edu>

I have a cgi:

	/cgi-bin/py/whocalledme.py

It was called by a shtml file "caller.shtml" as such:

    <!--#include virtual="/cgi-bin/py/whocalledme.py" -->

The full path name of "caller.shtml" is:

	/testfolder/caller.shtml

Now, what code should I put in the whocalledme.py such
that its execution (when called by caller.shtml) displays 
the folder name ('testfolder') and the caller name 
('caller.shtml') on a browser ???

Here were somethings I tried but they seem to offer the 
host info (namedly, /cgi-bin/py/whocalledme.py, but not 
/testfolder/caller.shtml) :

     print os.getcwd()
     print "<br>", os.environ.get("HTTP_REFERER", "--noreferer--")
     print "<br>", os.environ.get("HTTP_HOST", "--nohost--")
     print "<br>", os.curdir
     print "<br>", os.path.abspath(os.curdir)

I could have used:

   <!--#include virtual="/cgi-bin/py/whocalledme.py?caller.shtml" -->

but I really want to see if a python cgi can get the caller's name.

Thx in advance.

pan


============================================
  ~~ Be like water, be shapeless ~~
   Runsun Pan, PhD, 773-834-3965
 Ecology & Evolution, U of Chicago
============================================


From runsun@bilbo.bio.purdue.edu  Sun Jul 28 04:42:34 2002
From: runsun@bilbo.bio.purdue.edu (runsun)
Date: Sat, 27 Jul 2002 22:42:34 -0500
Subject: [Tutor] get local time ????
In-Reply-To: <20020727160003.6064.44233.Mailman@mail.python.org>
Message-ID: <HNEOKHJLEPAHPMJCIDCMOEEACCAA.runsun@bilbo.bio.purdue.edu>

I am in the chicago area. 

I am using freepagehosting.com as my web server. 

I want to know when my webpages are visited.

I tried several time-related methods but what I got were
all the server time, not my local time. 

How can I get the time -- as my local time -- when a
visitor visits my far-away website ???

Also, is it possible to log the visitor's time ???

thx.

pan

============================================
  ~~ Be like water, be shapeless ~~
   Runsun Pan, PhD, 773-834-3965
 Ecology & Evolution, U of Chicago
============================================ 


From donni@melwestmarket.com  Sun Jul 28 05:07:40 2002
From: donni@melwestmarket.com (Dimitrije Nikic)
Date: Sun, 28 Jul 2002 14:07:40 +1000
Subject: [Tutor] Converting all Characters in String to Array
Message-ID: <200207280412.g6S4C3c03580@mail022.syd.optusnet.com.au>

Help!

How do I place all characters from a string to an array list??
E.g: 
The string I want to convert: "Hello World"
The array I want: array[H,e,l,l,o,,W,o,r,l,d)

Thx!!


From Karthik_Gurumurthy@i2.com  Sun Jul 28 05:17:35 2002
From: Karthik_Gurumurthy@i2.com (Karthik_Gurumurthy@i2.com)
Date: Sun, 28 Jul 2002 09:47:35 +0530
Subject: [Tutor] Converting all Characters in String to Array
Message-ID: <OFB40A4A11.6BC5FCF8-ON65256C04.0017869C@i2.com>

This is a multipart message in MIME format.
--=_alternative 0017953065256C04_=
Content-Type: text/plain; charset="us-ascii"

did you try
list("hello world")





Dimitrije Nikic <donni@melwestmarket.com>
Sent by: tutor-admin@python.org
07/28/2002 09:37 AM
Please respond to donni

 
        To:     tutor@python.org
        cc: 
        Subject:        [Tutor] Converting all Characters in String to Array


Help!

How do I place all characters from a string to an array list??
E.g: 
The string I want to convert: "Hello World"
The array I want: array[H,e,l,l,o,,W,o,r,l,d)

Thx!!

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



--=_alternative 0017953065256C04_=
Content-Type: text/html; charset="us-ascii"


<br><font size=2 face="sans-serif">did you try</font>
<br><font size=2 face="sans-serif">list(&quot;hello world&quot;)</font>
<br>
<br>
<br>
<br>
<table width=100%>
<tr valign=top>
<td>
<td><font size=1 face="sans-serif"><b>Dimitrije Nikic &lt;donni@melwestmarket.com&gt;</b></font>
<br><font size=1 face="sans-serif">Sent by: tutor-admin@python.org</font>
<p><font size=1 face="sans-serif">07/28/2002 09:37 AM</font>
<br><font size=1 face="sans-serif">Please respond to donni</font>
<br>
<td><font size=1 face="Arial">&nbsp; &nbsp; &nbsp; &nbsp; </font>
<br><font size=1 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; To: &nbsp; &nbsp; &nbsp; &nbsp;tutor@python.org</font>
<br><font size=1 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; cc: &nbsp; &nbsp; &nbsp; &nbsp;</font>
<br><font size=1 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; Subject: &nbsp; &nbsp; &nbsp; &nbsp;[Tutor] Converting all Characters in String to Array</font></table>
<br>
<br>
<br><font size=2 face="Courier New">Help!<br>
<br>
How do I place all characters from a string to an array list??<br>
E.g: <br>
The string I want to convert: &quot;Hello World&quot;<br>
The array I want: array[H,e,l,l,o,,W,o,r,l,d)<br>
<br>
Thx!!<br>
<br>
_______________________________________________<br>
Tutor maillist &nbsp;- &nbsp;Tutor@python.org<br>
http://mail.python.org/mailman/listinfo/tutor<br>
</font>
<br>
<br>
--=_alternative 0017953065256C04_=--


From Karthik_Gurumurthy@i2.com  Sun Jul 28 05:38:03 2002
From: Karthik_Gurumurthy@i2.com (Karthik_Gurumurthy@i2.com)
Date: Sun, 28 Jul 2002 10:08:03 +0530
Subject: [Tutor] (no subject)
Message-ID: <OF3BD6C75A.86E73811-ON65256C04.001937CF@i2.com>

This is a multipart message in MIME format.
--=_alternative 0019752665256C04_=
Content-Type: text/plain; charset="us-ascii"

http://www.uselesspython.com/

i guess is a nice place to start off .  If i remember correctly it has a 
section "Python challenge" where you are asked to solve some 
questions/problems.

karthik





Richard Seguin <rseguin@shaw.ca>
Sent by: tutor-admin@python.org
07/27/2002 03:00 AM

 
        To:     tutor@python.org
        cc: 
        Subject:        [Tutor] (no subject)


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hey does anyone out there have any ideas for projects?  Im sitting way up 
here 
in the middle of no where (Canada) and have this awsome programming 
language 
that I am trying to learn.... but can't think of anything to do with 
it....

Rich
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)

iD8DBQE9Qb+Dn9670YZTFEcRAs4WAJ953TdcW3zcQabNxTbaRl1WAC4h3QCgiFuO
59a0ATkHaPArlISZ8fWhsQ0=
=Fo3H
-----END PGP SIGNATURE-----


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



--=_alternative 0019752665256C04_=
Content-Type: text/html; charset="us-ascii"


<br><font size=2 face="sans-serif">http://www.uselesspython.com/</font>
<br>
<br><font size=2 face="sans-serif">i guess is a nice place to start off . &nbsp;If i remember correctly it has a section &quot;Python challenge&quot; where you are asked to solve some questions/problems.</font>
<br>
<br><font size=2 face="sans-serif">karthik</font>
<br>
<br>
<br>
<br>
<table width=100%>
<tr valign=top>
<td>
<td><font size=1 face="sans-serif"><b>Richard Seguin &lt;rseguin@shaw.ca&gt;</b></font>
<br><font size=1 face="sans-serif">Sent by: tutor-admin@python.org</font>
<p><font size=1 face="sans-serif">07/27/2002 03:00 AM</font>
<br>
<td><font size=1 face="Arial">&nbsp; &nbsp; &nbsp; &nbsp; </font>
<br><font size=1 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; To: &nbsp; &nbsp; &nbsp; &nbsp;tutor@python.org</font>
<br><font size=1 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; cc: &nbsp; &nbsp; &nbsp; &nbsp;</font>
<br><font size=1 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; Subject: &nbsp; &nbsp; &nbsp; &nbsp;[Tutor] (no subject)</font></table>
<br>
<br>
<br><font size=2 face="Courier New">-----BEGIN PGP SIGNED MESSAGE-----<br>
Hash: SHA1<br>
<br>
Hey does anyone out there have any ideas for projects? &nbsp;Im sitting way up here <br>
in the middle of no where (Canada) and have this awsome programming language <br>
that I am trying to learn.... but can't think of anything to do with it....<br>
<br>
Rich<br>
-----BEGIN PGP SIGNATURE-----<br>
Version: GnuPG v1.0.7 (GNU/Linux)<br>
<br>
iD8DBQE9Qb+Dn9670YZTFEcRAs4WAJ953TdcW3zcQabNxTbaRl1WAC4h3QCgiFuO<br>
59a0ATkHaPArlISZ8fWhsQ0=<br>
=Fo3H<br>
-----END PGP SIGNATURE-----<br>
<br>
<br>
_______________________________________________<br>
Tutor maillist &nbsp;- &nbsp;Tutor@python.org<br>
http://mail.python.org/mailman/listinfo/tutor<br>
</font>
<br>
<br>
--=_alternative 0019752665256C04_=--


From millsl@cofc.edu" <millsl@cofc.edu  Sun Jul 28 19:16:39 2002
From: millsl@cofc.edu" <millsl@cofc.edu (Laney Mills)
Date: Sun, 28 Jul 2002 14:16:39 -0400
Subject: [Tutor] New member question
Message-ID: <01C23641.64741AE0.millsl@cofc.edu>

Hi everyone on the list,

This list seems like a perfect idea.

I am a pc used using windows 98.  I downloaded

Python 2.1.2 (#31, Jan 15 2002, 17:28:11) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>>


frp, www.python.org

and let it install itself.  I am able to open IDLE by clicking

"C:\Program Files\Python21\Tools\idle\idle.pyw"

statements like

>>>print 2+2
5


work ok.

But if I make a small module and try to open it, the program can't find it. 
 I am suspecting this problem is an issue concerning PYTHONPATH, but I'm 
not sure.  I have read news lists and tutor information and o'reilly 
"learning python", but ALL those sources given answers using concepts 
rather more sophisticated than my actual question.  Any help would be 
greatly appreciated.

Also, what is tkinter and does it come with this distribution?  I can't 
find it, but thought it came with the download from python.org.

Thanks in advance


From rickp@telocity.com  Sun Jul 28 19:41:40 2002
From: rickp@telocity.com (Rick Pasotto)
Date: Sun, 28 Jul 2002 14:41:40 -0400
Subject: [Tutor] New member question
In-Reply-To: <01C23641.64741AE0.millsl@cofc.edu>
References: <01C23641.64741AE0.millsl@cofc.edu>
Message-ID: <20020728184140.GA19803@tc.niof.net>

On Sun, Jul 28, 2002 at 02:16:39PM -0400, Laney Mills wrote:
> 
> statements like
> 
> >>>print 2+2
> 5
> 
> 
> work ok.

If my computer ever gave that answer I'd immediately get a new one.

-- 
"Wit is educated insolence."
		-- Aristotle
    Rick Pasotto    rickp@telocity.com    http://www.niof.net


From dyoo@hkn.eecs.berkeley.edu  Sun Jul 28 20:13:17 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Jul 2002 12:13:17 -0700 (PDT)
Subject: [Tutor] Converting all Characters in String to Array
In-Reply-To: <200207280412.g6S4C3c03580@mail022.syd.optusnet.com.au>
Message-ID: <Pine.LNX.4.44.0207281206590.10843-100000@hkn.eecs.berkeley.edu>


On Sun, 28 Jul 2002, Dimitrije Nikic wrote:

> Help!
>
> How do I place all characters from a string to an array list??
> E.g:
> The string I want to convert: "Hello World"
> The array I want: array[H,e,l,l,o,,W,o,r,l,d)

Hi Dimitrije,

By an "array", do you mean a Numeric Python array, or do you just mean a
regular list?


There's an add-on to Python called "Numeric Python" that adds good matrix
and homogenous array support to Python:

    http://www.pfdubois.com/numpy/

In other programming languages, the word "array" and "list" are almost
interchangable, but in the context of Python, they mean different things:
An 'array' can only contain values of a single type, like an array of
integers, or an array of characters.  A 'list', on the other hand, can
hold values of different types.  I want to make sure sure that we
understand your question properly.


Good luck to you!



From dyoo@hkn.eecs.berkeley.edu  Sun Jul 28 20:23:44 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Jul 2002 12:23:44 -0700 (PDT)
Subject: [Tutor] New member question
In-Reply-To: <01C23641.64741AE0.millsl@cofc.edu>
Message-ID: <Pine.LNX.4.44.0207281213430.10843-100000@hkn.eecs.berkeley.edu>


> But if I make a small module and try to open it, the program can't find
> it.  I am suspecting this problem is an issue concerning PYTHONPATH, but
> I'm not sure.  I have read news lists and tutor information and o'reilly
> "learning python", but ALL those sources given answers using concepts
> rather more sophisticated than my actual question.  Any help would be
> greatly appreciated.

That's odd!  Hmmm... I think we might need more information on this one.
How are you trying to open the module?


If you keep all your modules in a standard place, you can add the
environmental variable 'PYTHONPATH', so that Python knows about them.
For example, on my Linux system, I keep a personal directory of modules in
a directory called '/home/dyoo/src/python'.  My PYTHONPATH will look like:

    PYTHONPATH='/home/dyoo/src/python'

and that should be it; afterwards, I can do an 'import
[name-of-my-module]' statement in other programs, and it should import the
module ok.



> Also, what is tkinter and does it come with this distribution?  I can't
> find it, but thought it came with the download from python.org.

Tkinter is a module that provides GUI building support.  You can write
programs that open windows and bring up buttons and menus.  It should be
installed alongside Python if you're using the standard distribution from
Python.org.

If you'd like to read a little more on Tkinter, Fredrik Lundh's "An
Introduction to Tkinter" may whet your appetite:

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


There are other GUI toolkits available for Python; although Tkinter is
standard, another popular one is called "wxPython":

    http://www.wxpython.org/

I have to admit that I haven't tried wxPython yet, but other people on
this list may be able to share their experiences with it.


If you have more questions, please feel free to ask.  We'll be happy to
help!  Off to lunch for me.  *grin* I'll talk to you later!



From allyn@tardigrade.net  Sat Jul 27 23:19:13 2002
From: allyn@tardigrade.net (Allyn Weaks)
Date: Sat, 27 Jul 2002 15:19:13 -0700
Subject: [Tutor] IOError exception handling
Message-ID: <p05100300b968c864b199@[209.221.136.26]>

Unix; linux 7.1 if it matters.  Can one get a more finely divided error
back than IOError?  I'm counting lines in files that may or may not
exist, and if one doesn't exist, I can set the number of lines to zero
and continue with the rest.  But, if the file can't be opened because
of any other problem, such as a permission error, I want it to bail
with whatever error message is appropriate (preferably without handling
each and every case at this point, since I'm still a first instar
pythonista...)

def countlines(filename):
	try:
		f = open(filename, 'r')
		text = f.readlines()
		f.close()
		return len(text)
	except (file doesn't exist):
		return 0

Many thanks!
-- 
Allyn Weaks    allyn@tardigrade.net   Seattle, WA  Sunset zone 5
Pacific NW Native Wildlife Gardening: http://www.tardigrade.org/natives/
"The benefit of even limited monopolies is too doubtful, to be opposed
to that of their general suppression."  Thomas Jefferson


From bjmartin98@pennswoods.net  Sun Jul 28 23:04:13 2002
From: bjmartin98@pennswoods.net (Billie)
Date: Sun, 28 Jul 2002 18:04:13 -0400
Subject: [Tutor] Python information
Message-ID: <000e01c23682$b60f4e60$4538d141@bjmartin98>

This is a multi-part message in MIME format.

------=_NextPart_000_000B_01C23661.2E450CC0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hello,
First I would like to thank all you guys who help me with my password =
program.

I have a point I would like all of you to ponder.

I have been told by several sources, on the net and on TV, that Python =
is a great program for a first programming language.=20

Tell me why then there is only 2 tutorials on the net that teaches it =
from the beginning and assuming the reader has no other language =
experience and absolutely no books that doesn't assume the reader knows =
another language.  None, zero, zip!

Every place I looked on the net (I spent 10 hrs looking) assumes lots of =
Python programming under your belt or that you are knowledgeable in C++ =
or a Linux follower.

I've seen lots of stuff for beginners for VB, Perl, Java, and the like =
but Python - nothing.

Why are Python programmers so selfish with their knowledge.  I always =
thought the idea of OpenSource was also a sharing of ideas and helping =
the new guys.  But you know the other guys are more helpful than the =
Python guys.

I like this language and would like to learn more but if I don't know =
anything how can I ask a question, or further my learning in Python.

Where are you guys! Surely not promoting Python.

Billie

------=_NextPart_000_000B_01C23661.2E450CC0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 5.50.4522.1800" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hello,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>First I would like to thank all you =
guys who help=20
me with my password program.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I have a point I would like all of you =
to=20
ponder.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I have been told by several sources, on =
the net and=20
on TV, that Python is a great program for a first programming language.=20
</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Tell me why then there is only 2 =
tutorials on the=20
net that teaches it from the beginning and assuming the reader has no =
other=20
language experience and absolutely no books that doesn't assume the =
reader knows=20
another language.&nbsp; None, zero, zip!</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Every place I looked on the net (I =
spent 10 hrs=20
looking) assumes lots of Python programming under your belt or that you =
are=20
knowledgeable in C++ or a Linux follower.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I've seen lots of stuff for beginners =
for VB, Perl,=20
Java, and the like but Python - nothing.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Why&nbsp;are Python programmers so =
selfish with=20
their knowledge.&nbsp; I always thought the idea of OpenSource was also =
a=20
sharing of ideas and helping the new guys.&nbsp; But you know the other =
guys are=20
more helpful than the Python guys.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I like this language and would like to =
learn more=20
but if I don't know anything how&nbsp;can I ask a question, or further =
my=20
learning in Python.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Where are you guys! Surely not =
promoting=20
Python.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Billie</FONT></DIV></BODY></HTML>

------=_NextPart_000_000B_01C23661.2E450CC0--



From joel@prettyhipprogramming.com  Sun Jul 28 23:17:26 2002
From: joel@prettyhipprogramming.com (Joel Ricker)
Date: Sun, 28 Jul 2002 18:17:26 -0400
Subject: [Tutor] Returning repr() data by function
References: <p05100300b968c864b199@[209.221.136.26]>
Message-ID: <002f01c23684$935c7c10$f5e03942@joeltklrijxxms>

Horrible subject line :)

I'm been working with the wxPython gui framework and it uses a class called
wxBitmap to store an image for use within the program.  I've got a bunch of
little icons that I'm planning to use and instead of having a directory of a
bunch of little images, I'm trying to write a python program that creates
the class, pickles it, compresses the text by zlib, and takes the resulting
text and writes a python function to a module file to be used in my
application.

I found a script that comes with PIL called image2py that works similar to
what I want but when I adapted the code into my script, I keep getting a
invalid \x escape when it tries to parse the resulting module. The
difference between my code and theirs is that they use StringIO to load the
file and does a repr() on that.

Here is a sample of the output file I'm getting:

import cPickle
import zlib

def getFlagAA():

     return
cPickle.loads(zlib.decompress('x\xda\xd3\xc8,\xaf\x08\xa8,\xc9\xc8\x\
cf\xd3KO\xc9\xe4*\xafp\xca,\xc9M,\xe0*0\xe4\xd2H)0\xe2\nV/\xc9\xc8,V\xe7*0\x
\
062\xe3S\x8c-L\x13-\xe2a\xaa\xe2\x0b\xd4\xb9\x8a!*\xf2\xcb\xf3\x80\x8aL\xb8<
\
\r\xb9\x8a\x93\xf4\x00\xcb\xa7\x1b8'))

And my code:

import glob
from wxPython.wx import *
import cPickle
import zlib
import os

octdigits = "01234567"
wxInitAllImageHandlers()

files = glob.glob("images/*.*")

f = open("images.py", "wb")
f.write("import cPickle\n")
f.write("import zlib\n\n")

for x in files:
    name, ext = os.path.splitext(os.path.basename(x))
    print name.upper()

    ## wxBitmap takes in a filename to an image file, type =
wxBITMAP_TYPE_ANY
    ## tells wxBitMap to guess what image type it is (GIF, PNG, etc)
    image = wxBitmap(name = x, type = wxBITMAP_TYPE_ANY)

    data = zlib.compress(cPickle.dumps(image), 9)
    data = repr(data)
    f.write("def getFlag%s():\n\n" % name.upper())

    word = "\treturn cPickle.loads(zlib.decompress('"

    f.write(word)
    c = len(word)

    i = 1
    while i < len(data)-1:
        if data[i] != "\\":
            word = data[i]
            i = i + 1
        else:
            if data[i+1] in octdigits:
                for n in range(2, 5):
                    if data[i+n] not in octdigits:
                        break
                word = data[i:i+n]
                i = i + n
            else:
                word = data[i:i+2]
                i = i + 2
        l = len(word)
        if c + l >= 78-1:
            # fp.write("'\n'")
            f.write("\\\n")
            c = 0
        f.write(word)
        c = c + l

    f.write("'))\n\n\n")

Thanks for any help
Joel




From kb@mm.st  Sun Jul 28 23:15:32 2002
From: kb@mm.st (Kyle Babich)
Date: Sun, 28 Jul 2002 22:15:32 +0000
Subject: [Tutor] A few comparative perl/python questions
Message-ID: <20020728221532.915536D9EF@www.fastmail.fm>

I just have a few Perl-to-Python questions:

Does python have anything like Perl's || die, flock(), or seek()
functions?  (What are they?)
If Python doesn't have something like flock(), what happens what
multiple scripts are trying to write to one file at the same time?

Thank you,
--
Kyle


From joel@prettyhipprogramming.com  Sun Jul 28 23:31:19 2002
From: joel@prettyhipprogramming.com (Joel Ricker)
Date: Sun, 28 Jul 2002 18:31:19 -0400
Subject: [Tutor] Python information
References: <000e01c23682$b60f4e60$4538d141@bjmartin98>
Message-ID: <000f01c23686$7ef99a80$f5e03942@joeltklrijxxms>

This is a multi-part message in MIME format.

------=_NextPart_000_000C_01C23664.F7B72680
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

To be fair, those two tutorials are the best you'll find.  The standard =
documentation is top notch considering the fact of how much of it is =
created through volunteers rather than a paying company. I'm sure though =
that more documentation is being written all the time but writing =
quality documentation is a big workload and most poeple writting it have =
real lives as well ;)

Also, consider the other resources you'll find.  Almost all python =
programmers that I've run into, whether here on this list, the =
newsgroup, or IRC chats, have been the most helpful group of people I've =
run across.  I've not found this level of help with any other =
programming language I've ever seen. Ask a question and you'll receive =
explanations, sample programs, and references on the web rather than a =
terse response of RTM.

Joel

------=_NextPart_000_000C_01C23664.F7B72680
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2716.2200" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>To be fair, those two tutorials are the =
best you'll=20
find.&nbsp; The standard documentation is top notch considering the fact =
of how=20
much of it is created through volunteers rather than a paying company. =
I'm sure=20
though that more documentation is being written all the time but writing =
quality=20
documentation is a big workload and most poeple writting it have real =
lives as=20
well ;)</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Also, consider the other resources =
you'll=20
find.&nbsp; Almost all python programmers that I've run into, whether =
here on=20
this list, the newsgroup, or IRC chats, have been the most helpful group =
of=20
people I've run across.&nbsp; I've not found this level of help with any =
other=20
programming language I've ever seen. Ask a question and you'll receive=20
explanations, sample programs, and references on the web rather than a =
terse=20
response of RTM.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Joel</FONT></DIV></BODY></HTML>

------=_NextPart_000_000C_01C23664.F7B72680--



From alan.gauld@bt.com  Sun Jul 28 23:23:30 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 28 Jul 2002 23:23:30 +0100
Subject: [Tutor] (no subject)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C79F@mbtlipnt02.btlabs.bt.co.uk>

> Hey does anyone out there have any ideas for projects?  

What do you use yur computer for?
Anything repetitive? If so automate it...
backing up files, checking a web site, cataloging(sp?) 
data files, running a program and checking the logs?

Or, Visit Useless python and try any of the many 
challenges there... 

Or visit my tutor and try the projects on the 
last page. 

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld@bt.com  Sun Jul 28 23:38:38 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 28 Jul 2002 23:38:38 +0100
Subject: [Tutor] Re: Why x+=y instead of x=x+y?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A0@mbtlipnt02.btlabs.bt.co.uk>

> > in it I expect to be able to slow the loop down by changing 
> > x++ to x+=1
> 
> I cant get any of my compilers (Digital UNIX Compiler Driver 3.11
> and gcc) to compile (with -O0 to turn off all optimization)
>  i=i+1, i+=i and i++ differently.

Interesting, I must go do some experimentation when I get 
into work tomorrow. It could be a change in the latest 
ANSI standard but I hope not, an awful lot of code relies 
on those differences!

I'm particularly alarmed at i = i + 1 having the same 
behaviour since if i is a 'register' variable then that 
potentially changes the whole CPU semantics! 

> But they _are_ equivalent IIRC. 
> But I don't have a copy of the
> Standard at hand to look it up *wink*.

The last time I used raw C (as opposed to C++) was 
pre ANSI compilers(~1993/4), so the standard may 
have changed the rules. I'll check tomorrow...

> Now I am really courious what compilers You use.

The Sun Workbench, An HP EPROM programmer and the VAX VMS 
standard C compiler. Also occasionally the PSOS and OS/9 
compilers. We also used gcc(v2.something) for one job 
cross compiling to a Texas Instruments chip (can't recall 
which!) so I'm interested to see gcc in your list.

Alan G


From allyn.@tardigrade.net  Mon Jul 29 00:33:22 2002
From: allyn.@tardigrade.net (Allyn Weaks)
Date: Sun, 28 Jul 2002 16:33:22 -0700
Subject: [Tutor] IOError exception handling
Message-ID: <p05100301b96a2d7873ba@[209.221.136.35]>

Python 2.1 until I can get 2.2.1 installed properly (linux 7.1), but
I'll also be using 2.0 on another (aix) server.

Can one get a more detailed error back than IOError?  I'm counting
lines in files that may or may not exist, and if one doesn't exist, I
can set the number of lines to zero and continue with the rest.  But,
if the file can't be opened because of any other problem, such as a
permission error, I want it to bail with whatever error message is
appropriate (preferably without handling each and every case.)

def countlines(filename):
	try:
		f = open(filename, 'r')
		text = f.readlines()
		f.close()
		return len(text)
	except (file doesn't exist):
		return 0

Many thanks from a first instar pythonista...
-- 
Allyn Weaks    allyn@tardigrade.net   Seattle, WA  Sunset zone 5
Pacific NW Native Wildlife Gardening: http://www.tardigrade.org/natives/
"The benefit of even limited monopolies is too doubtful, to be opposed
to that of their general suppression."  Thomas Jefferson


From shalehperry@attbi.com  Mon Jul 29 00:48:58 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun, 28 Jul 2002 16:48:58 -0700 (PDT)
Subject: [Tutor] A few comparative perl/python questions
In-Reply-To: <20020728221532.915536D9EF@www.fastmail.fm>
Message-ID: <XFMail.20020728164858.shalehperry@attbi.com>

On 28-Jul-2002 Kyle Babich wrote:
> I just have a few Perl-to-Python questions:
> 
> Does python have anything like Perl's || die, flock(), or seek()
> functions?  (What are they?)
> If Python doesn't have something like flock(), what happens what
> multiple scripts are trying to write to one file at the same time?
> 

In perl a common idiom is:

func() || die;

in python the same thing is usually written as:

try:
  func()
except TypeofError:
  die()

in many places where perl would return an error code python using exceptions. 
So there is a lot less:

if func() == -1:
  handle bad thing

style of coding.

seek() in perl is a function called with a file descriptor passed as an
argument.  python makes seek() a method of the file object:

fname = '/path/to/file'
try:
  fd = open(fname)
except IOError, e:
  print 'Failed to open %s: %s' % (fname, e[1])
fd.seek(0, 2) # seek to end of file

Can;t help with the flock() question, I never use it.


From monashee@junction.net  Mon Jul 29 00:57:33 2002
From: monashee@junction.net (J or M Montgomery)
Date: Sun, 28 Jul 2002 16:57:33 -0700
Subject: [Tutor] Python information
References: <000e01c23682$b60f4e60$4538d141@bjmartin98> <000f01c23686$7ef99a80$f5e03942@joeltklrijxxms>
Message-ID: <3D4484ED.50904@junction.net>

Joel Ricker wrote:
> 
> Also, consider the other resources you'll find.  Almost all python 
> programmers that I've run into, whether here on this list, the 
> newsgroup, or IRC chats, have been the most helpful group of people I've 
> run across.  I've not found this level of help with any other 
> programming language I've ever seen. Ask a question and you'll receive 
> explanations, sample programs, and references on the web rather than a 
> terse response of RTM.
> 
I will certainly second that. The level of help given and the polite 
manners of everyone on this list beats any list I have seen.
Stick around and you can't help but learn.

Cheers

John Montgomery






From shalehperry@attbi.com  Mon Jul 29 00:53:49 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun, 28 Jul 2002 16:53:49 -0700 (PDT)
Subject: [Tutor] IOError exception handling
In-Reply-To: <p05100301b96a2d7873ba@[209.221.136.35]>
Message-ID: <XFMail.20020728165349.shalehperry@attbi.com>

On 28-Jul-2002 Allyn Weaks wrote:
> Python 2.1 until I can get 2.2.1 installed properly (linux 7.1), but
> I'll also be using 2.0 on another (aix) server.
> 
> Can one get a more detailed error back than IOError?  I'm counting
> lines in files that may or may not exist, and if one doesn't exist, I
> can set the number of lines to zero and continue with the rest.  But,
> if the file can't be opened because of any other problem, such as a
> permission error, I want it to bail with whatever error message is
> appropriate (preferably without handling each and every case.)
> 

>>> fd = open('/home/shoon/xinitrc')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 13] Permission denied: '/home/shoon/xinitrc'

As you can see, IOError covers many issues

>>> try:
...   fd = open('/home/shoon/xinitrc')
... except IOError, e:
...   print e[0], e[1]
... 
13 Permission denied

I am sure there is a wrapper for errno somewhere in python.


From guillermo.fernandez@epfl.ch  Mon Jul 29 01:22:47 2002
From: guillermo.fernandez@epfl.ch (Guillermo Fernandez)
Date: Mon, 29 Jul 2002 09:52:47 +0930
Subject: [Tutor] (no subject)
References: <200207261730.43335.rseguin@shaw.ca>
Message-ID: <3D448AD7.502BAD84@epfl.ch>

You can do little utilities (a program to download your preferred comic
strip from the web each day...), you can do genetic algorithms and
programming (really cool!!) you can do interfaces for your prefered
programs (cdrecord, ot whatever) you can do...

And if with all that you still don't find something you like, go to
http://www.uselesspython.com/
and you'll find lots of ideas to do!!

Regards,

Guille

Richard Seguin wrote:
> 
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> Hey does anyone out there have any ideas for projects?  Im sitting way up here
> in the middle of no where (Canada) and have this awsome programming language
> that I am trying to learn.... but can't think of anything to do with it....
> 
> Rich
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.0.7 (GNU/Linux)
> 
> iD8DBQE9Qb+Dn9670YZTFEcRAs4WAJ953TdcW3zcQabNxTbaRl1WAC4h3QCgiFuO
> 59a0ATkHaPArlISZ8fWhsQ0=
> =Fo3H
> -----END PGP SIGNATURE-----
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From dyoo@hkn.eecs.berkeley.edu  Mon Jul 29 01:21:46 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Jul 2002 17:21:46 -0700 (PDT)
Subject: [Tutor] Python information  [links for beginning programmers]
In-Reply-To: <000e01c23682$b60f4e60$4538d141@bjmartin98>
Message-ID: <Pine.LNX.4.44.0207281705590.16125-100000@hkn.eecs.berkeley.edu>


On Sun, 28 Jul 2002, Billie wrote:

> I've seen lots of stuff for beginners for VB, Perl, Java, and the like
> but Python - nothing.

Hi Billie,

There's actually quite a lot of stuff here for people who haven't
programmed before:

    http://python.org/doc/Newbies.html

It's true that there are a lot of resources for experienced programmers
out there, but there's also a lot of stuff for people who haven't
programmed before.  (If you find some more resources for beginning
programming, can you tell us about it?  We might be able to link it to
that page for others to use.)

Personally, I like Alan Gauld's "Learning to Program"  and Josh Cogliati's
"A Non-Programmer's Tutorial for Python", but all of the tutorials there
are pretty nice.  The Livewires course is also awesome.  Try one of these
tutorials, and as you play around with Python, you can always ask your
questions here on Tutor.


... I'm surprised that Useless Python doesn't appear to be linked from the
Newcomers page!  Billie, if you have time, you might find this site nice:

    http://uselesspython.com/tutorials.html

Useless Python is a great resource for beginning Python programmers.
Some of these tutorials do assume some programming background, but there
are some tutorials focused for newcomers in there as well.


You are also always welcome to ask any Python questions here on Tutor;
books can't talk back, but people can.  *grin*  Good luck to you.



From dyoo@hkn.eecs.berkeley.edu  Mon Jul 29 01:41:02 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Jul 2002 17:41:02 -0700 (PDT)
Subject: [Tutor] A few comparative perl/python questions
In-Reply-To: <20020728221532.915536D9EF@www.fastmail.fm>
Message-ID: <Pine.LNX.4.44.0207281722390.16125-100000@hkn.eecs.berkeley.edu>


On Sun, 28 Jul 2002, Kyle Babich wrote:

> I just have a few Perl-to-Python questions:
>
> Does python have anything like Perl's || die, flock(), or seek()
> functions?  (What are they?)

[Aside on Perl]

Perl has pretty nice documentation in the 'perldoc' utility: here's an
example of finding out information on the die() function:

###
dyoo@coffeetable:~$ perldoc -f die
die LIST
           Outside an "eval", prints the value of LIST to "STDERR" and
           exits with the current value of "$!" (errno).  If "$!" is "0",
           exits with the value of "($? >> 8)" (backtick `command` sta-
           tus).  If "($? >> 8)" is "0", exits with "255".  Inside an
           "eval()," the error message is stuffed into "$@" and the "eval"
           is terminated with the undefined value.  This makes "die" the
           way to raise an exception.
###

So if you're working with perl, 'perldoc' is your friend.  In Python, we
have the help() function, which does similar things:

###
>>> help(file.seek)
Help on method_descriptor:

seek(...)
    seek(offset[, whence]) -> None.  Move to new file position.

    Argument offset is a byte count.  Optional argument whence defaults to
    0 (offset from start of file, offset should be >= 0); other values are
    1 (move relative to current position, positive or negative), and 2
    (move relative to end of file, usually negative, although many platforms
    allow seeking beyond the end of a file).

    Note that not all file objects are seekable.
###


Simply speaking, die() causes the program to exit immediately with an
error message.  This is useful if something "bad" happens.  "Bad"  things
might include things like:

    Trying to open a file that doesn't exist.
    Trying to connect to a database with an incorrect password.
    Trying to divide by zero.


In Python, an equivalent way to make a program die is to "raise" an
exception, like this:

###
>>> def mydivide(a, b):
...     if b == 0:
...         raise ZeroDivisionError, "You bad person!"
...     return a / b
...
>>>
>>> mydivide(12, 4)
3
>>> mydivide(12, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in mydivide
ZeroDivisionError: You bad person!
###



But actually, division raises a ZeroDivisionError anyway:

###
>>> 12/0
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
###

so the example above is sorta Useless.  Still, it shows how we might be
able to make a program try to die quickly if we believe it should.  If
you're interested in exceptions, you may find:

    http://www.python.org/doc/tut/node10.html

a "deep-end-of-the-pool" introduction to exception handling.

Alan Gauld's "Learning to Program" has a much gentler introduction to
error handling here:

    http://www.freenetpages.co.uk/hp/alan.gauld/tuterrors.htm



> If Python doesn't have something like flock(), what happens what
> multiple scripts are trying to write to one file at the same time?

Python does have flock(), but it's in the somewhat unpronouncable 'fcntl'
"file control" module:

    http://www.python.org/doc/lib/module-fcntl.html

The only problem is that this appears to be Unix-specific.  Hmmm... Ah!
The Python Cookbook includes a module to make this file locking work on
Win32 platforms too:

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


Hope this helps!



From dyoo@hkn.eecs.berkeley.edu  Mon Jul 29 01:48:41 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Jul 2002 17:48:41 -0700 (PDT)
Subject: [Tutor] IOError exception handling
In-Reply-To: <XFMail.20020728165349.shalehperry@attbi.com>
Message-ID: <Pine.LNX.4.44.0207281747360.16125-100000@hkn.eecs.berkeley.edu>


> As you can see, IOError covers many issues
>
> >>> try:
> ...   fd = open('/home/shoon/xinitrc')
> ... except IOError, e:
> ...   print e[0], e[1]
> ...
> 13 Permission denied
>
> I am sure there is a wrapper for errno somewhere in python.

Here you go:

    http://www.python.org/doc/lib/module-errno.html


Hope this helps!



From wilson@visi.com  Mon Jul 29 02:07:30 2002
From: wilson@visi.com (Tim Wilson)
Date: Sun, 28 Jul 2002 20:07:30 -0500
Subject: [Tutor] Python information  [links for beginning programmers]
In-Reply-To: <Pine.LNX.4.44.0207281705590.16125-100000@hkn.eecs.berkeley.edu>
References: <000e01c23682$b60f4e60$4538d141@bjmartin98> <Pine.LNX.4.44.0207281705590.16125-100000@hkn.eecs.berkeley.edu>
Message-ID: <20020729010730.GA20144@isis.visi.com>

On Sun, Jul 28, 2002 at 05:21:46PM -0700, Danny Yoo wrote:
> 
> "A Non-Programmer's Tutorial for Python", but all of the tutorials there
> are pretty nice.  The Livewires course is also awesome.  Try one of these
> tutorials, and as you play around with Python, you can always ask your
> questions here on Tutor.

Don't forget the Python version of "How to Think Like a Computer Scientist."
I use it for my intro to programming course at Sibley High School. You
can get it (for free) at http://ibiblio.org/obp/thinkCS.php

-Tim

-- 
Tim Wilson      |   Visit Sibley online:   | Check out:
Henry Sibley HS |  http://www.isd197.org   | http://www.zope.com
W. St. Paul, MN |                          | http://slashdot.org
wilson@visi.com |  <dtml-var pithy_quote>  | http://linux.com


From guillermo.fernandez@epfl.ch  Mon Jul 29 05:48:15 2002
From: guillermo.fernandez@epfl.ch (Guillermo Fernandez)
Date: Mon, 29 Jul 2002 14:18:15 +0930
Subject: [Tutor] Copying list contents
Message-ID: <3D44C90F.DBE86B4C@epfl.ch>

hi!

Thanks for the 
mylist=[0] * size
trick. It's neat and quick.

I'm working with lists and I manipulate often. I have discovered that
Python treates the lists like objects, so this operation:
>>> list1=[1, 2, 3]
>>> list2=list1
will not create two listes with the same arguments, but will create two
references to the same object:
>>> list1[2]=4
>>> list2
[1, 2, 4]

In that kind of easy lists there is no problem, I define a function
like:
def copylist(a):
	b=[]
	for element in a:
		b.append(element)
	return b

but I'm working with lists of lists of lists...
Is there a way of copying lists cleanly, or will I have to create a
recursive list copy function?

Thanks,

Guille


From kalle@lysator.liu.se  Mon Jul 29 06:09:11 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Mon, 29 Jul 2002 07:09:11 +0200
Subject: [Tutor] Copying list contents
In-Reply-To: <3D44C90F.DBE86B4C@epfl.ch>
References: <3D44C90F.DBE86B4C@epfl.ch>
Message-ID: <20020729050911.GA1201@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Guillermo Fernandez]
> Is there a way of copying lists cleanly, or will I have to create a
> recursive list copy function?

There is the deepcopy function in the copy module.
http://python.org/doc/current/lib/module-copy.html

Also note that to perform a shallow copy on a list, a common idiom is
to use slice notation:

>>> list2 = list1[:] # creates a shallow copy of list1

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9RM3ydNeA1787sd0RAoOEAJ9D1XUBe9MLzqrLFXMZU83XBqTCEwCfTB1o
4+cV2s0SsRg3ycWe+4WopdY=
=T9Vq
-----END PGP SIGNATURE-----


From dyoo@hkn.eecs.berkeley.edu  Mon Jul 29 06:43:49 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Jul 2002 22:43:49 -0700 (PDT)
Subject: [Tutor] New member question (fwd)
Message-ID: <Pine.LNX.4.44.0207282241590.21637-100000@hkn.eecs.berkeley.edu>

Hi Laney,

Let me forward this to the Tutor mailing list; we often try to keep
everything on Tutor just to keep everyone in the loop.  *grin*


---------- Forwarded message ----------
Date: Sun, 28 Jul 2002 22:31:30 -0400
From: Laney Mills <millsl@cofc.edu>
To: 'Danny Yoo' <dyoo@hkn.eecs.berkeley.edu>
Subject: RE: [Tutor] New member question



Ok Danny,

Here is the problem I was trying to describe:

I made the customary file with the single line

print "Hellow World!"

and saved it as follows:

c:\program files\python21\Laney\hello.py

Then when I try to "import" I get the following.  Strangely notice that it
did run.

Here is the result of file path browser  (hand typed, I couldn;t copy it)

sys.path
C:\Program Files\Python21\Tools\idle
C:\Program Files\Python21\Tools\idle  (there are both these "idle" ones
C:\Program Files\Python21\DLLs
C:\Program Files\Python21\lib
C:\Program Files\Python21\lib\polat-win
C:\Program Files\Python21\lib\lib-tk
C:\Program Files\Python21\


Notice that there is no PYTHONPATH becuase I don't know and can't figure
out how to set it.  Is it done in the autoexec.bat just like path=???

Python 2.1.2 (#31, Jan 15 2002, 17:28:11) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> import hello.py
Hello World!
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in ?
    import hello.py
ImportError: No module named py
>>>

Thanks so much.  I have really been frustrated for months with this issue
and had almost given up.

After we get this path business straight, I'm going to ask how to launch
tkinter.  Is tkinter an alternative to idle??

Laney Mills
-----Original Message-----
From:	Danny Yoo [SMTP:dyoo@hkn.eecs.berkeley.edu]
Sent:	Sunday, July 28, 2002 3:24 PM
To:	Laney Mills
Cc:	'tutor@python.org'
Subject:	Re: [Tutor] New member question



> But if I make a small module and try to open it, the program can't find
> it.  I am suspecting this problem is an issue concerning PYTHONPATH, but
> I'm not sure.  I have read news lists and tutor information and o'reilly
> "learning python", but ALL those sources given answers using concepts
> rather more sophisticated than my actual question.  Any help would be
> greatly appreciated.

That's odd!  Hmmm... I think we might need more information on this one.
How are you trying to open the module?


If you keep all your modules in a standard place, you can add the
environmental variable 'PYTHONPATH', so that Python knows about them.
For example, on my Linux system, I keep a personal directory of modules in
a directory called '/home/dyoo/src/python'.  My PYTHONPATH will look like:

    PYTHONPATH='/home/dyoo/src/python'

and that should be it; afterwards, I can do an 'import
[name-of-my-module]' statement in other programs, and it should import the
module ok.



> Also, what is tkinter and does it come with this distribution?  I can't
> find it, but thought it came with the download from python.org.

Tkinter is a module that provides GUI building support.  You can write
programs that open windows and bring up buttons and menus.  It should be
installed alongside Python if you're using the standard distribution from
Python.org.

If you'd like to read a little more on Tkinter, Fredrik Lundh's "An
Introduction to Tkinter" may whet your appetite:

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


There are other GUI toolkits available for Python; although Tkinter is
standard, another popular one is called "wxPython":

    http://www.wxpython.org/

I have to admit that I haven't tried wxPython yet, but other people on
this list may be able to share their experiences with it.


If you have more questions, please feel free to ask.  We'll be happy to
help!  Off to lunch for me.  *grin* I'll talk to you later!





From dyoo@hkn.eecs.berkeley.edu  Mon Jul 29 06:53:00 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Jul 2002 22:53:00 -0700 (PDT)
Subject: [Tutor] New member question (fwd)
In-Reply-To: <Pine.LNX.4.44.0207282241590.21637-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0207282244360.21637-100000@hkn.eecs.berkeley.edu>


> Notice that there is no PYTHONPATH becuase I don't know and can't figure
> out how to set it.  Is it done in the autoexec.bat just like path=???

Yes, exactly: you can set it there like PATH.



> Python 2.1.2 (#31, Jan 15 2002, 17:28:11) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> IDLE 0.8 -- press F1 for help
> >>> import hello.py
> Hello World!
> Traceback (most recent call last):
>   File "<pyshell#0>", line 1, in ?
>     import hello.py
> ImportError: No module named py


Ah!  When we import modules in Python, it automatically assumes that it's
a '.py' file, so we don't need to write out the module extension.  Try:

###
import hello
###

and you should be in business.  So that error message that you were
getting was complaining about the '.py' part of the import: it wasn't
necessary.



> After we get this path business straight, I'm going to ask how to launch
> tkinter.  Is tkinter an alternative to idle??

Tkinter is a module in Python, and like all modules, all we need to access
it is an import.

###
import Tkinter
###

Tkinter isn't an alternative to IDLE, since it's much more primitive than
a text editor.  It's more like a toolbox of widgets, and, in fact, the
IDLE editor is actually written using Tkinter components.


Hope this helps!



From allyn.@tardigrade.net  Mon Jul 29 10:02:21 2002
From: allyn.@tardigrade.net (Allyn Weaks)
Date: Mon, 29 Jul 2002 02:02:21 -0700
Subject: [Tutor] IOError exception handling
In-Reply-To: <Pine.LNX.4.44.0207281747360.16125-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0207281747360.16125-100000@hkn.eecs.berkeley.edu>
Message-ID: <p0510030db96ab0d85189@[209.221.136.35]>

On 28/7/02, Danny Yoo wrote:
"Sean 'Shaleh' Perry" <shalehperry@attbi.com> wrote

>> As you can see, IOError covers many issues
>>
>> >>> try:
>> ...   fd = open('/home/shoon/xinitrc')
>> ... except IOError, e:
>> ...   print e[0], e[1]
>> ...
>> 13 Permission denied
>>
>> I am sure there is a wrapper for errno somewhere in python.
>
>Here you go:
>
>    http://www.python.org/doc/lib/module-errno.html

Many thanks.  Betwixt the two of you, I've now got:

def errortest():
    try:
        fd = open(filename)
        text = fd.readlines()
        return len(text)
    except IOError, e:
        if e[0] == 2: return 0  # file not found
        print e                 # any other error
        sys.exit(1)

Which works when I force errors of several types.  Do I need the
sys.exit(1), and is 1 a reasonable generic number?  I've seen it in
several examples, and since I'm still partly in monkey-see, monkey-do
mode, I stuck it in even though it superficially works without it. :-)
-- 
Allyn Weaks    allyn@tardigrade.net   Seattle, WA  Sunset zone 5
Pacific NW Native Wildlife Gardening: http://www.tardigrade.org/natives/
"The benefit of even limited monopolies is too doubtful, to be opposed
to that of their general suppression."  Thomas Jefferson


From allyn.@tardigrade.net  Mon Jul 29 10:29:42 2002
From: allyn.@tardigrade.net (Allyn Weaks)
Date: Mon, 29 Jul 2002 02:29:42 -0700
Subject: [Tutor] Printing a formatted list (of lists)
Message-ID: <p0510030eb96ab314d7f5@[209.221.136.35]>

Python 2.n on unix.

I have a table that's a list of lists (values can be mixed
numbers/text).  Is there a clean way to print a formatted list?  What I
have works, but it seems that there ought to be a more list-oriented
way of formatting the list part.  Or is this one of those places where
one accepts the explicit loop?  I've tried out list comprehension
variations 'til I'm dizzy with nothing but assorted errors.

for j in range(len(table)):
    print `table[j]`.rjust(columnwidth),

Thanks!
-- 
Allyn Weaks    allyn@tardigrade.net   Seattle, WA  Sunset zone 5
Pacific NW Native Wildlife Gardening: http://www.tardigrade.org/natives/
"The benefit of even limited monopolies is too doubtful, to be opposed
to that of their general suppression."  Thomas Jefferson


From shalehperry@attbi.com  Mon Jul 29 10:34:10 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 29 Jul 2002 02:34:10 -0700 (PDT)
Subject: [Tutor] IOError exception handling
In-Reply-To: <p0510030db96ab0d85189@[209.221.136.35]>
Message-ID: <XFMail.20020729023410.shalehperry@attbi.com>

> 
> Which works when I force errors of several types.  Do I need the
> sys.exit(1), and is 1 a reasonable generic number?  I've seen it in
> several examples, and since I'm still partly in monkey-see, monkey-do
> mode, I stuck it in even though it superficially works without it. :-)

without the sys.exit you would not exit (-: if you "need" it is another matter
and up to you.

As to the parameter for sys.exit(), 0 is success and non 0 is failure.  I often
use -1 for input issues and 1 for faults.

i.e.

if len(sys.argv) != 2:
  print 'Usage: app input'
  sys.exit(-1)

if not file_exists:
  sys.exit(1)


From lumbricus@gmx.net  Mon Jul 29 10:41:54 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Mon, 29 Jul 2002 11:41:54 +0200 (MEST)
Subject: [Tutor] IOError exception handling
References: <p0510030db96ab0d85189@[209.221.136.35]>
Message-ID: <21665.1027935714@www28.gmx.net>

> On 28/7/02, Danny Yoo wrote:
> "Sean 'Shaleh' Perry" <shalehperry@attbi.com> wrote

[ snip ]

> Many thanks.  Betwixt the two of you, I've now got:
> 
> def errortest():
>     try:
>         fd = open(filename)
>         text = fd.readlines()
>         return len(text)
>     except IOError, e:
>         if e[0] == 2: return 0  # file not found
>         print e                 # any other error
>         sys.exit(1)
> 
> Which works when I force errors of several types.  Do I need the
> sys.exit(1), and is 1 a reasonable generic number?  I've seen it in
> several examples, and since I'm still partly in monkey-see, monkey-do
> mode, I stuck it in even though it superficially works without it. :-)

How is that:

print errno.errorcode[e]
sys.exit(errno)

HTH, HAND
J"o!

-- 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net



From scot@possum.in-berlin.de  Mon Jul 29 09:33:37 2002
From: scot@possum.in-berlin.de (Scot W. Stevenson)
Date: Mon, 29 Jul 2002 10:33:37 +0200
Subject: [Tutor] Python information
In-Reply-To: <000f01c23686$7ef99a80$f5e03942@joeltklrijxxms>
References: <000e01c23682$b60f4e60$4538d141@bjmartin98> <000f01c23686$7ef99a80$f5e03942@joeltklrijxxms>
Message-ID: <200207291033.37592.scot@possum.in-berlin.de>

Hi,=20

> Almost all python
> programmers that I've run into, whether here on this list, the
> newsgroup, or IRC chats, have been the most helpful group of people I'v=
e
> run across. =20

They also tend to be witty and explain things in a humerous way that is=20
entertaining for its own sake. I'm not sure if this is the Monty Python=20
lunacy oozing thru everybody's keybord every time they type "import", or=20
just the result of having lots of mental capacity left over that other=20
programmers burn on placing braces, but it does make the tutor list a fun=
=20
group to hang out with.

Y, Scot

--=20
  Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany



From scot@possum.in-berlin.de  Mon Jul 29 10:48:01 2002
From: scot@possum.in-berlin.de (Scot W. Stevenson)
Date: Mon, 29 Jul 2002 11:48:01 +0200
Subject: [Tutor] printing columns
In-Reply-To: <20020725222721.51da606f.ckasso@sprynet.com>
References: <Pine.LNX.4.44.0207251539370.13973-100000@hkn.eecs.berkeley.edu> <MPEOIFCOPCIHEDCLBLPBIEBKCBAA.rob@uselesspython.com> <20020725222721.51da606f.ckasso@sprynet.com>
Message-ID: <200207291148.01542.scot@possum.in-berlin.de>

Hello Chris,=20

Just curious - there any reason you used

> # find longest string
> i =3D 0
> longestLength =3D len(menuItems[i])
> while i < len(menuItems):
> =09x =3D len(menuItems[i])
> =09i =3D i + 1
> =09if x > longestLength:
> =09=09longestLength =3D x

instead of something like

# find longest string
longestLength =3D 0
for item in menuItems:
    x =3D len(item)
    if x > longestLength:
        longestLength =3D x

which seems to do the same thing with less indexing?

Y, Scot

--=20
  Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany



From scot@possum.in-berlin.de  Mon Jul 29 10:40:57 2002
From: scot@possum.in-berlin.de (Scot W. Stevenson)
Date: Mon, 29 Jul 2002 11:40:57 +0200
Subject: [Tutor] Python information
In-Reply-To: <000e01c23682$b60f4e60$4538d141@bjmartin98>
References: <000e01c23682$b60f4e60$4538d141@bjmartin98>
Message-ID: <200207291140.57176.scot@possum.in-berlin.de>

Hello Billie,=20

> Every place I looked on the net (I spent 10 hrs looking) assumes lots o=
f
> Python programming under your belt or that you are knowledgeable in C++
> or a Linux follower.

There are quite a few online and book resources out there on starting=20
programming from scratch. The trick - as with any other field you are new=
=20
to, from rose gardening to nuclear physics - is to avoid the adults'=20
section and look for an introduction for high school kids. No kidding -=20
they are usually better written and don't assume as much. _Never_ touch=20
anything that is written for undergraduates, since everybody seems to=20
think they are masochists.=20

Others have already added lots of links, so just one more thing:=20

> Every place I looked on the net (I spent 10 hrs looking) assumes lots o=
f=20
> Python programming under your belt or that you are knowledgeable in C++=
=20
> or a Linux follower.

My personal interpretation, if it makes you feel better:

C unfortunately is something of the lingua franca of computer languages=20
because it works hand in glove with Unix (and therefore Linux). Nowadays,=
=20
almost all operating systems in our price range are some form of Unix=20
(even Apple's OS X is basically just BSD with some pretty colors), with=20
the Microsoft family the (admittedly very big) exception. Since Microsoft=
=20
won't let you see its code, the people who seriously enjoy playing around=
=20
with computers and write the hard core Open Source stuff are drawn to=20
Linux, and therefore all know C.=20

I agree that this is a bummer, since programming in C is basically like=20
using a bullwhip: You need years of practice, and even then it still tend=
s=20
to switch back and cut you in the face; even if you do it right, it can=20
cut thru skin, muscle, and bone. There are very few times when you really=
=20
do need a bullwhip (unless, of course, your first name is "Indiana").=20
Unfortunately, there is this image that they are really cool, so we have=20
all of these teenager types running around in fake black leather trying t=
o=20
impress each other with the loudest cracking sound. The=20
Real-Men-use-C-crowd is terribly annoying, but they are useful for=20
operating systems and games, so we're going to have to live with them.=20

One way to get your revenge is to learn Python and happily program whatev=
er=20
they are trying to do in parallel. This is lots of fun. Even as a newbie,=
=20
you'll usually be done with the whole program while that oh so cool C=20
coder is still figuring out how to get his character array assembled into=
=20
a string without producing a buffer overflow that will let every cracker=20
from here to Seoul take over his computer, infiltrate the Internet and=20
destroy Western civilization as we know it. And you'll still have time=20
left over to follow a life style based on applied Brucian philosophy...

Y, Scot

--=20
  Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany



From alan.gauld@bt.com  Mon Jul 29 10:44:59 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 29 Jul 2002 10:44:59 +0100
Subject: [Tutor] New member question
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A3@mbtlipnt02.btlabs.bt.co.uk>

> Tkinter is a module that provides GUI building support.  ...
> It should be installed alongside Python if you're using 
> the standard distribution from Python.org.

In fact it *must* be installed OK since you can get IDLE 
to run and IDLE is built using Tkinter.

> There are other GUI toolkits available for Python; 
> although Tkinter is standard, another popular one 
> is called "wxPython":

For a very basic intro (pre Lundh standard) visit my 
web tutor and go to the GUI programming page. There 
you'll find an intro to Tkinter plus a wxPython version 
of the same tiny sample program for comparison.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld


From scot@possum.in-berlin.de  Mon Jul 29 10:58:56 2002
From: scot@possum.in-berlin.de (Scot W. Stevenson)
Date: Mon, 29 Jul 2002 11:58:56 +0200
Subject: [Tutor] printing columns
In-Reply-To: <200207291148.01542.scot@possum.in-berlin.de>
References: <Pine.LNX.4.44.0207251539370.13973-100000@hkn.eecs.berkeley.edu> <20020725222721.51da606f.ckasso@sprynet.com> <200207291148.01542.scot@possum.in-berlin.de>
Message-ID: <200207291158.56677.scot@possum.in-berlin.de>

Hello Chris,=20

just thought of another variant instead of my

> # find longest string
> longestLength =3D 0
> for item in menuItems:
>     x =3D len(item)
>     if x > longestLength:
>         longestLength =3D x

that is even shorter: =20

# find longest string
longestLength =3D 0
for item in menuItems:
    longestLength =3D max(len(item), longestLength)

The output seems to be the same...but I'm never sure about stuff like=20
memory use and speed...

Y, Scot


--=20
  Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany



From alan.gauld@bt.com  Mon Jul 29 10:54:19 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 29 Jul 2002 10:54:19 +0100
Subject: [Tutor] Python information
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A4@mbtlipnt02.btlabs.bt.co.uk>

Is this a troll by any chance?? Whatever I'll bite, 
the summary might be useful...

>  Python is a great program for a first programming language. 

Tis true.

> Tell me why then there is only 2 tutorials on the net 
> that teaches it from the beginning and assuming the 
> reader has no other language experience 

Tis not so. The Newbies page on the Python web site 
has several tutors including my own...

> and absolutely no books that doesn't assume the 
> reader knows another language.  None, zero, zip!

Again wrong. Both Ivan Laningham's "Teach Yourself 
Python in 24 hours" and my own "Learn to Program 
using Python" assume a complete beginner. We take 
slightly different routes: Ivan concentrates on 
teaching pure Python to beginners, I teach programming 
using Python to illustrate the concepts. But both 
are books for sure! :-)

> Every place I looked on the net (I spent 10 hrs looking) 
> assumes lots of Python programming under your belt 
> or that you are knowledgeable in C++ or a Linux follower.

Did you try the Python website page for non programmers?

> Why are Python programmers so selfish with their knowledge.  

I'd argue that the Python community is one of the most 
willing to share bodies of folks on the net. I guess 
you've been looking in the wrong places!

> I like this language and would like to learn more but 
> if I don't know anything how can I ask a question, 
> or further my learning in Python.

Start with Danny's IDLE intro, then progress to my tutor
(or Josh's or "How to Think like..." etc) then move onto 
the official tutor that comes with Python and finally 
read "Dive Into Python" and Eckel's "Thinking in Python".
Then go write a program.

Each time on that journey you don't understand something 
send an email to this list...

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld@bt.com  Mon Jul 29 11:06:24 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 29 Jul 2002 11:06:24 +0100
Subject: [Tutor] A few comparative perl/python questions
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A5@mbtlipnt02.btlabs.bt.co.uk>

> > Does python have anything like Perl's || die, flock(), or seek()
> > functions?  (What are they?)

The previous answers have been appropriate but it occurs to me that a non
pythonic but literal translattion of Perl's

Foo() || die

idiom is possible in Python:

Foo() or raise SystemExit

The '||' is just Perl's logical OR and relies on 
short-circuit evaluation such that if the first 
value( Foo() )  is true we don't need to evaluate 
the second item. Pythons 'or' operator does the same. 

However although easy to translate it's not very 
Pythonic and I don't recommend it... 
Just noting the possibility.

Alan G.



From alan.gauld@bt.com  Mon Jul 29 11:11:12 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 29 Jul 2002 11:11:12 +0100
Subject: [Tutor] Copying list contents
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A6@mbtlipnt02.btlabs.bt.co.uk>

> Python treates the lists like objects

All python variables are references, regardless of the 
object to which they point.

> def copylist(a):
     return a[:]  # list slicing the whole list creates a copy.

The map and filter functions can also be used to copy lists
with various element modifications applied en route.

And zip() can be used to join lists together.

> but I'm working with lists of lists of lists...

There is also a deepcopy module for copying nested lists.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld@bt.com  Mon Jul 29 11:19:06 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 29 Jul 2002 11:19:06 +0100
Subject: [Tutor] IOError exception handling
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A7@mbtlipnt02.btlabs.bt.co.uk>

> Many thanks.  Betwixt the two of you, I've now got:
> 
> def errortest():
>     try: ...
>     except IOError, e:
>         if e[0] == 2: return 0  # file not found
>         print e                 # any other error
>         sys.exit(1)

A minor point. Inside a function rather than use sys.exit() 
I prefer to "raise SystemExit"

This has the same effect but avoids the need to import sys.

Just a thought. 
(And no my tutor doesn't (yet) mention this, I only discovered 
the advantages of SystemExit after I wrote the tutor! :-)

Alan G.


From lumbricus@gmx.net  Mon Jul 29 11:39:19 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Mon, 29 Jul 2002 12:39:19 +0200 (MEST)
Subject: [Tutor] Printing a formatted list (of lists)
References: <p0510030eb96ab314d7f5@[209.221.136.35]>
Message-ID: <14840.1027939159@www28.gmx.net>

> Python 2.n on unix.
> 
> I have a table that's a list of lists (values can be mixed
> numbers/text).  Is there a clean way to print a formatted list?  What I
> have works, but it seems that there ought to be a more list-oriented
> way of formatting the list part.  Or is this one of those places where
> one accepts the explicit loop?  I've tried out list comprehension
> variations 'til I'm dizzy with nothing but assorted errors.
> 
> for j in range(len(table)):
>     print `table[j]`.rjust(columnwidth),

split and join?
(string methods)

> Thanks!

HTH, HAND
J"o!

-- 


-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net



From lumbricus@gmx.net  Mon Jul 29 11:43:29 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Mon, 29 Jul 2002 12:43:29 +0200 (MEST)
Subject: [Tutor] A few comparative perl/python questions
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A5@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <24914.1027939409@www28.gmx.net>

Hello!
 
> Foo() || die
> 
> idiom is possible in Python:
> 
> Foo() or raise SystemExit

Now  this is beautyful.
 
> The '||' is just Perl's logical OR and relies on 
> short-circuit evaluation such that if the first 
> value( Foo() )  is true we don't need to evaluate 
> the second item. Pythons 'or' operator does the same. 
> 
> However although easy to translate it's not very 
> Pythonic and I don't recommend it... 

Is there a special reason?
I like it.

> Just noting the possibility.
> 
> Alan G.
> 

Greetings J"o!

-- 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net



From cmhowe@patriot.net  Mon Jul 29 12:55:46 2002
From: cmhowe@patriot.net (Charles M Howe)
Date: Mon, 29 Jul 2002 07:55:46 -0400
Subject: [Tutor] Full screen in text mode?
Message-ID: <3D452D42.1E4A664C@patriot.net>

Tuts, (hope this is ok as a salutation)

I am undertaking a task that will (very likely) require a GUI if I like
it enough to release it to the world. However, if I could control the
entire screen in text mode -- colorize printing, maybe have some large
fonts, move about a fixed screen, create a few icons -- I would stay in
text mode until (and if) I basically solve the problem. So my question
is, Is this possible?

Charlie (Charles M Howe)




From lumbricus@gmx.net  Mon Jul 29 12:41:05 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Mon, 29 Jul 2002 13:41:05 +0200 (MEST)
Subject: [Tutor] Full screen in text mode?
References: <3D452D42.1E4A664C@patriot.net>
Message-ID: <17519.1027942865@www28.gmx.net>

> Tuts, (hope this is ok as a salutation)

Well, what does it mean?
It sounds nasty.
 
> I am undertaking a task that will (very likely) require a GUI if I like
> it enough to release it to the world. However, if I could control the
> entire screen in text mode -- colorize printing, maybe have some large
> fonts, move about a fixed screen, create a few icons -- I would stay in
> text mode until (and if) I basically solve the problem. So my question
> is, Is this possible?

except for the icons:
man [n]curses
 
> Charlie (Charles M Howe)

HTH, HAND
J"o!

-- 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net



From printers@sendme.cz  Mon Jul 29 13:11:28 2002
From: printers@sendme.cz (A)
Date: Mon, 29 Jul 2002 14:11:28 +0200
Subject: [Tutor] How to redirect output to browser - second request for help
Message-ID: <3D454D10.11064.218373@localhost>

Hi,
Is it possible to send output continuously to a web browser?. 
For example I have the following code
>>> import httplib
>>> h = httplib.HTTP('www.cwi.nl')
>>> h.putrequest('GET', '/index.html')
>>> h.putheader('Accept', 'text/html')
>>> h.putheader('Accept', 'text/plain')
>>> h.endheaders()
I would like to send coming bytes ( here coming bytes of 
/index.html file)  directly to web browser in the same 
way as I use a web browser on my computer to open a 
webpage where I can see a progress how webpage is being 
opened.
In other words I do NOT want to wait for downloading the 
whole file and only after that open that downloaded file 
in a web browser. 

Thank you for help
Ladislav




From rob@uselesspython.com  Mon Jul 29 13:58:23 2002
From: rob@uselesspython.com (Rob)
Date: Mon, 29 Jul 2002 07:58:23 -0500
Subject: [Tutor] Python information
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A4@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <MPEOIFCOPCIHEDCLBLPBKEFECBAA.rob@uselesspython.com>

I'll pose this question to the list (especially the newbies): What would you
like to see demonstrated in a tutorial for absolute programming newbies? Be
as specific or as general as you like. I'd be willing to work on producing
such a tutorial, and I'd bet that others on this list will be willing to
work on it as well. (And you just might receive links to tutorials already
on the web that provide some of your answers.)

Now, on with the post:

Python is indeed a great starter language. I even see it receiving more and
more respect from a friend of mine who initially scoffed in the way he
scoffs at all high-level languages. When he saw how much my Python tinkering
had equipped me to understand C, C++, and Java, he changed his tune. The
hardest-to-impress person I know has finally concluded that this is a good
teaching language when he saw how it really does imprint good programming
practices on people who might be more easily led astray in other
circumstances.

There are lots of good tutorials out there, and all you need is one to get
you started. I got my start by opening up the official tutorial that shipped
with my Python distribution, starting up IDLE, and typing in code as I went.
As I did this, I found myself trying to do things differently from the
tutorial's way as well, just to see what happened. I was Having Fun
Programming within minutes!

I stumbled across the Python Tutor email list and started seeing that other
people had some of the same questions I had, and asked a few of my own here
and there. It seems wonderful and amazing to me that even on
comp.lang.python you can find such knowledgeable people who actually want to
help. I have never experienced a lack of support from the Python community.
This seems to be something I have in common with a good number of other
people out there. And the archives of both this email list and
comp.lang.python are loaded with neat gems of explanation and example.

Useless Python has also been recommended a number of times lately, which
puts a smile on my face. (I'm the maintainer of the site, and it's a pretty
good concept despite this fact! heehee) Since you can learn a lot by looking
at source code that runs at all, even if it's not the *best* in the world,
Useless makes a wide variety of sample stuff available. There's also the
Python Cookbook online, as well as a mass of personal home pages.

Rob
http://uselesspython.com

> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> alan.gauld@bt.com
> Sent: Monday, July 29, 2002 4:54 AM
> To: bjmartin98@pennswoods.net; tutor@python.org
> Subject: RE: [Tutor] Python information
>
>
> Is this a troll by any chance?? Whatever I'll bite,
> the summary might be useful...
>
> >  Python is a great program for a first programming language.
>
> Tis true.
>
> > Tell me why then there is only 2 tutorials on the net
> > that teaches it from the beginning and assuming the
> > reader has no other language experience
>
> Tis not so. The Newbies page on the Python web site
> has several tutors including my own...
>
> > and absolutely no books that doesn't assume the
> > reader knows another language.  None, zero, zip!
>
> Again wrong. Both Ivan Laningham's "Teach Yourself
> Python in 24 hours" and my own "Learn to Program
> using Python" assume a complete beginner. We take
> slightly different routes: Ivan concentrates on
> teaching pure Python to beginners, I teach programming
> using Python to illustrate the concepts. But both
> are books for sure! :-)
>
> > Every place I looked on the net (I spent 10 hrs looking)
> > assumes lots of Python programming under your belt
> > or that you are knowledgeable in C++ or a Linux follower.
>
> Did you try the Python website page for non programmers?
>
> > Why are Python programmers so selfish with their knowledge.
>
> I'd argue that the Python community is one of the most
> willing to share bodies of folks on the net. I guess
> you've been looking in the wrong places!
>
> > I like this language and would like to learn more but
> > if I don't know anything how can I ask a question,
> > or further my learning in Python.
>
> Start with Danny's IDLE intro, then progress to my tutor
> (or Josh's or "How to Think like..." etc) then move onto
> the official tutor that comes with Python and finally
> read "Dive Into Python" and Eckel's "Thinking in Python".
> Then go write a program.
>
> Each time on that journey you don't understand something
> send an email to this list...
>
> Alan g.
> Author of the 'Learning to Program' web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From fgranger@altern.org  Mon Jul 29 14:09:57 2002
From: fgranger@altern.org (Francois Granger)
Date: Mon, 29 Jul 2002 15:09:57 +0200
Subject: [Tutor] Python information
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A4@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <B96B0B45.53034%fgranger@altern.org>

on 29/07/02 11:54, alan.gauld@bt.com at alan.gauld@bt.com wrote:

> Start with [2] Danny's IDLE intro, then progress to [3] my tutor
> (or Josh's or "How to Think like..." etc) then move onto
> the official tutor that comes with Python and finally
> read "Dive Into Python" and Eckel's "Thinking in Python".
> Then [1]go write a program.

I reordered these items following my way of doing things ;-)
And [1] must be redone at each step ;-)

--=20
Fran=E7ois Granger
fgranger@altern.org



From einarth@decode.is  Mon Jul 29 14:11:17 2002
From: einarth@decode.is (Einar Th. Einarsson)
Date: Mon, 29 Jul 2002 13:11:17 +0000
Subject: [Tutor] Python information
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A4@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A4@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <200207291311.21296.einarth@decode.is>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

I think this may be of some help.

A tutorial which assumes no prior programming experience, focus is on=20
programming in general using python as a teaching laguage. Intented as a=20
first programming course textbook published on the web and copyleft'd:

http://www.ibiblio.org/obp/thinkCSpy/index.htm


- --=20
Old man: Take this doll, but beware; it carries a terrible curse.
Homer: Ooo, that's bad.
Old man: But it comes with a free serving of frozen yogurt!
Homer: That's good!
Old man: The frozen yogurt is also cursed.
Homer: That's bad.
Old man: But it comes with your choice of toppings!
Homer: That's good!
Old man: The toppings contain potassium benzoate...
Homer: (confused look)
Old man: That's bad.
Homer: Can I go now?

Yours etc.
    Einar Th.

-----BEGIN PGP SIGNATURE-----
Version: PGP 6.5.8

iQA/AwUBPUU++G1/ORZtyd/tEQJ0nQCgkTG8CQUv41yPUZlv0MTTTEEgVckAoLXj
YdiDaDgWC19xIRWXb0sLEi8K
=3DwzZ6
-----END PGP SIGNATURE-----



From ckasso@sprynet.com  Mon Jul 29 15:36:25 2002
From: ckasso@sprynet.com (Chris Kassopulo)
Date: Mon, 29 Jul 2002 10:36:25 -0400
Subject: [Tutor] printing columns
In-Reply-To: <200207291148.01542.scot@possum.in-berlin.de>
References: <Pine.LNX.4.44.0207251539370.13973-100000@hkn.eecs.berkeley.edu>
 <MPEOIFCOPCIHEDCLBLPBIEBKCBAA.rob@uselesspython.com>
 <20020725222721.51da606f.ckasso@sprynet.com>
 <200207291148.01542.scot@possum.in-berlin.de>
Message-ID: <20020729103625.14e8533a.ckasso@sprynet.com>

On Mon, 29 Jul 2002 11:48:01 +0200
"Scot W. Stevenson" <scot@possum.in-berlin.de> wrote:

> Hello Chris, 
> 
> Just curious - there any reason you used
> 
> > # find longest string
> > i = 0
> > longestLength = len(menuItems[i])
> > while i < len(menuItems):
> > 	x = len(menuItems[i])
> > 	i = i + 1
> > 	if x > longestLength:
> > 		longestLength = x
> 
> instead of something like
> 
> # find longest string
> longestLength = 0
> for item in menuItems:
>     x = len(item)
>     if x > longestLength:
>         longestLength = x
> 
> which seems to do the same thing with less indexing?
> 
> Y, Scot
> 

Hi Scot,

I would like to say that there are many technical
reasons I chose to use a while loop instead of the
for loop you suggest.  However, "newbie"ism is the
only reason I can offer. ;-)

Thanks for the pointer.
-- 
Chris Kassopulo _/\_ Linux User #199893 _/\_ Slackware



From fgranger@altern.org  Mon Jul 29 17:06:02 2002
From: fgranger@altern.org (Francois Granger)
Date: Mon, 29 Jul 2002 18:06:02 +0200
Subject: [Tutor] Python information
In-Reply-To: <MPEOIFCOPCIHEDCLBLPBKEFECBAA.rob@uselesspython.com>
Message-ID: <B96B348A.53065%fgranger@altern.org>

on 29/07/02 14:58, Rob at rob@uselesspython.com wrote:

> I'll pose this question to the list (especially the newbies): What would =
you
> like to see demonstrated in a tutorial for absolute programming newbies? =
Be
> as specific or as general as you like. I'd be willing to work on producin=
g
> such a tutorial, and I'd bet that others on this list will be willing to
> work on it as well. (And you just might receive links to tutorials alread=
y
> on the web that provide some of your answers.)

>From my point of view, what was most missing, after the first steps in
Pyhton was a set of code snippet to achieve some common tasks.

So I started a FAQ based on this (don't stop at the mac in the name, most o=
f
it apply to any Python setup.

http://francois.granger.free.fr/MacPython/faq/MacPyBeg.html

Most of it came from carefull reading of c.l.py. But this list could be a
good source of these code snippets as well. Because of lack of time, and
lack of feed back from readers, I did not updated it very often. But it
still interrest some readers. The most accessed page in july got 27 hits.

I am eventually willing to improve it, but I don't spend that much time
reading c.l.py now because of other occupations.

--=20
Fran=E7ois Granger
fgranger@altern.org



From python-help@python.org  Mon Jul 29 15:49:45 2002
From: python-help@python.org (Alex Martelli)
Date: Mon, 29 Jul 2002 16:49:45 +0200
Subject: [Tutor] Re: [Python-Help] How to redirect output to browser - second request for help
In-Reply-To: <3D454D10.11064.218373@localhost>
References: <3D454D10.11064.218373@localhost>
Message-ID: <E17ZBqk-00065T-00@mail.python.org>

On Monday 29 July 2002 02:11 pm, A wrote:
> Hi,
> Is it possible to send output continuously to a web browser?.

Module webbrowser lets you direct the browser to any URL
of your choice.  However, to perform the task you require...:

> For example I have the following code
>
> >>> import httplib
> >>> h = httplib.HTTP('www.cwi.nl')
> >>> h.putrequest('GET', '/index.html')
> >>> h.putheader('Accept', 'text/html')
> >>> h.putheader('Accept', 'text/plain')
> >>> h.endheaders()
>
> I would like to send coming bytes ( here coming bytes of
> /index.html file)  directly to web browser in the same
> way as I use a web browser on my computer to open a
> webpage where I can see a progress how webpage is being
> opened.
> In other words I do NOT want to wait for downloading the
> whole file and only after that open that downloaded file
> in a web browser.

...that URL must also be supplied by your Python program.

In other words, you must implement a webserver and feed
the data as it comes to the browser.  Python supplies
modules in its standard library that are web browsers of
various capabilities, you can subclass and customize one
of those.  To get simultaneous operation between the data
arriving from the remote server and the data you feed to
the waiting browser, you will need either to write your Python
program as multi-threaded (and I suggest using module
Queue to communicate between the threads, it's simple
and natural), or use asynchronous even-driven programming
(the Python standard libraries come with two modules that
support such programming, asyncore and asynchat, but a
vastly more powerful arrangement for both asynchronous
servers and clients is found in the vast Python package
"Twisted Matrix", www.twistedmatrix.com, specifically in
subpackage twisted.internet).


In other words: the answer to your question is YES, but the
amount of programming (and the necessary skill, in Python
in particular and in programming in general) to achieve
your goal can be surprisingly high.  Were I approached as
a freelance consultant by a client requesting such a program,
I would size it at about 12 hours (and that's because I'm
already somewhat skilled in twisted.matrix, as well as an
expert programmer -- i.e., my consulting hours do _not_ come
cheap:-).  That's for a finished product of course, a rough
and ready feasibiliy-check prototype might take me less!


Alex


From jeff@ccvcorp.com  Mon Jul 29 18:08:56 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 29 Jul 2002 10:08:56 -0700
Subject: [Tutor] get local time ????
References: <HNEOKHJLEPAHPMJCIDCMOEEACCAA.runsun@bilbo.bio.purdue.edu>
Message-ID: <3D4576A8.8AD7866C@ccvcorp.com>

runsun wrote:

> How can I get the time -- as my local time -- when a
> visitor visits my far-away website ???

I'm not sure of the specifics of your situation, as far as where your
code is running, etc, but ISTM that the solution to your problem is to
use UTC time (formerly/aslo known as GMT) as a baseline.  When your
(distant) webserver logs a timestamp, convert its local time to UTC.
When you view the logs on your machine, convert from UTC to your local
time.  If you always store all of your times as UTC, then it's fairly
simple to convert that to the appropriate local time for any location
(as long as you know the time zone ;) ).

I still have not done any significant web programming, so I can't help
you with logging of page visits, but I'm sure it can be done.

Jeff Shannon
Technician/Programmer
Credit International




From alan.gauld@bt.com  Mon Jul 29 18:08:02 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 29 Jul 2002 18:08:02 +0100
Subject: [Tutor] Full screen in text mode?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7AE@mbtlipnt02.btlabs.bt.co.uk>

> I am undertaking a task that will (very likely) require a GUI 
> if I like it enough to release it to the world. 


> entire screen in text mode -- colorize printing, 
> maybe have some large fonts, move about a fixed screen, 
> create a few icons 

Icons are tricky but the other things an be done on 
Unix using curses. If you are on Windows then its harder 
but you can fake some of it using ANSO codes in a DOS box.
Also using the extended character set you can draw boxes, 
lines etc. (You need to load ANSI.SYS too)

However such an approach is likely to compromise your 
design for when you want to add a GUI. Try to build a 
vanilla text mode solution if poss then add the GUI, 
forget about text mode unless you are on Unix.

Alan G.


From jeff@ccvcorp.com  Mon Jul 29 18:28:45 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 29 Jul 2002 10:28:45 -0700
Subject: [Tutor] Printing a formatted list (of lists)
References: <p0510030eb96ab314d7f5@[209.221.136.35]>
Message-ID: <3D457B4D.48014364@ccvcorp.com>

Allyn Weaks wrote:

> Python 2.n on unix.
>
> I have a table that's a list of lists (values can be mixed
> numbers/text).  Is there a clean way to print a formatted list?  What I
> have works, but it seems that there ought to be a more list-oriented
> way of formatting the list part.  Or is this one of those places where
> one accepts the explicit loop?  I've tried out list comprehension
> variations 'til I'm dizzy with nothing but assorted errors.
>
> for j in range(len(table)):
>     print `table[j]`.rjust(columnwidth),

Well, the above snippet can be simplified as

for cell in table:
    print cell.rjust(columnwidth),

but that's not much of an improvement.  (I also don't think it does what you
want, really, anyhow, but my code will do the same thing as yours.)

If you know the number (and width) of columns in your table, then you can do
something like this:

for line in table:
    print "%15s %15s %15s %15s" % tuple(line)

This has the advantage that you can adjust the size of each column, if you
want -- the first column can be half as wide as the second, simply by
modifying the format numbers.

If you *don't* know the number of columns, but have a good idea what width
you want to use, then you can maybe use a list comprehension to create
column-width strings, then join those together and print the result:

for line in table:
    columns = ["%15s" % cell for cell in line]
    print ' '.join(columns)

If you don't know what your maximum column width should be, then you'll have
to iterate through the entire list of lists to determine what the longest
item is.  Using that length, you can then generate a format string for the
above snippet (the "%15s" is the format string, you'd need to assemble one
with '15' replaced by whatever the maximum width should be).

Hope this at least gives you some ideas...

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Mon Jul 29 18:32:48 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 29 Jul 2002 10:32:48 -0700
Subject: [Tutor] printing columns
References: <Pine.LNX.4.44.0207251539370.13973-100000@hkn.eecs.berkeley.edu> <20020725222721.51da606f.ckasso@sprynet.com> <200207291148.01542.scot@possum.in-berlin.de> <200207291158.56677.scot@possum.in-berlin.de>
Message-ID: <3D457C40.261FCD69@ccvcorp.com>


"Scot W. Stevenson" wrote:

> that is even shorter:
>
> # find longest string
> longestLength = 0
> for item in menuItems:
>     longestLength = max(len(item), longestLength)

Another possibility would be:

    longestLength = max( map(len, menuItems) )

or something equivalent using a list comprehension:

    longestLength = max( [len(item) for item in menuItems] )

Again, I'm not sure how this compares as far as memory/speed...

Jeff Shannon
Technician/Programmer
Credit International




From rob@uselesspython.com  Mon Jul 29 19:57:13 2002
From: rob@uselesspython.com (Rob)
Date: Mon, 29 Jul 2002 13:57:13 -0500
Subject: [Tutor] Python information
In-Reply-To: <B96B348A.53065%fgranger@altern.org>
Message-ID: <MPEOIFCOPCIHEDCLBLPBIEGDCBAA.rob@uselesspython.com>

My experience also seems to suggest that people want access to a good
collection of code snippets while learning. The most hits Useless Python has
picked up in any single day I've made note of was just under 13,000 (for the
whole site, of course). I've calculated page views and such based on the
available statistics and found that after images and style sheets are
factored out, the tutorials and source pages on Useless were still receiving
a massive amount of traffic compared with what I would have suspected.

If only the site had a better manager than me.....

heh

Rob
http://uselesspython.com

> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Francois Granger
> Sent: Monday, July 29, 2002 11:06 AM
> To: 'Tutor@Python. Org'
> Subject: Re: [Tutor] Python information
>
>
> on 29/07/02 14:58, Rob at rob@uselesspython.com wrote:
>
> > I'll pose this question to the list (especially the newbies):
> What would you
> > like to see demonstrated in a tutorial for absolute programming
> newbies? Be
> > as specific or as general as you like. I'd be willing to work
> on producing
> > such a tutorial, and I'd bet that others on this list will be willing to
> > work on it as well. (And you just might receive links to
> tutorials already
> > on the web that provide some of your answers.)
>
> From my point of view, what was most missing, after the first steps in
> Pyhton was a set of code snippet to achieve some common tasks.
>
> So I started a FAQ based on this (don't stop at the mac in the
> name, most of
> it apply to any Python setup.
>
> http://francois.granger.free.fr/MacPython/faq/MacPyBeg.html
>
> Most of it came from carefull reading of c.l.py. But this list could be a
> good source of these code snippets as well. Because of lack of time, and
> lack of feed back from readers, I did not updated it very often. But it
> still interrest some readers. The most accessed page in july got 27 hits.
>
> I am eventually willing to improve it, but I don't spend that much time
> reading c.l.py now because of other occupations.
>
> --
> François Granger
> fgranger@altern.org
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From troels@kvaksalver.dk  Tue Jul 30 02:02:57 2002
From: troels@kvaksalver.dk (Troels Leth Petersen)
Date: Tue, 30 Jul 2002 03:02:57 +0200
Subject: [Tutor] Comparing Time.
Message-ID: <002701c23764$d7ab4be0$0a01a8c0@allah>

Hi,

I am reading 'How to Think Like A Computer Scientist' - and have done
the following exercise:

"As a second exercise, write a boolean function after that takes two
Time objects, t1 and t2, as arguments, and returns true (1) if t1
follows t2 chronologically and false (0) otherwise. "

And the Time object is a very simple object with 3 attributes: hours,
minutes, seconds. As said I did the above exercise but in a
non-elegant way using 9 if statements (3 * if >, <, ==).

Now I would like to see the Über-cool and short way to do it :)

Regards



From guillermo.fernandez@epfl.ch  Tue Jul 30 01:57:27 2002
From: guillermo.fernandez@epfl.ch (Guillermo Fernandez)
Date: Tue, 30 Jul 2002 10:27:27 +0930
Subject: [Tutor] Copying list contents
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A6@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3D45E477.6737C8F9@epfl.ch>

> > Python treates the lists like objects
> All python variables are references, regardless of the
> object to which they point.
Those this include variables of integer, strings and that kind of
objects?

> > but I'm working with lists of lists of lists...
> There is also a deepcopy module for copying nested lists.
Deep copy seems to work perfectly, thanks!

Guille


From kalle@lysator.liu.se  Tue Jul 30 04:07:33 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Tue, 30 Jul 2002 05:07:33 +0200
Subject: [Tutor] Copying list contents
In-Reply-To: <3D45E477.6737C8F9@epfl.ch>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7A6@mbtlipnt02.btlabs.bt.co.uk> <3D45E477.6737C8F9@epfl.ch>
Message-ID: <20020730030733.GA2081@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Guillermo Fernandez]
> > > Python treates the lists like objects

[Alan Gauld, I think]
> > All python variables are references, regardless of the
> > object to which they point.

[Guillermo again]
> Those this include variables of integer, strings and that kind of
> objects?

Yes.  The thing to notice here is that these objects are immutable,
they can't be changed.  What really happens when you say something
like this

  x = 0
  x += 1

is that the name 'x' is first bound to the integer object 0.  Then an
object (0+1), that is 1, is created and the name 'x' is bound to that
instead.  The initial 0 object is thrown away*, since there are no
more references to it.

 * This is not strictly true, since low (below 100, I think) integer
 objects are optimized, but that's the idea anyway.

List objects, on the other hand, are mutable.  Here += modifies the
original object, and no new object is created.

Fredrik Lundh wrote a page about this on
http://effbot.org/guides/python-objects.htm

Another thing that follows from this is that using + to concatenate
strings can be very inefficient, since the contents of the left hand
side string are copied to the new result string.

The hypothetical function body

  nonemptylines = ""
  for line in fileobj.readlines():
      if line.strip():
          nonemptylines += line
  return nonemptylines

should be written like

  nonemptylines = []
  for line in fileobj.readlines():
      if line.strip():
          nonemptylines.append(line)
  return "".join(nonemptylines)

as this will be considerably faster for large files.  In the first
version, a new -- progressively larger -- object is created each time
through the loop and nonemptylines is rebound to reference this.  The
second version avoids this and only creates one extra string object,
the return value of "".join().

Hmm.  Sorry for the digression, I got a bit carried away there. :)

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9RgLvdNeA1787sd0RAq5JAKC2+P8AZU2L9OxAhuf7b/3TTOlIXACeLtGm
uz9PNMqK6Lroj3Am4+TdqOw=
=uyMi
-----END PGP SIGNATURE-----


From slime@vsnl.net  Tue Jul 30 04:45:56 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Tue, 30 Jul 2002 09:15:56 +0530
Subject: [Tutor] Splitting long lines correctly
Message-ID: <20020730034556.GA1392@localhost.localdomain>

Hi,

    I am trying to write a script to paginate text files, and make them
"pretty" enough to print - something like "pr", only in Python.

    Now, the main problem I am facing is splitting long (> 80 chars)
lines into smaller lines, while still preserving the readability.

ie. I do not want lines with a comma at the first column - instead I
would like to bring down the previous word onto the next line.

    Also, I would like to be able to recognise and preserve paragraph
breaks, etc.

    How do I go about achieving this ? Are there programs that already
do this (in Python) ?

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

Do not use that foreign word "ideals".  We have that excellent native
word "lies".
		-- Henrik Ibsen, "The Wild Duck"


From slime@vsnl.net  Tue Jul 30 04:38:02 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Tue, 30 Jul 2002 09:08:02 +0530
Subject: [Tutor] Re:  Full screen in text mode?
In-Reply-To: <3D452D42.1E4A664C@patriot.net>
References: <3D452D42.1E4A664C@patriot.net>
Message-ID: <20020730033802.GB1104@localhost.localdomain>

Hi,

On Mon, 29 Jul 2002 Charles M Howe spewed into the ether:
> Tuts, (hope this is ok as a salutation)
> 
> I am undertaking a task that will (very likely) require a GUI if I like
> it enough to release it to the world. However, if I could control the
> entire screen in text mode -- colorize printing, maybe have some large
> fonts, move about a fixed screen, create a few icons -- I would stay in
> text mode until (and if) I basically solve the problem. So my question
> is, Is this possible?

    You can do a lot of funky stuff on the console with curses or
ncurses. Under python, you could use the curses library.

    To get started, you might want to take a look at :

        http://www.python.org/doc/howto/curses/curses.html

    A quick google also threw up this :

        http://pyncurses.sourceforge.net

HTH,
    
pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

The most difficult thing in the world is to know how to do a thing and to
watch someone else doing it wrong, without commenting.
		-- T.H. White


From slime@vsnl.net  Tue Jul 30 04:30:12 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Tue, 30 Jul 2002 09:00:12 +0530
Subject: [Tutor] Re:  Printing a formatted list (of lists)
In-Reply-To: <p0510030eb96ab314d7f5@[209.221.136.35]>
References: <p0510030eb96ab314d7f5@[209.221.136.35]>
Message-ID: <20020730033011.GA1104@localhost.localdomain>

Hi,

On Mon, 29 Jul 2002 Allyn Weaks spewed into the ether:
> Python 2.n on unix.
> 
> I have a table that's a list of lists (values can be mixed
> numbers/text).  Is there a clean way to print a formatted list?  What I
> have works, but it seems that there ought to be a more list-oriented
> way of formatting the list part.  Or is this one of those places where
> one accepts the explicit loop?  I've tried out list comprehension
> variations 'til I'm dizzy with nothing but assorted errors.
> 
> for j in range(len(table)):
>     print `table[j]`.rjust(columnwidth),

How about this :

"""
def print_list (list_of_lists) :
    column_width = 8
    separator = ","
    line_break = "\n"
    out_str = ""
    ## Explicit loop
    ## This makes it clearer than when list comprehension
    ## is used, IMHO.
    for inner_list in list_of_lists :
        for l in inner_list :
            ## The str() function will convert all values
            ## be it numbers/text, into the corresponding
            ## string form.
            out_str += str(l).rjust(column_width) + separator
        ## Adds the line break
        out_str += line_break
    return out_str

if __name__ == "__main__":
    l = [ [1,2,3,complex(1,1)], [5,6,7,8.12], [10,11,12,"string"] ]
    print print_list(l)
"""

HTH,

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

The beauty of a pun is in the "Oy!" of the beholder.


From dylan.belsey@baesystems.com  Tue Jul 30 05:22:02 2002
From: dylan.belsey@baesystems.com (BELSEY, Dylan)
Date: Tue, 30 Jul 2002 13:52:02 +0930
Subject: [Tutor] FW: Embedding Python
Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B96320D1@wtntex1.baea.com.au>

Hi Tutor list,
	I posted the below mail last week and haven't seen any replies on
the topic so I am not sure if it got through or if the questions were out of
the scope of this list.  If it is out of scope, any suggestions to what list
would be more appropriate.
	Further to the information provided, I compiled the code in
"Release" mode and still obtained the same error.  When I refer to error I
mean the 'import site' failure message.  I would appreciate any help on
this.
	Thanks,
		Dylan


> -----Original Message-----
> From:	BELSEY, Dylan 
> Sent:	Wednesday, 24 July 2002 15:51
> To:	tutor@python.org
> Subject:	Embedding Python
> 
> Hi,
> 	I am attempting to try and get the embedding of Python running on my
> system (WinNT). I am using VC++ and I copied the code from "5.1 Very High
> Level Embedding" within "Extending and Embedding the Python Interpreter"
> from the Python docs.  I have also installed the latest release of Python,
> version 2.3a0.  The code from the documentation is pasted below:
> 
> #include <Python.h>
> 
> int
> main(int argc, char *argv[])
> {
>   Py_Initialize();
>   PyRun_SimpleString("from time import time,ctime\n"
>                      "print 'Today is',ctime(time())\n");
>   Py_Finalize();
>   return 0;
> }
> 
> 	It compiles OK but when I go to run it I get the following error:
> 
> 'import site' failed; use -v for traceback
> Today is Wed Jul 24 15:39:04 2002
> Press any key to continue
> 
> 	Any ideas why this error is occurring.  Has anyone seen this error
> and if so why is it occurring?  The code is compiled in debug mode so
> maybe the error is an artefact of that??  I have noticed that when I put
> the produced executable in the directory where python.exe lives I don't
> get the error.  Unfortunately I don't know enough about the guts of Python
> to follow this discovery through.
> 	Any help would be appreciated.
> 		Dylan


From slime@vsnl.net  Tue Jul 30 05:15:27 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Tue, 30 Jul 2002 09:45:27 +0530
Subject: [Tutor] Re:  Comparing Time.
In-Reply-To: <002701c23764$d7ab4be0$0a01a8c0@allah>
References: <002701c23764$d7ab4be0$0a01a8c0@allah>
Message-ID: <20020730041527.GA2025@localhost.localdomain>

Hi,

On Tue, 30 Jul 2002 Troels Leth Petersen spewed into the ether:
> Hi,
> 
> I am reading 'How to Think Like A Computer Scientist' - and have done
> the following exercise:
> 
> "As a second exercise, write a boolean function after that takes two
> Time objects, t1 and t2, as arguments, and returns true (1) if t1
> follows t2 chronologically and false (0) otherwise. "
> 
> And the Time object is a very simple object with 3 attributes: hours,
> minutes, seconds. As said I did the above exercise but in a
> non-elegant way using 9 if statements (3 * if >, <, ==).
> 
> Now I would like to see the Über-cool and short way to do it :)

    Why not do this :

"""
def compare (t1, t2) :
    t1_time = ((t1.hours*3600) + (t1.minutes*60) + t1.seconds)
    t2_time = ((t2.hours*3600) + (t2.minutes*60) + t2.seconds)
    return t1_time < t2_time
"""

HTH,

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

As in certain cults it is possible to kill a process if you know its true name.
		-- Ken Thompson and Dennis M. Ritchie


From tjenkins@devis.com  Tue Jul 30 06:15:12 2002
From: tjenkins@devis.com (Tom Jenkins)
Date: Tue, 30 Jul 2002 01:15:12 -0400
Subject: [Tutor] Comparing Time.
References: <002701c23764$d7ab4be0$0a01a8c0@allah>
Message-ID: <3D4620E0.90506@devis.com>

Troels Leth Petersen wrote:
> Hi,
> 
> I am reading 'How to Think Like A Computer Scientist' - and have done
> the following exercise:
> 
> "As a second exercise, write a boolean function after that takes two
> Time objects, t1 and t2, as arguments, and returns true (1) if t1
> follows t2 chronologically and false (0) otherwise. "
> 
> And the Time object is a very simple object with 3 attributes: hours,
> minutes, seconds. As said I did the above exercise but in a
> non-elegant way using 9 if statements (3 * if >, <, ==).

how about this: we really want to only do one comparison; hours and 
minutes can be converted to seconds.

def compareTimes(t1, t2):
     # formula is
     #   seconds = (hours * 60 min/hr * 60 sec/min) +
     #             (minutes * 60 sec/min) +
     #             seconds
     t1_seconds = (t1.hours * 3600) + (t1.minutes * 60) + t1.seconds
     t2_seconds = (t2.hours * 3600) + (t2.minutes * 60) + t2.seconds
     if t1_seconds > t2_seconds:
         return 1
     return 0

> 
> Now I would like to see the Über-cool and short way to do it :)
> 

well-i-don't-think-its-Über-cool-but-it-works'ly yours
Tom




From dyoo@hkn.eecs.berkeley.edu  Tue Jul 30 06:22:56 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 29 Jul 2002 22:22:56 -0700 (PDT)
Subject: [Tutor] FW: Embedding Python
In-Reply-To: <86C3892A0C52D411AF5000A0C9EAA3B96320D1@wtntex1.baea.com.au>
Message-ID: <Pine.LNX.4.44.0207292149280.18392-100000@hkn.eecs.berkeley.edu>


On Tue, 30 Jul 2002, BELSEY, Dylan wrote:

> 	I posted the below mail last week and haven't seen any replies on
> the topic so I am not sure if it got through or if the questions were
> out of the scope of this list.  If it is out of scope, any suggestions
> to what list would be more appropriate.

Hi Dylan,

Yikes, I missed your original post!


There's a similar experience that some random guy named Guido stumbled
through while compiling the Demo/embed/ example that's included in the
source distribution:

    http://mail.python.org/pipermail/python-dev/2000-July/005974.html

so I wouldn't worry about not getting this right the first time.




> > 	I am attempting to try and get the embedding of Python running on
> > my system (WinNT). I am using VC++ and I copied the code from "5.1
> > Very High Level Embedding" within "Extending and Embedding the Python
> > Interpreter" from the Python docs.  I have also installed the latest
> > release of Python, version 2.3a0.  The code from the documentation is
> > pasted below:

2.3a0 is still in alpha, so there may be other reasons why the example
isn't working for you yet; 2.3a0 may still yet have a buggy build
procedure.  2.2.1 is the latest stable release, so you may want to try
that instead.



> > #include <Python.h>
> >
> > int
> > main(int argc, char *argv[])
> > {
> >   Py_Initialize();
> >   PyRun_SimpleString("from time import time,ctime\n"
> >                      "print 'Today is',ctime(time())\n");
> >   Py_Finalize();
> >   return 0;
> > }
> >
> > 	It compiles OK but when I go to run it I get the following error:
> >
> > 'import site' failed; use -v for traceback


Hmmm... The embedding example shouldn't need to look for the site-wide
'site.py' module.  Can you try it with '-v' to see what's going on?


My best guess so far is that, during the Py_Initialize() step, that some
symbols weren't compiled into your binary.  For example, on Linux, the
following flags need to be used during compilation:

    '-Xlinker -export-dynamic'

or else the 'import site' error occurs.  Perhaps something similar needs
to be done in Visual C++?  There's a section on Linking Requirements:

    http://www.python.org/doc/current/ext/link-reqs.html

that might be relevant, although it only mentions Unix. The following
article might be helpful:

    http://www.faqts.com/knowledge_base/view.phtml/aid/5325/fid/245


Unfortunately, I don't have Visual C++, so I can't experiment with this at
all.  This may not be the best forum for getting a good answer to your
embedding question; you may want to try comp.lang.python or the
python-win32 list.  Here's are links to both forums:


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


Best of wishes to you!



From dylan.belsey@baesystems.com  Tue Jul 30 06:35:00 2002
From: dylan.belsey@baesystems.com (BELSEY, Dylan)
Date: Tue, 30 Jul 2002 15:05:00 +0930
Subject: [Tutor] FW: Embedding Python
Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B96320D2@wtntex1.baea.com.au>

	Lots of things to try here and good links as well.  Thanks Danny.


-----Original Message-----
From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu]
Sent: Tuesday, 30 July 2002 15:23
To: BELSEY, Dylan
Cc: 'tutor@python.org'
Subject: Re: [Tutor] FW: Embedding Python




On Tue, 30 Jul 2002, BELSEY, Dylan wrote:

> 	I posted the below mail last week and haven't seen any replies on
> the topic so I am not sure if it got through or if the questions were
> out of the scope of this list.  If it is out of scope, any suggestions
> to what list would be more appropriate.

Hi Dylan,

Yikes, I missed your original post!


There's a similar experience that some random guy named Guido stumbled
through while compiling the Demo/embed/ example that's included in the
source distribution:

    http://mail.python.org/pipermail/python-dev/2000-July/005974.html

so I wouldn't worry about not getting this right the first time.




> > 	I am attempting to try and get the embedding of Python running on
> > my system (WinNT). I am using VC++ and I copied the code from "5.1
> > Very High Level Embedding" within "Extending and Embedding the Python
> > Interpreter" from the Python docs.  I have also installed the latest
> > release of Python, version 2.3a0.  The code from the documentation is
> > pasted below:

2.3a0 is still in alpha, so there may be other reasons why the example
isn't working for you yet; 2.3a0 may still yet have a buggy build
procedure.  2.2.1 is the latest stable release, so you may want to try
that instead.



> > #include <Python.h>
> >
> > int
> > main(int argc, char *argv[])
> > {
> >   Py_Initialize();
> >   PyRun_SimpleString("from time import time,ctime\n"
> >                      "print 'Today is',ctime(time())\n");
> >   Py_Finalize();
> >   return 0;
> > }
> >
> > 	It compiles OK but when I go to run it I get the following error:
> >
> > 'import site' failed; use -v for traceback


Hmmm... The embedding example shouldn't need to look for the site-wide
'site.py' module.  Can you try it with '-v' to see what's going on?


My best guess so far is that, during the Py_Initialize() step, that some
symbols weren't compiled into your binary.  For example, on Linux, the
following flags need to be used during compilation:

    '-Xlinker -export-dynamic'

or else the 'import site' error occurs.  Perhaps something similar needs
to be done in Visual C++?  There's a section on Linking Requirements:

    http://www.python.org/doc/current/ext/link-reqs.html

that might be relevant, although it only mentions Unix. The following
article might be helpful:

    http://www.faqts.com/knowledge_base/view.phtml/aid/5325/fid/245


Unfortunately, I don't have Visual C++, so I can't experiment with this at
all.  This may not be the best forum for getting a good answer to your
embedding question; you may want to try comp.lang.python or the
python-win32 list.  Here's are links to both forums:


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


Best of wishes to you!


From shalehperry@attbi.com  Tue Jul 30 07:01:54 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 29 Jul 2002 23:01:54 -0700 (PDT)
Subject: [Tutor] Splitting long lines correctly
In-Reply-To: <20020730034556.GA1392@localhost.localdomain>
Message-ID: <XFMail.20020729230154.shalehperry@attbi.com>

> 
>     How do I go about achieving this ? Are there programs that already
> do this (in Python) ?
> 

there are several algorithms for this.  I believe Knuth even documented one.


From scot@possum.in-berlin.de  Tue Jul 30 09:40:23 2002
From: scot@possum.in-berlin.de (Scot W. Stevenson)
Date: Tue, 30 Jul 2002 10:40:23 +0200
Subject: [Tutor] Python information
In-Reply-To: <MPEOIFCOPCIHEDCLBLPBKEFECBAA.rob@uselesspython.com>
References: <MPEOIFCOPCIHEDCLBLPBKEFECBAA.rob@uselesspython.com>
Message-ID: <200207301040.23452.scot@possum.in-berlin.de>

Hello Rob,=20

> I'll pose this question to the list (especially the newbies): What woul=
d
> you like to see demonstrated in a tutorial for absolute programming
> newbies? Be as specific or as general as you like.

I was wondering if there would be any chance of creating "spot" tutorials=
=20
for added features in new releases, given that the rate of change means=20
that the paper people have little chance to catch up. These spot tutorial=
s=20
[do pythons have spots?] could be organsized as "chapters" and should be=20
less of a chore to write than a whole book.

For example, the 2.2 version begs a tutorial on generators, which explain=
s=20
the concept in prose, goes thru an example in pseudocode, and then shows=20
how it can be used to win friends and influence people. Everybody keeps=20
talking about how cool list comprehension is (and I live in deathly fear=20
that one day I will join them); since they seem to be set to become a=20
central tool, a short tutorial on how they work, what they can replace,=20
where they make sense, etc. would be great.

These short, specific tutorials would assume that you have a basic grasp=20
of "Core Python" but still think that "icon" is something that lives in a=
=20
Russian Orthodox church or on your desktop, a computer language. Ideally,=
=20
the would appear at the same time as the "What is new in Python *"-series=
=20
and be cross-referenced with it.

I don't think that my Python skills are good enough to actually write the=
=20
things, but I would be happy to help as a non-computer-scientist crash=20
test dummy on the examples and explanations...

Y, Scot

--=20
  Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany



From allyn.@tardigrade.net  Tue Jul 30 10:19:15 2002
From: allyn.@tardigrade.net (Allyn Weaks)
Date: Tue, 30 Jul 2002 02:19:15 -0700
Subject: [Tutor] Printing a formatted list (of lists)
In-Reply-To: <3D457B4D.48014364@ccvcorp.com>
References: <p0510030eb96ab314d7f5@[209.221.136.35]>
 <3D457B4D.48014364@ccvcorp.com>
Message-ID: <p05100304b96c0332b62c@[209.221.136.46]>

On 29/7/02, Jeff Shannon wrote:

>> for j in range(len(table)):
>>     print `table[j]`.rjust(columnwidth),
>
>Well, the above snippet can be simplified as
>
>for cell in table:
>    print cell.rjust(columnwidth),

That is prettier.  Though I didn't quite tell everything--in several
places I have basically the same thing, but inside of another loop,
with things to print on the line before and after the list.

for i in range(len(name)):
    print  `name[i]`.ljust(titlewidth),
    for j in range(len(values[i])):
        print `values[i][j]`.rjust(columnwidth),
    print `total[i]`.rjust(columnwidth)

>If you know the number (and width) of columns in your table, then you can do
>something like this:
>
>for line in table:
>    print "%15s %15s %15s %15s" % tuple(line)

Tuples!  I knew there must be a use for tuples! :-)  I kept trying to
do something similar with lists, and it didn't like that.

>If you *don't* know the number of columns
...
>If you don't know what your maximum column width should be

I expect that this sort of thing comes up often enough that it's worth
writing up something general that can figure out how many of this and
that, and all the widths and such itself.  Think once, day dream ad
lib...

>Hope this at least gives you some ideas...

Yes indeed.  Especially the tuple keys to the kingdom!  Many thanks.
-- 
Allyn Weaks    allyn@tardigrade.net   Seattle, WA  Sunset zone 5
Pacific NW Native Wildlife Gardening: http://www.tardigrade.org/natives/
"The benefit of even limited monopolies is too doubtful, to be opposed
to that of their general suppression."  Thomas Jefferson


From fgranger@altern.org  Tue Jul 30 10:12:28 2002
From: fgranger@altern.org (Francois Granger)
Date: Tue, 30 Jul 2002 11:12:28 +0200
Subject: [Tutor] Splitting long lines correctly
In-Reply-To: <20020730034556.GA1392@localhost.localdomain>
Message-ID: <B96C251C.5336F%fgranger@altern.org>

on 30/07/02 5:45, Prahlad Vaidyanathan at slime@vsnl.net wrote:

>   Now, the main problem I am facing is splitting long (> 80 chars)
> lines into smaller lines, while still preserving the readability.
>=20
> ie. I do not want lines with a comma at the first column - instead I
> would like to bring down the previous word onto the next line.

I don't know how sophisticated you want it to be. I have been studying hte
full rules for splitting words in french long time ago ;-)

Going through Google with "split line word boundary" gave me in the first
page this ref wich give a really simple answer in Perl, easy to implement i=
n
Python, I guess:

http://www.perlmonks.com/index.pl?node_id=3D8730

$rest =3D $messagebody;
@text=3D();=20
while($rest ne '') {
    $rest =3D~ /(.{1,140}\W)/ms;
    push @text, $1;
    $rest =3D $';=20
}=20



--=20
Fran=E7ois Granger
fgranger@altern.org



From alan.gauld@bt.com  Tue Jul 30 10:59:11 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 30 Jul 2002 10:59:11 +0100
Subject: [Tutor] Copying list contents
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7B3@mbtlipnt02.btlabs.bt.co.uk>

> > > Python treates the lists like objects
> > All python variables are references, regardless of the
> > object to which they point.

> Those this include variables of integer, strings and that kind of
> objects?

Yes, except those are immutable so you can't change them.
(The number 1 is always the number 1, you can assign a new number 
but you can't change the literal value... But the variable is still pointing

to a number object nonetheless)

Like so:

>>> a = 42     # create a number object with immutable value 42
>>> b = a      #  points to the same number object
>>> a = 27    #  can't change '42' so create a new number object value 27
>>> print a,b    # a is 27, b is 42
>>> a = [1,2,3]  # same a but now pointing at a list object
>>> b = a      # same b but now pointing at a's list (27 & 42 now get
garbage collected)
>>> a[0] = 42  # create a new number, value 42 and make the 1st element of
list point at it
>>> b        # b still points at a's list which now holds a new 1st element
[42, 2 ,3 ]
>>> b = a[:]   # b now has a copy of a's list
>>> a[0] = 27  # new number value 27(garbage collect 42), point at 27 from
list
>>> b      # b now unchanged
[42, 2 ,3 ]
>>> a     # but a is changed
[27, 2, 3]

Hopefully that helps,

Its actually slightly more complicated because for performance reasons
Python 
actually caches some low integer values, but the principle holds.
Everything is a reference, including the members of the list!

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld@bt.com  Tue Jul 30 12:23:37 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 30 Jul 2002 12:23:37 +0100
Subject: [Tutor] Comparing Time.
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7B7@mbtlipnt02.btlabs.bt.co.uk>

> "As a second exercise, write a boolean function after that takes two
> Time objects, t1 and t2, as arguments, and returns true (1) if t1
> follows t2 chronologically and false (0) otherwise. "
> 
> And the Time object is a very simple object with 3 attributes: hours,
> minutes, seconds. As said I did the above exercise but in a
> non-elegant way using 9 if statements (3 * if >, <, ==).

def isAfter(t1,t2):
    " return true if t1 is later than t2 "
    t1secs = t1.hours * 3600 + t1.minutes * 60 + t1.seconds
    t2secs = t2.hours * 3600 + t2.minutes * 60 + t2.seconds
    return t1secs < t2secs

Should do it. If you wanbt to be absolutely sure that 
its 1,0 rather than any other non zero value then use 
an if/else with explicit returns.

Alan g.


From rob@uselesspython.com  Tue Jul 30 13:48:35 2002
From: rob@uselesspython.com (Rob)
Date: Tue, 30 Jul 2002 07:48:35 -0500
Subject: [Tutor] Python information
In-Reply-To: <200207301040.23452.scot@possum.in-berlin.de>
Message-ID: <MPEOIFCOPCIHEDCLBLPBAEHHCBAA.rob@uselesspython.com>

> > I'll pose this question to the list (especially the newbies): What would
> > you like to see demonstrated in a tutorial for absolute programming
> > newbies? Be as specific or as general as you like.
>
> I was wondering if there would be any chance of creating "spot" tutorials
> for added features in new releases, given that the rate of change means
> that the paper people have little chance to catch up. These spot
> tutorials
> [do pythons have spots?] could be organsized as "chapters" and should be
> less of a chore to write than a whole book.
>

I agree that this would be nifty, although I'm not "cutting edge" enough to
actually use most new features as they come up. I tend to learn new Python
(or any other programming language) tricks in one of three ways most of the
time:

1. By "happy accident" or magic. I will be piddling around doing something
odd, like sifting through the documentation and just seeing what all I can
figure out about some module. I try things out and *BAM!*... knowledge
occurs. (As NASA scientists not-infrequently seem to point out: You are more
likely to find something when you look for it.)

2. I need/want to do something, so I look it up as best I can and likely
wind up asking people like the Tutor List, Jython Users list,
comp.lang.python, etc. and benefit from spiffy on-the-spot lectures. The
archives are AMAZINGLY rich with these gems.

3. I set out to write an answer, however weak, to someone else's question or
problem. It's really spectacular how much you can learn by just *trying* to
answer someone else's question, whether or not yours proves to be the one
that seems to do them the most good. A variant on this is trying to write a
short demo or tutorial on anything you can put words to. I have added a few
of these to Useless Python, and look forward to adding more after this class
I'm in finishes (after this week) and I have more time to get caught up on
updating the site.

So I'm not usually the first to get to the newer features of the language
unless they happen to be something I already need to do.

Rob
http://uselesspython.com




From ccampbell@ede.org  Tue Jul 30 15:02:43 2002
From: ccampbell@ede.org (Colin Campbell)
Date: Tue, 30 Jul 2002 08:02:43 -0600
Subject: [Tutor] Comparing Time.
In-Reply-To: <002701c23764$d7ab4be0$0a01a8c0@allah>
Message-ID: <5.1.0.14.0.20020730075717.00a8fa00@mail.ede.org>

--=====================_1512593==_.ALT
Content-Type: text/plain; charset="iso-8859-1"; format=flowed
Content-Transfer-Encoding: quoted-printable

At 07:02 PM 7/29/02, you wrote:
>Hi,
>
>I am reading 'How to Think Like A Computer Scientist' - and have done
>the following exercise:
>
>"As a second exercise, write a boolean function after that takes two
>Time objects, t1 and t2, as arguments, and returns true (1) if t1
>follows t2 chronologically and false (0) otherwise. "
>
>And the Time object is a very simple object with 3 attributes: hours,
>minutes, seconds. As said I did the above exercise but in a
>non-elegant way using 9 if statements (3 * if >, <, =3D=3D).
>
>Now I would like to see the =DCber-cool and short way to do it :)

It would be arrogant to claim ubercoolness, but how about this:

import time
def bigtime(t1, t2)
         return t1 > t2

### sample values
t1 =3D time.gmtime
t2 =3D time.localtime

test =3D bigtime(t1, t2)
# or for slight extra coolness
print bigtime(t2, t1)

Python generally has a greater degree of coolness than most other languages!

HTH,

Colin


I stay cool and dig all jive, That's the way I stay alive.
My motto, as I live and learn, is "Dig and be dug in return."
    - Langston Hughes
--=====================_1512593==_.ALT
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<html>
<font size=3D3>At 07:02 PM 7/29/02, you wrote:<br>
<blockquote type=3Dcite class=3Dcite cite>Hi,<br><br>
I am reading 'How to Think Like A Computer Scientist' - and have
done<br>
the following exercise:<br><br>
&quot;As a second exercise, write a boolean function after that takes
two<br>
Time objects, t1 and t2, as arguments, and returns true (1) if t1<br>
follows t2 chronologically and false (0) otherwise. &quot;<br><br>
And the Time object is a very simple object with 3 attributes:
hours,<br>
minutes, seconds. As said I did the above exercise but in a<br>
non-elegant way using 9 if statements (3 * if &gt;, &lt;, =3D=3D).<br><br>
Now I would like to see the =DCber-cool and short way to do it :)<br>
</font></blockquote><br>
It would be arrogant to claim ubercoolness, but how about this:<br><br>
import time<br>
<font size=3D3>def bigtime(t1, t2)<br>
<x-tab>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</x-tab>return t1
&gt; t2<br><br>
### sample values<br>
t1 =3D time.gmtime<br>
t2 =3D time.localtime<br><br>
test =3D bigtime(t1, t2)<br>
# or for slight extra coolness<br>
print bigtime(t2, t1)<br><br>
Python generally has a greater degree of coolness than most other
languages!<br><br>
HTH,<br><br>
Colin<br><br>
<x-sigsep><p></x-sigsep>
I stay cool and dig all jive, That's the way I stay alive. <br>
My motto, as I live and learn, is &quot;Dig and be dug in
return.&quot;<br>
&nbsp;&nbsp; - Langston Hughes</font></html>

--=====================_1512593==_.ALT--



From gwatt3@backbonesecurity.com  Tue Jul 30 15:47:09 2002
From: gwatt3@backbonesecurity.com (Watt III, Glenn)
Date: Tue, 30 Jul 2002 10:47:09 -0400
Subject: [Tutor] linux/win problem
Message-ID: <94FD5825A793194CBF039E6673E9AFE034D60D@bbserver1.backbonesecurity.com>

my server uses linux however my system uses win 98 and the editors dont
communicate well the idle win ver. imbeds  line break tags that the
linux editor doesnt like i can edit using a program called PuTTY which
alows me access to the text editors PICO and VI however i cant debug
that way i can get along right now but the whole programing process
takes way to long this way if there are any patches any knows of or any
advice it would be greatly apprectiated


From anthony.barker@bmo.com  Tue Jul 30 15:54:14 2002
From: anthony.barker@bmo.com (anthony.barker@bmo.com)
Date: Tue, 30 Jul 2002 10:54:14 -0400
Subject: [Tutor] Dynamic/Weak Types and large projects
Message-ID: <OFDC0DA917.5AFFD625-ON85256C06.00515A6B-85256C06.0052B4EF@notes.bmo.com>

This is a multipart message in MIME format.
--=_alternative 0052B4E485256C06_=
Content-Type: text/plain; charset="us-ascii"

1) Dynamic vs Weak Types

I have heard python referred to as having "weak" types - how does this 
differ from "dynamic types" ?

2) General consensus is that for large projects strongly typed languages 
are better.
Is there any statistical proof of this beside hearsay?

Thanks

Anthony







--=_alternative 0052B4E485256C06_=
Content-Type: text/html; charset="us-ascii"


<br><font size=2 face="sans-serif">1) Dynamic vs Weak Types</font>
<br>
<br><font size=2 face="sans-serif">I have heard python referred to as having &quot;weak&quot; types - how does this differ from &quot;dynamic types&quot; ?</font>
<br>
<br><font size=2 face="sans-serif">2) General consensus is that for large projects strongly typed languages are better.</font>
<br><font size=2 face="sans-serif">Is there any statistical proof of this beside hearsay?</font>
<br>
<br><font size=2 face="sans-serif">Thanks</font>
<br>
<br><font size=2 face="sans-serif">Anthony</font>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
--=_alternative 0052B4E485256C06_=--


From shalehperry@attbi.com  Tue Jul 30 16:09:57 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 30 Jul 2002 08:09:57 -0700 (PDT)
Subject: [Tutor] Dynamic/Weak Types and large projects
In-Reply-To: <OFDC0DA917.5AFFD625-ON85256C06.00515A6B-85256C06.0052B4EF@notes.bmo.com>
Message-ID: <XFMail.20020730080957.shalehperry@attbi.com>

On 30-Jul-2002 anthony.barker@bmo.com wrote:
> 1) Dynamic vs Weak Types
> 
> I have heard python referred to as having "weak" types - how does this 
> differ from "dynamic types" ?
> 

input = '42'   # I am a string
i = int(input) # I am now an integer
i = '83'       # oops I am a string again

Python has types.  string, integer, float, list, tuple, dictionary.

d = {}
l = []

if you do:

d = l # I am allowed but the dictionary is forgotten

hence "weak" types.  In say C++ that never would have compiled because the
pointers would have been of different types.

> 2) General consensus is that for large projects strongly typed languages 
> are better.
> Is there any statistical proof of this beside hearsay?
> 

I am uncertain if this is still true.  I do not know of any clear documentation
of this.

However my above examples is definately something that a strong type person
would use to point out a failing in python.  He would say look how easy it is
to assign the "wrong" values to a variable.  The key difference is in python
almost all errors are noticed at runtime whereas strong type languages can
catch problems at compile/parse time.  So a problem is known much earlier.  In
a large project being able to reproduce a runtime error can be quite difficult.

In the end you weight the pros and cons.  Is stronger up front handling more
important to you than python's other features?  dynamic and weak allows for
some great flexibility and often really clean and ingenious solutions to
difficult problems.


From yduppen@xs4all.nl  Tue Jul 30 16:36:12 2002
From: yduppen@xs4all.nl (Yigal Duppen)
Date: Tue, 30 Jul 2002 17:36:12 +0200
Subject: [Tutor] Dynamic/Weak Types and large projects
In-Reply-To: <XFMail.20020730080957.shalehperry@attbi.com>
References: <XFMail.20020730080957.shalehperry@attbi.com>
Message-ID: <200207301736.13084.yduppen@xs4all.nl>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> However my above examples is definately something that a strong type person
> would use to point out a failing in python.  He would say look how easy it
> is to assign the "wrong" values to a variable.  The key difference is in
> python almost all errors are noticed at runtime whereas strong type
> languages can catch problems at compile/parse time.  So a problem is known
> much earlier.  In a large project being able to reproduce a runtime error
> can be quite difficult.

OTOH, the absence of compile-time error checking almost _forces_ you to write 
unittests. And in my experience, unittests usually reveal much more potential 
errors than a compiler.

This might even be an argument _against_ typed languages; I have the vague 
impression that whenever you have a good compiler at hand, you'll rely too 
much on it ("oh, it compiles, it must be correct").

But that's just my opinion of course.

YDD
- -- 
http://www.xs4all.nl/~yduppen
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE9RrJsLsKMuCf5EdwRAsBKAJ0VRQTMUi8w5lQyqhwhj7fNLG4eaACgkpGH
/0Bro+YAMEYyIScbPpNTQ9c=
=6foc
-----END PGP SIGNATURE-----



From tjenkins@devis.com  Tue Jul 30 16:55:58 2002
From: tjenkins@devis.com (Tom Jenkins)
Date: 30 Jul 2002 11:55:58 -0400
Subject: [Tutor] linux/win problem
In-Reply-To: <94FD5825A793194CBF039E6673E9AFE034D60D@bbserver1.backbonesecurity.com>
References: <94FD5825A793194CBF039E6673E9AFE034D60D@bbserver1.backbonesecurity.com>
Message-ID: <1028044559.639.15.camel@asimov>

On Tue, 2002-07-30 at 10:47, Watt III, Glenn wrote:
> my server uses linux however my system uses win 98 and the editors dont
> communicate well the idle win ver. imbeds  line break tags that the
> linux editor doesnt like i can edit using a program called PuTTY which
> alows me access to the text editors PICO and VI however i cant debug
> that way i can get along right now but the whole programing process
> takes way to long this way if there are any patches any knows of or any
> advice it would be greatly apprectiated
> 

there are a few options available to you:
1) run dos2unix over your python files on your linux server
2) open your python files on your linux server in vi and type
  :%s/<ctrl-v><ctrl-m>//g
don't type the <ctrl> part, actually hold the CTRL key down and hit 'v'
then 'm'; that will substitute any ^M (carriage returns) with nothing
3) install cvs on your linux server.  then you would check in any
changes to your python files into cvs (Concurrent Version System?) and
check them out on your linux box.  the cvs clients handle the CR & LF
issues across OS's.

-- 

Tom Jenkins
Development InfoStructure
http://www.devis.com




From ATrautman@perryjudds.com  Tue Jul 30 17:17:29 2002
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Tue, 30 Jul 2002 11:17:29 -0500
Subject: [Tutor] doze embedding info
Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A349@CORP_EXCHANGE>

All,

In response to the question about embedding python in Windows I found this
article in my mailbox yesterday and thought it might help answer the
question. It is from builder.com and is on of their columns converted to
plain text. I can't find a URL listed on their website for it so it is
below. If somebody wants the HTML for please email me.

Alan



Extending Python the Windows way 

My favorite feature of Python is how easy it is to extend. If you want to
write C Python extensions, there's a C++ library that makes creating Python
extensions nearly as easy as writing a C++ class. You can also write
extensions in Delphi. You can even use C functions directly from a DLL and
use COM components written in a variety of languages. In this article, I'll
focus on the last two methods. 
Note: I'm assuming that you have Python installed. If you don't, go to
ActiveState's Web site
<http://clickthru.online.com/Click?q=8b-SBGBQY0VljNDiSYEbODU_baFUL9R> and
download the 2.1.1, 2.1.3 or 2.2.1. release. These distributions come
complete with COM support. 
Using C DLLs 
First, you'll want to get CallDLL. You can download the source and compile
it, or if you have ActiveState's Python distribution installed, you can use
PPM to get it. Then do the same for DynWin. 
I've included a simple DLL in this downloadable Zip file
<ftp://ftp.download.com/pub/builder/techmails/SoftDev0725.zip> that contains
sample code. The DLL exports a function called ShowMsg that shows a pop-up
MessageBox. The function has the following signature: 
extern "C" {
__declspec( dllexport ) void MsgBox(const char *msg);
} 
Something to notice about the declaration is the extern "C". The function
names can't be mangled, so you either have to use straight C or declare the
functions extern "C". 
Here's the Python code to use this function: 
from dynwin.windll import *
mod = module('TestDLL')
buf = cstring("test")
mod.MsgBox(buf) 
The key to the Python code is the cstring line. This takes the Python string
and converts it into a pointer to a character buffer. The disadvantage in
extending Python in this manner is that you lose Python's excellent
error-handling capabilities such as exceptions. The advantage of using this
method to extend Python is that other programming languages such as Delphi
can use the extensions; also, it's somewhat cross-platform. 
Using ActiveX controls 
COM is well supported in Python. You can use ActiveX controls and can create
ActiveX controls in Python. 
For this example, we'll make use of Microsoft's XML control. First, open the
PythonWin development environment that ships with ActiveState's Python
distribution. Then from the tools menu, select the Makepy utility. This will
bring up a dialog that lists all of the registered ActiveX controls on the
system. Scroll down until you find the Microsoft XML control. Choose v3.0 if
it's available. What this does is set up all the constants and the Python
wrapper classes, which will make life much easier. (You can skip this step,
but I don't recommend it.) The following code demonstrates using MSXML in
Python: 
from win32com.client import Dispatch
import pythoncom

parser = Dispatch("Microsoft.XMLDOM")
parser.load('license.xml')
children = parser.getElementsByTagName('string')

for child in children:
print child.xml 
This code is very close to what you would do when using MSXML in Visual
Basic. One thing to note is that Python is a case-sensitive language where
Visual Basic is case-insensitive. This can cause some confusion if you don't
use the Makepy utility before using MSXML. 
When you use Makepy, it forces Python to use early binding, which also makes
all of the MSXML methods and properties case-sensitive. If you don't use
Makepy, then Python uses late binding and the MSXML methods and properties
are case-insensitive. 
Are you wondering why I'm advising using Makepy? When you combine a
case-sensitive language with a case-insensitive library, it's just asking
for trouble. It makes spotting errors in your code very difficult. 
If you're targeting Windows only, then extending Python using COM is an
excellent way to go. Unfortunately, it completely ties you to the Windows
platform. The nice thing about using COM is that you get very good language
interoperability. 
So what's my second favorite thing about Python? It runs on even more
platforms than Java! 


Mike Owens, who has been involved in the software industry for over eight
years, is a software engineer with Allscripts Healthcare Solution. 



From jeff@ccvcorp.com  Tue Jul 30 18:07:46 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue, 30 Jul 2002 10:07:46 -0700
Subject: [Tutor] Printing a formatted list (of lists)
References: <p0510030eb96ab314d7f5@[209.221.136.35]>
 <3D457B4D.48014364@ccvcorp.com> <p05100304b96c0332b62c@[209.221.136.46]>
Message-ID: <3D46C7E1.9A4C6FB0@ccvcorp.com>

Allyn Weaks wrote:

> On 29/7/02, Jeff Shannon wrote:
>
> >If you *don't* know the number of columns
> ...
> >If you don't know what your maximum column width should be
>
> I expect that this sort of thing comes up often enough that it's worth
> writing up something general that can figure out how many of this and
> that, and all the widths and such itself.  Think once, day dream ad
> lib...

Well, there was a recent thread here about the best way to find the maximum
length of a list's items -- my own solution was this:

maxlen = max( map(len, mylist) )

If you're doing this over a list of lists, you'd need to find the max length of
each nested list, and then use the largest of those:

maxlen = max( [ max( map(len, innerlist) for innerlist in outerlist ] )

Just in case that's a bit too much happening at once to be easy to follow ;)
it's equivalent to the following:

def FindMaxLength(outerlist):
    # create a list of all the maximum lengths
    # start with an empty list
    lengths = []
    # now, for each of the nested lists...
    for innerlist in outerlist:
        # calculate the max length and add it to lengths list
        lengths.append( max(map(len, mylist) ) )
    # then find the largest of them
    maxlen = max( lengths)
    return maxlen

(Personally, I'd prefer to use the one-liner, but I'd probably wrap it up in a
function anyhow.)

If you want to go whole-hog and do something *really* fancy, you could write a
routine that would find maximum lengths for each column independently (perhaps
returning a list of column lengths), then another routine that would convert that
list of column lengths into a suitable formatstring and use the previously
discussed string substitution methods to print out your table.  (I have some
thoughts on how to approach this, too, but won't work out details unless you
really want it. ;) )

Jeff Shannon
Technician/Programmer
Credit International




From KellyPhe@logica.com  Tue Jul 30 18:13:06 2002
From: KellyPhe@logica.com (Kelly, Phelim)
Date: Tue, 30 Jul 2002 18:13:06 +0100
Subject: [Tutor] if statement
Message-ID: <C9054F12A3EED311B0160090274D912108AF1126@shannon.ie.logica.com>

Hi,
	hoping you can help me.... I'm trying to create an if statement that
works if a certain string contains a specified 4 characters. Basically I
want to quit the program if an imported file is a .jpg file, so I'm looking
for an if statement kind of like:

if filename contains ".jpg":        (I'm looking for correct syntax for this
bit)
   sys.exit()




can this be done?? hope so!!

thanks

Phelim. 
   

This e-mail and any attachment is for authorised use by the intended recipient(s) only.  It may contain proprietary material, confidential information and/or be subject to legal privilege.  It should not be copied, disclosed to, retained or used by, any other party.  If you are not an intended recipient then please promptly delete this e-mail and any attachment and all copies and inform the sender.  Thank you.


From dyoo@hkn.eecs.berkeley.edu  Tue Jul 30 18:23:40 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Jul 2002 10:23:40 -0700 (PDT)
Subject: [Tutor] Splitting long lines correctly
In-Reply-To: <B96C251C.5336F%fgranger@altern.org>
Message-ID: <Pine.LNX.4.44.0207301020540.629-100000@hkn.eecs.berkeley.edu>


On Tue, 30 Jul 2002, Francois Granger wrote:

> on 30/07/02 5:45, Prahlad Vaidyanathan at slime@vsnl.net wrote:
>
> >   Now, the main problem I am facing is splitting long (> 80 chars)
> > lines into smaller lines, while still preserving the readability.
> >
> > ie. I do not want lines with a comma at the first column - instead I
> > would like to bring down the previous word onto the next line.
>
> I don't know how sophisticated you want it to be. I have been studying hte
> full rules for splitting words in french long time ago ;-)

By the way, if you want to do english hyphenation, here's a module that
may help you:

    http://hkn.eecs.berkeley.edu/~dyoo/python/pyHnj/index.html

The wrapper is, admittedly, a bit old, and I haven't compiled new versions
for Python 2.2.1 yet.



From jeff@ccvcorp.com  Tue Jul 30 18:29:33 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue, 30 Jul 2002 10:29:33 -0700
Subject: [Tutor] Comparing Time.
References: <5.1.0.14.0.20020730075717.00a8fa00@mail.ede.org>
Message-ID: <3D46CCFD.AEBDAB05@ccvcorp.com>

Colin Campbell wrote:

> At 07:02 PM 7/29/02, you wrote:
>
>> "As a second exercise, write a boolean function after that takes
>> two
>> Time objects, t1 and t2, as arguments, and returns true (1) if t1
>> follows t2 chronologically and false (0) otherwise. "
>>
>> And the Time object is a very simple object with 3 attributes:
>> hours,
>> minutes, seconds.  [....]
>
> import time
> def bigtime(t1, t2)
> return t1 > t2
>
> ### sample values
> t1 = time.gmtime
> t2 = time.localtime

Well, the problem stated above indicates that the time values in use
are special class-objects with three attributes, *not*
seconds-since-epoch time values.  Besides which... you're not really
getting time values there.  You didn't add parentheses at the end of
your functions, there, so you never called them -- you just assigned
references.  Thus, t1() is now effectively an alias for time.gmtime().

Looking at the original problem, we have a class that looks like this:

class TimeObj:
    def __init__(self, hour, min, sec):
        self.hour = hour
        self.min = min
        self.sec = sec

Now, I will make one assumption about our time values, that they are
all normalized -- that is, that we will never have more than 60
minutes or more than 60 seconds.  With that presumption, we can then
take advantage of Python's rules for comparing sequences -- the first
element is compared first, and if that matches the second element is
compared, and if that matches the third is compared, etc...

def CompareTime(t1, t2):
    left = (t1.hour, t1.min, t1.sec)
    right = (t2.hour, t2.min, t1.sec)
    return left > right

Actually, as an interesting aside, when I tested this out in the
interpreter, I found that the TimeObj class I had above compared
correctly even *without* the CompareTime() function --

>>> t1 = TimeObj(5, 35, 15)
>>> t2 = TimeObj(12, 45, 5)
>>> t3 = TimeObj(17, 10, 45)
>>> t1 > t2
0
>>> t2 > t3
0
>>> t3 > t1
1

However, it is only happy coincidence that the default compare seems
to be comparing attributes in the correct order.  (I presume that it's
comparing each instance's __dict__, and that 'hours' just happens to
hash first...)  This is not something to rely on, thus the
CompareTime() function explicitly specifies which attributes are most
significant.

Jeff Shannon
Technician/Programmer
Credit International




From jtk@yahoo.com  Tue Jul 30 17:50:03 2002
From: jtk@yahoo.com (Jeff Kowalczyk)
Date: Tue, 30 Jul 2002 12:50:03 -0400
Subject: [Tutor] Deriving from base class, adding an attribute
Message-ID: <ai6g3b$2cl$1@main.gmane.org>

Pardon the ultra-newbie question, but I want to derive a number of
classes (in a single module) from the classes in another module.
To each of the classes, I need to add a single attribute (if in fact
attributes are what they're properly called):

The base product is Formulator, the module StandardFields.py
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/formulator/Formulator/

Products\Formulator\StandardFields.py (original)
-----------------------------------------------
class StringField(ZMIField):
    meta_type = "StringField"
    widget = Widget.TextWidgetInstance
    validator = Validator.StringValidatorInstance

class PasswordField(ZMIField):
    meta_type = "PasswordField"
    widget = Widget.PasswordWidgetInstance
    validator = Validator.StringValidatorInstance
(...)

What I need to add to my derived module (pseudocode):
Products\MyFormulator\StandardFields.py
-----------------------------------------------
from Layout import Layout
import Products.Formulator.StandardFields

class StringField(Formulator.StandardFields.StringField):
 layout = Layout.LayoutInstance

class PasswordField(Formulator.StandardFields.StringField):
    layout = Layout.LayoutInstance
(...)

Where Layout.py is a module in this derived Python product. How
is this intent supposed to be expressed?

I would like to do this the manual way first, so I learn about
module imports and python's inheritance syntax. But once I
understand that, I would imagine that Python's nifty introspection
features could make something like this possible:
"For all classes deriving from X in module Y, add attribute Z"






From shalehperry@attbi.com  Tue Jul 30 18:39:31 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 30 Jul 2002 10:39:31 -0700 (PDT)
Subject: [Tutor] if statement
In-Reply-To: <C9054F12A3EED311B0160090274D912108AF1126@shannon.ie.logica.com>
Message-ID: <XFMail.20020730103931.shalehperry@attbi.com>

On 30-Jul-2002 Kelly, Phelim wrote:
> Hi,
>       hoping you can help me.... I'm trying to create an if statement that
> works if a certain string contains a specified 4 characters. Basically I
> want to quit the program if an imported file is a .jpg file, so I'm looking
> for an if statement kind of like:
> 
> if filename contains ".jpg":        (I'm looking for correct syntax for this
> bit)
>    sys.exit()
> 
> 

import os.path
base, ext = os.path.splitext(filename)
if ext == '.jpg':
  handle jpg file

>    
> 
> This e-mail and any attachment is for authorised use by the intended
> recipient(s) only.  It may contain proprietary material, confidential
> information and/or be subject to legal privilege.  It should not be copied,
> disclosed to, retained or used by, any other party.  If you are not an
> intended recipient then please promptly delete this e-mail and any attachment
> and all copies and inform the sender.  Thank you.
> 

um, this message prevents any online site from storing you email for later
searching.  It is rather impolite.


From jeff@ccvcorp.com  Tue Jul 30 18:59:21 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue, 30 Jul 2002 10:59:21 -0700
Subject: [Tutor] Dynamic/Weak Types and large projects
References: <OFDC0DA917.5AFFD625-ON85256C06.00515A6B-85256C06.0052B4EF@notes.bmo.com>
Message-ID: <3D46D3F8.5B2738C8@ccvcorp.com>


anthony.barker@bmo.com wrote:

>
> 1) Dynamic vs Weak Types
>
> I have heard python referred to as having "weak" types - how does
> this differ from "dynamic types" ?

This is actually exactly the opposite of how most Pythonistas would
describe Python's type system -- Python has *strong* but dynamic
typing.  Dynamic typing means that any name can be bound to any type
of object.

# create an integer
MyVariable = 1
# then replace it with a string
MyVariable = "A String"

Python is perfectly happy with this, but C/C++ would throw fits.
(Well, compiler errors.)  The strong typing means that the operations
you can perform on an object depend upon the type of the object --
Python will (usually) not coerce things from one type to another
unless you specifically ask it to.

>>> x = 1
>>> y = "2"
>>> x + y
Traceback (most recent call last):
  File "<input>", line 1, in ?
TypeError: unsupported operand types for +: 'int' and 'str'
>>>

Here, you cannot add these two variables because they are of different
types.  In Perl, a language that truly is weakly typed, you *would* be
able to add these together and get a result of 3.

The real difference between a dynamically typed language (such as
Python) and a statically typed language (such as C/C++), is that in
static languages, the type is associated with a specific variable name
-- once you create a variable, that name will always be of the type it
was created with.  In dynamic languages, the type is associated with
an *object* -- but a given name can refer to *any* object, regardless
of its type.

The advantage of static typing is that a compiler can ensure that
every operation performed on an object is valid for that type of
object, and that compiler errors give the programmer the earliest
possible warning about problems.  You don't need to test the whole
program in order to find type mismatches.  Of course, this is also the
biggest drawback of static languages -- since you don't need to test
everything for type mismatches, most programmers *won't* test
everything -- and therefore may not uncover logic errors or algorithm
errors that are buried in untested code ("it compiled so it *must* be
right").

The big advantage of dynamic languages is that it encourages generic
programming.  You don't have to worry about what *type* an object is,
only what operations it supports.  This means that if you want to add
a new type, that supports the same operations in a slightly different
way, it is trivially easy -- the client code that uses the objects
probably won't change at all, whereas in a static language you'd at
*least* have to go through and change all of the variable declarations
(and hope that you don't miss any).

Static languages nowadays have quite a range of features that are
designed to enable generic programming styles -- pointer upcasting,
templates, etc.  A lot of work has gone into the C++ standard template
library... which, in effect, allows you to program C++ using the sorts
of idioms that are native to dynamic languages like Python.  But those
idioms are still easier to use in truly dynamic languages.


> 2) General consensus is that for large projects strongly typed
> languages are better.
> Is there any statistical proof of this beside hearsay?

No, there is no proof of this -- or at least, there's no proof that
*statically* typed languages are better (which is what most people
mean when they say "strongly typed" in this context).  In fact, most
of the experimental evidence these days supports the idea that dynamic
langauges are "better" in most senses of the word -- shorter code,
fewer errors, faster release times.  The one area in which static
typing is a demonstrable advantage is in situations where a program
must be provably correct, in the sense of writing a mathematic proof.
Mathematical analysis of a dynamic program is considerably more
difficult.  (However, common-sense interpretation is often easier.)

Jeff Shannon
Technician/Programmer
Credit International




From hall@nhn.ou.edu  Tue Jul 30 18:48:14 2002
From: hall@nhn.ou.edu (Isaac Hall)
Date: Tue, 30 Jul 2002 12:48:14 -0500
Subject: [Tutor] Python information
In-Reply-To: <MPEOIFCOPCIHEDCLBLPBAEHHCBAA.rob@uselesspython.com>; from rob@uselesspython.com on Tue, Jul 30, 2002 at 07:48:35 -0500
References: <200207301040.23452.scot@possum.in-berlin.de> <MPEOIFCOPCIHEDCLBLPBAEHHCBAA.rob@uselesspython.com>
Message-ID: <20020730124814.E28406@ouhep1.nhn.ou.edu>

Hi Rob,

while I guess Im really not a programming newbie, I was a python and 
OOP newbie
not all that long ago.  The things that I would have really appreciated 
at that
time which I found difficult to find were general OOP 'good 
behaviours'.  for example
maybe pointers on when one benifits from creating classes, when one 
benefits from
creating a function outside a class as opposed to a method inside a 
class.  along with
examples of how to do this, along with the rules of inheritance with 
detailed explanation.

I happpend to have to learn Python and OOP at the same time for a 
program nessecary to
my work (Im a Grad strudent in High Energy Physics, which means that I 
only write code
when it is nessecary, and until this program had to be written, I 
hadn't written code in
5 years).  While doing this I followed the basic aspects of Python 
rather well
from the Python Tutorial on the Python.org page, however when it came 
to writing classes
and methods for those classes, I was hopelessly lost.  To some extent I 
still am, as I
am probably not the most efficent user of pythons OOP ability, however 
I can write code
that does what I want it to, and thats pretty much the goal.  But I 
gather that the true
programming newbies that have never had to write a bit of code until 
today, or whatever day
it is when they go searching for python tutorials will also percieve a 
better explanation
of OOP in general, OOP as it applies in python, and what good OOP 
programing is all about.

anyway, I hope this helps, and I thank you for asking the newbies what 
they would like
to see in a tutorial.

Ike

On 2002.07.30 07:48 Rob wrote:
> > > I'll pose this question to the list (especially the newbies): What
> would
> > > you like to see demonstrated in a tutorial for absolute
> programming
> > > newbies? Be as specific or as general as you like.
> >
> > I was wondering if there would be any chance of creating "spot"
> tutorials
> > for added features in new releases, given that the rate of change
> means
> > that the paper people have little chance to catch up. These spot
> > tutorials
> > [do pythons have spots?] could be organsized as "chapters" and
> should be
> > less of a chore to write than a whole book.
> >
> 
> I agree that this would be nifty, although I'm not "cutting edge"
> enough to
> actually use most new features as they come up. I tend to learn new
> Python
> (or any other programming language) tricks in one of three ways most
> of the
> time:
> 
> 1. By "happy accident" or magic. I will be piddling around doing
> something
> odd, like sifting through the documentation and just seeing what all I
> can
> figure out about some module. I try things out and *BAM!*... knowledge
> occurs. (As NASA scientists not-infrequently seem to point out: You
> are more
> likely to find something when you look for it.)
> 
> 2. I need/want to do something, so I look it up as best I can and
> likely
> wind up asking people like the Tutor List, Jython Users list,
> comp.lang.python, etc. and benefit from spiffy on-the-spot lectures.
> The
> archives are AMAZINGLY rich with these gems.
> 
> 3. I set out to write an answer, however weak, to someone else's
> question or
> problem. It's really spectacular how much you can learn by just
> *trying* to
> answer someone else's question, whether or not yours proves to be the
> one
> that seems to do them the most good. A variant on this is trying to
> write a
> short demo or tutorial on anything you can put words to. I have added
> a few
> of these to Useless Python, and look forward to adding more after this
> class
> I'm in finishes (after this week) and I have more time to get caught
> up on
> updating the site.
> 
> So I'm not usually the first to get to the newer features of the
> language
> unless they happen to be something I already need to do.
> 
> Rob
> http://uselesspython.com
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From jeff@ccvcorp.com  Tue Jul 30 19:11:15 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue, 30 Jul 2002 11:11:15 -0700
Subject: [Tutor] if statement
References: <C9054F12A3EED311B0160090274D912108AF1126@shannon.ie.logica.com>
Message-ID: <3D46D6C3.3305C8FB@ccvcorp.com>


"Kelly, Phelim" wrote:

> Hi,
>         hoping you can help me.... I'm trying to create an if statement that
> works if a certain string contains a specified 4 characters. Basically I
> want to quit the program if an imported file is a .jpg file, so I'm looking
> for an if statement kind of like:
>
> if filename contains ".jpg":        (I'm looking for correct syntax for this
> bit)
>    sys.exit()

Well, there's a couple of ways to do this.  You can simply look at the last bit of the string, in a couple of different ways:

# using a string method
if filename.endswith(".jpg"):    ...

# using slice notation
if filename[-4:] == ".jpg":    ...

However, since you're specifically working with filenames, I'd recommend looking into the os.path module.

>>> import os
>>> filename = "c:\\MyProgram\\Lib\\image.jpg"
>>> os.path.splitext(filename)
('c:\\MyProgram\\Lib\\image', '.jpg')
>>> name, ext = os.path.splitext(filename)
>>> if ext == '.jpg':
...     print "yes!"
...
yes!
>>>

There is, however, one slight problem to watch for, however you do this.

>>> filename = "IMAGE.JPG"
>>> name, ext = os.path.splitext(filename)
>>> if ext == '.jpg':
...     print "yes!"
>>>

Note that our test failed, because the case was different.  The simple thing to do, here, is to use the string method lower(), to make everything lowercase:

>>> if ext.lower() == '.jpg':
...     print "yes!"
...
yes!
>>>

Hope that this helps...

Jeff Shannon
Technician/Programmer
Credit International




From einarth@decode.is  Tue Jul 30 18:22:13 2002
From: einarth@decode.is (Einar Th. Einarsson)
Date: Tue, 30 Jul 2002 17:22:13 +0000
Subject: [Tutor] if statement
In-Reply-To: <C9054F12A3EED311B0160090274D912108AF1126@shannon.ie.logica.com>
References: <C9054F12A3EED311B0160090274D912108AF1126@shannon.ie.logica.com>
Message-ID: <200207301722.14071.einarth@decode.is>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

something like:

import os.path

if( os.path.splitext(filename)[1] =3D=3D ".jpg):
    sys.exit(0)


- --=20
 "One of the symptoms of an approaching nervous breakdown is the
belief that one's work is terribly important."
                -- Bertrand Russell

Yours etc.
    Einar Th.

On Tuesday 30 July 2002 17:13, Kelly, Phelim wrote:
> Hi,
> 	hoping you can help me.... I'm trying to create an if statement that
> works if a certain string contains a specified 4 characters. Basically I
> want to quit the program if an imported file is a .jpg file, so I'm looki=
ng
> for an if statement kind of like:
>
> if filename contains ".jpg":        (I'm looking for correct syntax for
> this bit)
>    sys.exit()
>
>
>
>
> can this be done?? hope so!!
>
> thanks
>
> Phelim.
>
>
> This e-mail and any attachment is for authorised use by the intended
> recipient(s) only.  It may contain proprietary material, confidential
> information and/or be subject to legal privilege.  It should not be copie=
d,
> disclosed to, retained or used by, any other party.  If you are not an
> intended recipient then please promptly delete this e-mail and any
> attachment and all copies and inform the sender.  Thank you.
>
> =5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=
=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F=5F
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


-----BEGIN PGP SIGNATURE-----
Version: PGP 6.5.8

iQA/AwUBPUbLRW1/ORZtyd/tEQKO/ACgiKJWwjTxQR+ds8yAWJWJYEkAOrsAoIVh
SOvnvMaPVg2A0ah3lmcEdb4a
=3DiHBz
-----END PGP SIGNATURE-----



From Jkr2004@aol.com  Tue Jul 30 20:40:26 2002
From: Jkr2004@aol.com (Jkr2004@aol.com)
Date: Tue, 30 Jul 2002 15:40:26 EDT
Subject: [Tutor] (no subject)
Message-ID: <7a.2a96df70.2a7845aa@aol.com>

--part1_7a.2a96df70.2a7845aa_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

stop sending mail to me

--part1_7a.2a96df70.2a7845aa_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

<HTML><FONT FACE=arial,helvetica><FONT  COLOR="#000080" SIZE=2 FAMILY="DECORATIVE" FACE="Snap ITC" LANG="6"><I>stop sending mail to me</I></FONT></HTML>

--part1_7a.2a96df70.2a7845aa_boundary--


From gp@pooryorick.com  Tue Jul 30 21:53:48 2002
From: gp@pooryorick.com (Poor Yorick)
Date: Tue, 30 Jul 2002 14:53:48 -0600
Subject: [Tutor] listdir, ispath,  and unicode
Message-ID: <3D46FCDC.9080309@pooryorick.com>

I am running Windows 2000 and have files which use cyrillic characters 
in their names.  I am running into this problem when I try to work with 
them:
 
 
 >>> os.listdir('c:\\tmp2')[0]
'????????.url'
 >>> os.path.isfile(os.listdir('c:\\tmp2')[0])
0
 
 
Can anyone tell me why os.path.isfile does not recognize my file?



From dyoo@hkn.eecs.berkeley.edu  Tue Jul 30 22:30:37 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Jul 2002 14:30:37 -0700 (PDT)
Subject: [Tutor] listdir, ispath,  and unicode
In-Reply-To: <3D46FCDC.9080309@pooryorick.com>
Message-ID: <Pine.LNX.4.44.0207301425030.6898-100000@hkn.eecs.berkeley.edu>


On Tue, 30 Jul 2002, Poor Yorick wrote:

> I am running Windows 2000 and have files which use cyrillic characters
> in their names.  I am running into this problem when I try to work with
> them:
>
>
>  >>> os.listdir('c:\\tmp2')[0]
> '????????.url'
>  >>> os.path.isfile(os.listdir('c:\\tmp2')[0])
> 0
>
>
> Can anyone tell me why os.path.isfile does not recognize my file?

I'm not sure if this is related to cyrillic characters, but I think
os.path.isfile() needs to know the full path of the file; otherwise, it
would have to guess where to start looking.


That is, os.path.isfile()  can't know that when we say '???????.url', we
mean the '???????.url' in the tmp2 directory; what if there were other
'????????.url' files in other directories?


Here's a chunk of code that may work better for you:

###
os.path.isfile(os.path.join('c:\\tmp2',
                            os.listdir('c:\\tmp2')[0]))
###



From rob@uselesspython.com  Tue Jul 30 22:50:50 2002
From: rob@uselesspython.com (Rob)
Date: Tue, 30 Jul 2002 16:50:50 -0500
Subject: [Tutor] listdir, ispath,  and unicode
In-Reply-To: <3D46FCDC.9080309@pooryorick.com>
Message-ID: <MPEOIFCOPCIHEDCLBLPBCEILCBAA.rob@uselesspython.com>

I'm also running Win2K on this machine and tried to reproduce your problem.
Here I ran os.listdir on the folder on C:\insight. It displayed its contents
in some detail.

>>> os.listdir('c:\\insight')
['abbrev.html', 'begin.html', 'glossary.html', 'history.html',
'index-author.html', 'index-names.html', 'index-number.html',
'index-similes.html', 'index-subject.html', 'index-sutta.html',
'index-title.html', 'index.html', 'other.html', 'sutta101.html',
'theravada.html', 'tech', 'cdrom', 'pali', 'ptf', 'icon', 'lib', 'canon',
'faq.html', 'help.html', 'news.html', 'search.html', 'bfaq.html',
'Tibet-HTML']

Then I ran os.path.isfile on one of the files in that folder thusly:

>>> os.path.isfile('c:\\insight\\index-sutta.html')
1
>>>

All seems well here. It seems that in your code you are asking if the folder
C:\tmp2 is a file, and you are being correctly told that it is not a file.

Do I have all of your facts correct?

Rob
http://uselesspython.com

> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Poor Yorick
> Sent: Tuesday, July 30, 2002 3:54 PM
> To: tutor@python.org
> Subject: [Tutor] listdir, ispath, and unicode
>
>
> I am running Windows 2000 and have files which use cyrillic characters
> in their names.  I am running into this problem when I try to work with
> them:
>
>
>  >>> os.listdir('c:\\tmp2')[0]
> '????????.url'
>  >>> os.path.isfile(os.listdir('c:\\tmp2')[0])
> 0
>
>
> Can anyone tell me why os.path.isfile does not recognize my file?
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From rob@uselesspython.com  Tue Jul 30 23:02:25 2002
From: rob@uselesspython.com (Rob)
Date: Tue, 30 Jul 2002 17:02:25 -0500
Subject: [Tutor] listdir, ispath,  and unicode
In-Reply-To: <MPEOIFCOPCIHEDCLBLPBCEILCBAA.rob@uselesspython.com>
Message-ID: <MPEOIFCOPCIHEDCLBLPBEEIMCBAA.rob@uselesspython.com>

Please ignore my last message. I just noticed how much of the original post
I overlooked. (Guess I'm running low on brain fuel at the moment.)

If you care to send me a copy of one of the files, I'll gladly try a thing
or two.

Rob

> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Rob
> Sent: Tuesday, July 30, 2002 4:51 PM
> To: 'Tutor@Python. Org'
> Subject: RE: [Tutor] listdir, ispath, and unicode
>
>
> I'm also running Win2K on this machine and tried to reproduce
> your problem.
> Here I ran os.listdir on the folder on C:\insight. It displayed
> its contents
> in some detail.
>
> >>> os.listdir('c:\\insight')
> ['abbrev.html', 'begin.html', 'glossary.html', 'history.html',
> 'index-author.html', 'index-names.html', 'index-number.html',
> 'index-similes.html', 'index-subject.html', 'index-sutta.html',
> 'index-title.html', 'index.html', 'other.html', 'sutta101.html',
> 'theravada.html', 'tech', 'cdrom', 'pali', 'ptf', 'icon', 'lib', 'canon',
> 'faq.html', 'help.html', 'news.html', 'search.html', 'bfaq.html',
> 'Tibet-HTML']
>
> Then I ran os.path.isfile on one of the files in that folder thusly:
>
> >>> os.path.isfile('c:\\insight\\index-sutta.html')
> 1
> >>>
>
> All seems well here. It seems that in your code you are asking if
> the folder
> C:\tmp2 is a file, and you are being correctly told that it is not a file.
>
> Do I have all of your facts correct?
>
> Rob
> http://uselesspython.com
>
> > -----Original Message-----
> > From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> > Poor Yorick
> > Sent: Tuesday, July 30, 2002 3:54 PM
> > To: tutor@python.org
> > Subject: [Tutor] listdir, ispath, and unicode
> >
> >
> > I am running Windows 2000 and have files which use cyrillic characters
> > in their names.  I am running into this problem when I try to work with
> > them:
> >
> >
> >  >>> os.listdir('c:\\tmp2')[0]
> > '????????.url'
> >  >>> os.path.isfile(os.listdir('c:\\tmp2')[0])
> > 0
> >
> >
> > Can anyone tell me why os.path.isfile does not recognize my file?
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From dyoo@hkn.eecs.berkeley.edu  Tue Jul 30 23:18:59 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Jul 2002 15:18:59 -0700 (PDT)
Subject: [Tutor] if statement   [the string methods: endswith(),
 startswith(), and find()]
In-Reply-To: <XFMail.20020730103931.shalehperry@attbi.com>
Message-ID: <Pine.LNX.4.44.0207301508050.8267-100000@hkn.eecs.berkeley.edu>


On Tue, 30 Jul 2002, Sean 'Shaleh' Perry wrote:

>
> On 30-Jul-2002 Kelly, Phelim wrote:
> > Hi,
> >       hoping you can help me.... I'm trying to create an if statement that
> > works if a certain string contains a specified 4 characters. Basically I
> > want to quit the program if an imported file is a .jpg file, so I'm looking
> > for an if statement kind of like:
> >
> > if filename contains ".jpg":        (I'm looking for correct syntax for this
> > bit)
> >    sys.exit()


This almost works.  What we can ask is if the filename ends with the
extension ".jpg":

###
>>> 'foo.jpg'.endswith('.jpg')
1
>>> 'foo.jpg'.endswith('.png')
0
###

We want to check that the filename ends with that suffix '.jpg', and not
just if the filename contains the string '.jpg'.  We need to be strict
about this, because otherwise, we can hit pathological file names like
'foo.jpg.backup'!


But although we end up being safer with endswith(), we should say that
os.path.splitext() is an even better way to grab at the file extension,
since it takes platform-specific details into account.  Still, it's nice
to know that 'endswith()' is a method we can use to search the end of a
string.  Symmetrically, strings also have a 'startswith()' method to look
at the beginning of a string.


If we only care if a particular substring appears anywhere, we can use the
find() method to see where exactly some substring is located: if we can't
find the darn string, then find() will return us the nonsense index number
'-1':

###
>>> 'supercalifragilisticexpialidocous'.find('frag')
9
>>> 'supercalifragilisticexpialidocous'.find('foo')
-1
###


Hope this helps!



From mnavarre@anteon.com  Tue Jul 30 23:30:03 2002
From: mnavarre@anteon.com (Matthew Navarre)
Date: Tue, 30 Jul 2002 15:30:03 -0700
Subject: [Tutor] __init__ Problem, self is not defined
Message-ID: <200207301530.03758.mnavarre@anteon.com>

I'm attempting to subclass Pmw.ComboBox. when my class definition is run =
by=20
the interpreter I get a NameError: name self is not defined. AFAICT, my=20
syntax is correct, but I've obviously missed something.

here's the relevant part of my class definition:
from Tkinter import *
import Pmw

class AddressComboBox(Pmw.ComboBox):
    def __init__(self, root=3DNone, label_text=3D'Address:',
                label_pos=3D'w', listbox_width=3D24, dropdown=3D1,
                scrolledlist_items=3Dself.addresses, history=3D1,
                unique=3D1, selectioncommand=3Dself.getAddress,=20
                addressfile=3DNone ):

The interpreter gets to line five and throws NameError on self:
Python 2.2.1 (#1, Jun 27 2002, 13:17:43)=20
[GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4
Type "help", "copyright", "credits" or "license" for more information.
>>> import AddressComboBox
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "AddressComboBox.py", line 5, in ?
    class AddressComboBox(Pmw.ComboBox):
  File "AddressComboBox.py", line 6, in AddressComboBox
    def __init__(self, root=3DNone, label_text=3D'Address:',
NameError: name 'self' is not defined

Does anyone have an idea what's going on here? every example I have seems=
 like=20
this should work.=20

thanks,
Matt 'Well, I'm stumped' Navarre
--=20
mnavarre@anteon.com           Matthew Navarre
It was a hard sell, since he's a database person, and as far as I've seen=
,
once those database worms eat into your brain, it's hard to ever get
anything practical done again. To a database person, every nail looks
like a thumb. Or something like that. - jwz



From tbrauch@mindless.com  Wed Jul 31 00:17:21 2002
From: tbrauch@mindless.com (Timothy M. Brauch)
Date: Tue, 30 Jul 2002 19:17:21 -0400
Subject: [Tutor] Sorting
Message-ID: <000b01c2381f$41c89040$9c21840a@tmbrau00>

I have a class, Participant.  It has attributes last_name, first_name, and
team, among others.  I also have a class Competition.  Members of
Participant are inserted into a list in Competition.  Everything is going
great.

Now for my problem...
I would like to be able to sort the list of Participants in Competition in
specific ways.  I am pretty sure it can be done with sort(cmpfunc), but I
can't figure it out and documention on the cmpfunc for sort seems to be
lacking, or hard to find.  Here is an example session of what I would like
to have.

##Participant(first_name, last_name, team)
##This part works
>>p0 = Participant('Tim', 'Brauch', 'Foo')
>>p1 = Participant('Bob', 'Smith', 'Foo')
>>p2 = Participant('John', 'Doe', 'Bar')
>>p3 = Participant('Jane', 'Doe', 'Bar')
>>C = Competition()
>>C.add_p(p0)
>>C.add_p(p1)
>>C.add_p(p2)
>>C.add_p(p3)

##Now the part I can't get to work...
>>C.sort_by_team()
>>C.display()
Doe, Jane Bar
Doe, John Bar
Brauch, Tim Foo
Smith, Bob Foo

>>C.sort_alpha()
>>C.display()
Brauch, Tim Foo
Doe, Jane Bar
Doe, John Bar
Smith, Bob Foo

I tried writing sort_by_team() by scratch using if statements, but somehow
there is an error in my statements and possibly my identing, but at
something like 15 lines to sort a list, I think I am on the wrong track.
So, I would greatly appreciate it if someone could help me with the sort().

 - Tim



From dylan.belsey@baesystems.com  Wed Jul 31 01:19:18 2002
From: dylan.belsey@baesystems.com (BELSEY, Dylan)
Date: Wed, 31 Jul 2002 09:49:18 +0930
Subject: [Tutor] __init__ Problem, self is not defined
Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B96320D5@wtntex1.baea.com.au>

Matthew,
	Copied your code and ran it in idle.  I believe that the interpreter
is not actually falling over at 'self' but at
'scrolledlist_items=self.addresses'.  When declaring member functions (if
that is what they are called in Python), the 'self' as the first parameter
is standard. However the interpreter cannot find 'self.addresses' because it
has not been created yet (for that matter: self.getAddress as well).  These
can't be referred to in the __init__() args because they don't exist yet.
	Quoting Ivan Van Laningham in "SAMS Teach Yourself Python in 24
Hours", "Self...is just a simple, explicit way that a method can tell what
kind of object it is and that gives it a way to change its own state and/or
behaviour."
	In light of this, self is just being "defined" in the __init__()
method so the attributes such as 'address' and 'getAddress' are undefined.
	I put the following in a file (test.py) and ran it at the prompt
(the self. refs have been removed):


from Tkinter import *
import Pmw

class AddressComboBox(Pmw.ComboBox):
    def __init__(self, root=None, label_text='Address:',
                 label_pos='w', listbox_width=24, dropdown=1,
                 history=1,
                 unique=1,
                 addressfile=None):
        print "dasgd"

a = AddressComboBox()


C:\Python21>test.py
dasgd

C:\Python21>

	Unfortunately, not knowing how/why your class requires these input
parameters I can't be of much more assistance than to say you might have to
rethink your default values.
	Hope this helps,
		Dylan


-----Original Message-----
From: Matthew Navarre [mailto:mnavarre@anteon.com]
Sent: Wednesday, 31 July 2002 08:30
To: tutor@python.org
Subject: [Tutor] __init__ Problem, self is not defined



I'm attempting to subclass Pmw.ComboBox. when my class definition is run by 
the interpreter I get a NameError: name self is not defined. AFAICT, my 
syntax is correct, but I've obviously missed something.

here's the relevant part of my class definition:
from Tkinter import *
import Pmw

class AddressComboBox(Pmw.ComboBox):
    def __init__(self, root=None, label_text='Address:',
                label_pos='w', listbox_width=24, dropdown=1,
                scrolledlist_items=self.addresses, history=1,
                unique=1, selectioncommand=self.getAddress, 
                addressfile=None ):

The interpreter gets to line five and throws NameError on self:
Python 2.2.1 (#1, Jun 27 2002, 13:17:43) 
[GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4
Type "help", "copyright", "credits" or "license" for more information.
>>> import AddressComboBox
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "AddressComboBox.py", line 5, in ?
    class AddressComboBox(Pmw.ComboBox):
  File "AddressComboBox.py", line 6, in AddressComboBox
    def __init__(self, root=None, label_text='Address:',
NameError: name 'self' is not defined

Does anyone have an idea what's going on here? every example I have seems
like 
this should work. 

thanks,
Matt 'Well, I'm stumped' Navarre
-- 
mnavarre@anteon.com           Matthew Navarre
It was a hard sell, since he's a database person, and as far as I've seen,
once those database worms eat into your brain, it's hard to ever get
anything practical done again. To a database person, every nail looks
like a thumb. Or something like that. - jwz


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


From sarmstrong13@mac.com  Wed Jul 31 02:00:30 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 30 Jul 2002 20:00:30 -0500
Subject: [Tutor] Problem w/ redirect to shell
Message-ID: <B96CA0DE.A25B%sarmstrong13@mac.com>

Hi Everyone-

I was tranlating a perl script to python and I was having some problems.

Basically the script takes user input places it in an url string. The string
is then added to a text of applescript which is then executed as follows:

"osascript -l AppleScript -e %s" % todo

Where todo contains the applescript and the rest of the quoted string is the
command that is executed in the shell. This is a tcsh shell on OSX.
Basically this translates into something like the following:

Osascript -l AppleScript -e 'tell application Navigator to Get URL
"www.whatever.com"

How do I tell python to execute that command in the tcsh shell?


Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me



From jeff@ccvcorp.com  Wed Jul 31 02:25:05 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue, 30 Jul 2002 18:25:05 -0700
Subject: [Tutor] Problem w/ redirect to shell
References: <B96CA0DE.A25B%sarmstrong13@mac.com>
Message-ID: <3D473C71.48358152@ccvcorp.com>


SA wrote:

> How do I tell python to execute that command in the tcsh shell?

import os
os.system('string containing shell command here')

That should execute the given string using whatever the default shell is.  If
you need to capture the output of the command, then look into the os.popen()
family of functions.

Hope that helps...

Jeff Shannon
Technician/Programmer
Credit International




From dyoo@hkn.eecs.berkeley.edu  Wed Jul 31 02:33:33 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Jul 2002 18:33:33 -0700 (PDT)
Subject: [Tutor] Problem w/ redirect to shell  [grabbing URL data with
 urllib]
In-Reply-To: <B96CA0DE.A25B%sarmstrong13@mac.com>
Message-ID: <Pine.LNX.4.44.0207301827290.14074-100000@hkn.eecs.berkeley.edu>


On Tue, 30 Jul 2002, SA wrote:

> I was tranlating a perl script to python and I was having some problems.
>
> Basically the script takes user input places it in an url string. The
> string is then added to a text of applescript which is then executed as
> follows:
>
> "osascript -l AppleScript -e %s" % todo
>
> Where todo contains the applescript and the rest of the quoted string is
> the command that is executed in the shell. This is a tcsh shell on OSX.
> Basically this translates into something like the following:
>
> Osascript -l AppleScript -e 'tell application Navigator to Get URL
> "www.whatever.com"


HI SA,

I'm not too familiar with Applescript, but if I understand correctly, is
this code trying to retrieve the data associated with some URL?  If so,
would it be possible to use the 'urllib' library?

    http://www.python.org/doc/lib/module-urllib.html

If so, we may want to use urllib just to avoid touching tcsh: I always get
worried because of the tricky features of shell quoting.  Anything that
allows the user enter arbitrary commands needs to be treated carefully if
we're worried about security, and I trust 'urllib' more that tcsh.
*grin*



From jtk@yahoo.com  Tue Jul 30 17:47:03 2002
From: jtk@yahoo.com (Jeff Kowalczyk)
Date: Tue, 30 Jul 2002 12:47:03 -0400
Subject: [Tutor] Inheriting module-level attributes and methods in derived module
Message-ID: <ai6ftn$1pv$1@main.gmane.org>

I need to make a product that derives from Formulator (MyFormulator),
but allows me to selectively override certain methods. For example,
the only thing I need to change in FieldRegistry is the
initializeFieldForm() method. The FieldRegistry singleton should be
distinct from the original Formulator's one, so I can register a
different set of fields.

http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/formulator/Formulator/

Products\Formulator\FieldRegistry.py
-----------------------------------------------
(...)
class FieldRegistry:
    """A registry of fields, maintaining a dictionary with
    the meta_type of the field classes as key and the field class as
    values. Updates the Form as necessary as well.
    """
    def __init__(self):
        """Initializer of FieldRegistry.
        """
        self._fields = {}
(...)
# initialize registry as a singleton
FieldRegistry = FieldRegistry()

def initializeFieldForm(field_class):
    """Initialize the properties (fields and values) on a particular
    field class. Also add the tales and override methods.
    (...)
----------------------------------------------

How would  be set up? I'm new to all this, and formulator is a
complicated heirarchy to begin with. Do I need to derive a new
FieldRegistry to modify a module-level method, or to ensure that
I have a distinct singleton instance?

Products\MyFormulator\FieldRegistry.py
----------------------------------------------
from Products.Formulator.FieldRegistry import FieldRegistry
as BaseFieldRegistry

class FieldRegistry(BaseFieldRegistry):
    pass

# initialize registry as a singleton - Do I need this?
FieldRegistry = FieldRegistry()

def initializeFieldForm(field_class):
    """My new Doc string"""
    PossiblyCallBaseInitializeFieldForm(()
    # How do I? Namespace refs this FieldRegistry singleton?
    (write my own follow-on or complete replacement code here)
---------------------------------------------

Gives me errors like:
  File C:\(...)\Products\MyFormulator\FieldRegistry.py, line 3, in ?
TypeError: __init__() takes exactly 1 argument (4 given)

Or, an alternate way I was thinking it might need to be:
----------------------------------------------
from Products.Formulator.FieldRegistry import FieldRegistry
as BaseFieldRegistry

# initialize registry as a singleton
FieldRegistry = BaseFieldRegistry.FieldRegistry()

def initializeFieldForm(field_class):
    """Initialize the properties (fields and values) on a particular
    field class. Also add the tales and override methods.
----------------------------------------------
File C:\(...)\Products\Formulator3\FieldRegistry.py, line 4, in ?
AttributeError: FieldRegistry instance has no attribute 'FieldRegistry'

I guess I just don't grok module imports yet.

Thanks for any advice, I just need to have a few key concepts spelled
out for me, and I'll be off and running here. A couple more questions
to follow...







From sarmstrong13@mac.com  Wed Jul 31 03:49:36 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 30 Jul 2002 21:49:36 -0500
Subject: [Tutor] Problem w/ redirect to shell  [grabbing URL data with
 urllib]
In-Reply-To: <Pine.LNX.4.44.0207301827290.14074-100000@hkn.eecs.berkeley.edu>
Message-ID: <B96CBA70.A282%sarmstrong13@mac.com>

On 7/30/02 8:33 PM, "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> wrote:
> 
> HI SA,
> 
> I'm not too familiar with Applescript, but if I understand correctly, is
> this code trying to retrieve the data associated with some URL?  If so,
> would it be possible to use the 'urllib' library?
> 
>   http://www.python.org/doc/lib/module-urllib.html
> 
> If so, we may want to use urllib just to avoid touching tcsh: I always get
> worried because of the tricky features of shell quoting.  Anything that
> allows the user enter arbitrary commands needs to be treated carefully if
> we're worried about security, and I trust 'urllib' more that tcsh.
> *grin*
> 
> 
Osascript is a shell command in OSX that runs an command in a scripting
language. Basically the format is:

Osascript -l AppleScript -e 'command'

-l flag designates the script language to run, in this case applescript.
-e flag tells osascript to run the command in single quotes instead of
running a script file. The 'command' in this case is:

Tell application "Navigator" to Get URL "www.whatever.com"

This is a simple applescript that displays the website "www.whatever.com" in
the web browser "Navigator". In the case of the script I'm translating, I'm
taking a search term from the user and placing it in the Version Tracker
search string for their web site:

url = 
"http://www.versiontracker.com/mp/new_search.m?productDB=mac&mode=Quick&OS_F
ilter=%s&search=%s&x=0&y=0" % (filter, keyword)

Where filter is "MacOSX" and keyword is whatever the user of this script
wishes to search for. So as far as security goes in this case, it is opening
a page on someone elses search site.

Here is the python script:

#!/usr/bin/env python
import os
import sys
browser = "Navigator"
filter = "MacOSX"
keyword = sys.argv[1]
url = 
"http://www.versiontracker.com/mp/new_search.m?productDB=mac&mode=Quick&OS_F
ilt
er=%s&search=%s&x=0&y=0" % (filter, keyword)
todo = ""'Tell application "%s" to Get URL "%s"'"" % (browser, url)
os.system("osascript -l AppleScript -e '%s'" % todo)

Will urllib do this?
Can anyone find a simpler way to code this in Python?
Getting rid of the Applescript command would be best. This would keep
everything in python.

Here is the original perl script I was trying to translate:

#!/usr/bin/perl -w
#######
# This is a spiffy script written by Robert Daeley to
# search VersionTracker sans loading their frickin' big
# honkin' homepage. With the encouragement of cohort Hans Hickman.
# 27 7 2002 version 0.9.9
#######
# User-specified variables are below.
# To use, simply type ./vtsearch.pl (or whatever you name the script).
# A blank line will appear. Type keyword you want to search by and hit
return.
# $browser can be any webbrowser's full name

$browser = "OmniWeb";

#### LEAVE EVERYTHING BELOW AS IS ####

$filter = "MacOSX";
print "Search string: ";
$keyword = <STDIN>;
chomp($keyword);
$url = "http://www.versiontracker.com/mp/new_search.m?productDB=mac&
  mode=Quick&OS_Filter=".$filter."&search=".$keyword."&x=0&y=0";
$todo = "\'Tell application \"$browser\" to getURL \"$url\"\'";
system("osascript -l AppleScript -e $todo");



From sarmstrong13@mac.com  Wed Jul 31 04:27:10 2002
From: sarmstrong13@mac.com (SA)
Date: Tue, 30 Jul 2002 22:27:10 -0500
Subject: [Tutor] Newbie Help on reading files.
In-Reply-To: <20020726204215.GA4077@ak.silmarill.org>
Message-ID: <B96CC33E.A285%sarmstrong13@mac.com>

On 7/26/02 3:42 PM, "Andrei Kulakov" <ak@silmarill.org> wrote:
> No re, split.. if line.strip().startswith('#'): continue
> then split the rest and word[0] will be 'alias', word[1] will be
> filewho and then the rest will be 'sudo fs_usage'
> 

So if I was to use split, what search pattern needs to be used to keep split
from breaking up the last?

Test = "alias ls 'ls -l'"
Word = string.split(test, sep=??)

If you use the default whitespace word would =
["alias", "ls", "'ls", "-l'"]

How do I get:
["alias", "ls", "'ls -l'"]?

Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me





From kalle@lysator.liu.se  Wed Jul 31 05:16:13 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Wed, 31 Jul 2002 06:16:13 +0200
Subject: [Tutor] Sorting
In-Reply-To: <000b01c2381f$41c89040$9c21840a@tmbrau00>
References: <000b01c2381f$41c89040$9c21840a@tmbrau00>
Message-ID: <20020731041613.GA1161@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Timothy M. Brauch]
> I would like to be able to sort the list of Participants in
> Competition in specific ways.  I am pretty sure it can be done with
> sort(cmpfunc), but I can't figure it out and documention on the
> cmpfunc for sort seems to be lacking, or hard to find.  Here is an
> example session of what I would like to have.
[snip]

Maybe simple compare functions like these would work?

  def compare_by_team(x, y):
      return cmp(x.team, y.team)

  def compare_by_name(x, y):
      return (cmp(x.last_name, y.last_name) or
              cmp(x.first_name, y.first_name))

They mostly use the builtin function cmp that is the standard compare
function.  lst.sort() and lst.sort(cmp) are equivalent.

compare_by_name is a bit clever with the or.  It could be written as

  def compare_by_name(x, y):
      ln = cmp(x.last_name, y.last_name)
      if not ln: # Last names are equal
          return cmp(x.first_name, y.first_name)
      return ln

which is perhaps more clear.

> I tried writing sort_by_team() by scratch using if statements, but
> somehow there is an error in my statements and possibly my identing,
> but at something like 15 lines to sort a list, I think I am on the
> wrong track.  So, I would greatly appreciate it if someone could
> help me with the sort().

Generally, if you post more of your code and error messages, it is
easier to help.  This time, I don't think that it mattered.  Just a
tip for the future.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9R2SDdNeA1787sd0RAruWAJ0fbES9KN1LSnWnKHuXyjG8wgDryACgkWMh
44mgjNBmriZIoCrloxDV778=
=bnBJ
-----END PGP SIGNATURE-----


From dyoo@hkn.eecs.berkeley.edu  Wed Jul 31 05:20:54 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Jul 2002 21:20:54 -0700 (PDT)
Subject: [Tutor] Problem w/ redirect to shell  [grabbing URL data with
 urllib]
In-Reply-To: <B96CBA70.A282%sarmstrong13@mac.com>
Message-ID: <Pine.LNX.4.44.0207302106080.17903-100000@hkn.eecs.berkeley.edu>


> Osascript is a shell command in OSX that runs an command in a scripting
> language. Basically the format is:
>
> Osascript -l AppleScript -e 'command'
>
> -l flag designates the script language to run, in this case applescript.
> -e flag tells osascript to run the command in single quotes instead of
> running a script file. The 'command' in this case is:
>
> Tell application "Navigator" to Get URL "www.whatever.com"
>
> This is a simple applescript that displays the website
> "www.whatever.com" in the web browser "Navigator".

This sounds like a job for the 'webbrowser' module!

    http://www.python.org/doc/lib/module-webbrowser.html

The 'webbrowser' module should take action to make sure the url that's
being called doesn't have tricky escape sequences that try to do arbitrary
shell commands.


I've looked at the 'webbrowser' code a bit: I can't say for sure if it
works for any other browser besides IE.  You may want to check with the
pythonmac-sig mailing list to see if anyone else knows about this.  Here's
a link to the pythonmac-sig mailing list:

    http://www.python.org/sigs/pythonmac-sig/


Hope this helps!



From dyoo@hkn.eecs.berkeley.edu  Wed Jul 31 05:25:43 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Jul 2002 21:25:43 -0700 (PDT)
Subject: [Tutor] Sorting
In-Reply-To: <20020731041613.GA1161@i92.ryd.student.liu.se>
Message-ID: <Pine.LNX.4.44.0207302121310.17903-100000@hkn.eecs.berkeley.edu>


On Wed, 31 Jul 2002, Kalle Svensson wrote:

> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> [Timothy M. Brauch]
> > I would like to be able to sort the list of Participants in
> > Competition in specific ways.  I am pretty sure it can be done with
> > sort(cmpfunc), but I can't figure it out and documention on the
> > cmpfunc for sort seems to be lacking, or hard to find.  Here is an
> > example session of what I would like to have.
> [snip]
>
> Maybe simple compare functions like these would work?
>
>   def compare_by_team(x, y):
>       return cmp(x.team, y.team)
>
>   def compare_by_name(x, y):
>       return (cmp(x.last_name, y.last_name) or
>               cmp(x.first_name, y.first_name))

Hello!

Here's another way of defining compare_by_name without the tricky 'or':

###
def compare_by_name(x, y):
    return cmp( (x.last_name, x.first_name),
                (y.last_name, y.first_name) )
###

The reason this works is because, when Python compares between two tuples,
it does it in lexicographic order: that is, the first components of each
tuple are considered first, then the seconds, then the thirds, etc.


Best of wishes!



From lumbricus@gmx.net  Wed Jul 31 07:15:35 2002
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Wed, 31 Jul 2002 08:15:35 +0200 (MEST)
Subject: [Tutor] Problem w/ redirect to shell  [grabbing URL data with urllib]
References: <Pine.LNX.4.44.0207302106080.17903-100000@hkn.eecs.berkeley.edu>
Message-ID: <13633.1028096135@www58.gmx.net>

 
Hello!
 
Apropos tcsh:
"http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/"

HTH,HAND
J"o!

-- 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net



From tbrauch@tbrauch.com  Wed Jul 31 07:22:05 2002
From: tbrauch@tbrauch.com (Timothy M. Brauch)
Date: Wed, 31 Jul 2002 02:22:05 -0400
Subject: [Tutor] Sorting
References: <000b01c2381f$41c89040$9c21840a@tmbrau00> <20020731041613.GA1161@i92.ryd.student.liu.se>
Message-ID: <001801c2385a$977f2720$9c21840a@tmbrau00>

Let's send this to the entire list this time...

> I muttered something about:
> > I would like to be able to sort the list of Participants in
> > Competition in specific ways.  I am pretty sure it can be done with
> > sort(cmpfunc), but I can't figure it out and documention on the
> > cmpfunc for sort seems to be lacking, or hard to find.  Here is an
> > example session of what I would like to have.
> [snip]
> > I tried writing sort_by_team() by scratch using if statements, but
> > somehow there is an error in my statements and possibly my identing,
> > but at something like 15 lines to sort a list, I think I am on the
> > wrong track.  So, I would greatly appreciate it if someone could
> > help me with the sort().

>From the extremely helpful Kalle:
> Generally, if you post more of your code and error messages, it is
> easier to help.  This time, I don't think that it mattered.  Just a
> tip for the future.

Each Participant also has age.  How I sorted alphabetically previously,
which did not work:

    def sort_by_alpha1(self):
        self.results = []
        for ca in xrange(len(self.roster)):
            CA = self.roster[ca]
            if len(self.results) == 0:
                self.results.append(CA)
            elif (CA.last+CA.first <
self.results[0].last+self.results[0].first):
                self.results.insert(0, CA)
            elif (CA.last+CA.first >
self.results[0].last+self.results[0].first):
                self.results.append(CA)
            else:
                for da in xrange(len(self.results)):
                    DA = self.results[da]
                    if (CA.last+CA.first > DA.last+DA.first):
                        pass
                    elif CA not in self.results:
                        self.results.insert(da, CA)
        return self.results

And how I do it now, which works:

    def cmp_alpha1(self, x, y):
        return cmp((x.last, x.first),
                   (y.last, y.first))

    def sort_alpha1(self):
        self.results = []
        for item in self.roster:
            self.results.append(item)
        self.results.sort(self.cmp_alpha1)
        return self.results

But, more importantly, I understand how the new way works.  And, it is much
cleaner and easier to understand.

Thanks all

 - Tim




From dyoo@hkn.eecs.berkeley.edu  Wed Jul 31 07:36:13 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Jul 2002 23:36:13 -0700 (PDT)
Subject: [Tutor] __init__ Problem, self is not defined [default values
 assigned at method definition time]
In-Reply-To: <200207301530.03758.mnavarre@anteon.com>
Message-ID: <Pine.LNX.4.44.0207301725300.11818-100000@hkn.eecs.berkeley.edu>


On Tue, 30 Jul 2002, Matthew Navarre wrote:

> I'm attempting to subclass Pmw.ComboBox. when my class definition is run
> by the interpreter I get a NameError: name self is not defined. AFAICT,
> my syntax is correct, but I've obviously missed something.
>
> here's the relevant part of my class definition:
>
>
> from Tkinter import *
> import Pmw
>
> class AddressComboBox(Pmw.ComboBox):
>     def __init__(self, root=None, label_text='Address:',
>                 label_pos='w', listbox_width=24, dropdown=1,
>                 scrolledlist_items=self.addresses, history=1,
>                 unique=1, selectioncommand=self.getAddress,
>                 addressfile=None ):


Hi Matt,

During the __init__() function, you should assume that none of the 'self'
values have been initialized yet, so that's why one reason why
'self.addresses' and 'self.getAddress' can confuse Python...


... actually, I'm fibbing.  A more truthful reason is that all of the
default values in the __init__() definition need to make sense to Python
during the definition, even before any instances of AddressComboBox exist.


This can be really problematic if we're working with mutable things.  For
example:

###
>>> class TestInitializer:
...     def __init__(self, some_number=3*4, some_list=[]):
...         self.number = some_number
...         self.list = some_list
...
>>> t1 = TestInitializer()
>>> t1.number
12
>>> t1.list
[]
>>> t2 = TestInitializer()
>>> t2.number
12
>>> t2.list
[]
>>> t1.list.append(42)
>>> t1.list
[42]
>>> t2.list
[42]
###

Notice here that both t1 and t2 share that default list that was created
during the definition of __init__:

    def __init__(self, some_number=3*4, some_list=[]):

So default values get set once, during method definition, and they stick
with that same value for all calls to that method.



Here's another small example that shows when the default stuff is being
evaluated:

###
>>> def makelist():
...     print "I'm being called"
...     return []
...
>>> class TestDefault:
...     def __init__(self, value=makelist()):
...         self.value = value
...
I'm being called
>>> TestDefault()
<__main__.TestDefault instance at 0x8155884>
>>> TestDefault()
<__main__.TestDefault instance at 0x8152d5c>
###

The key thing here is seeing that "I'm being called" shows up immediately,
even before we create an instance.  And it only gets called once.



Going back to your original question: this is why trying to refer to
'self.addresses' and 'self.getAddress' doesn't work: those two names won't
be defined at that particular type as you're typing that __init__
definition.



Hmmm... what is self.addresses, though?  Is it referring to some
'addresses' variable in your class?  If so, you can express things this
way:

###
class AddressComboBox(Pmw.ComboBox):
    def __init__(self, root=None, label_text='Address:',
                label_pos='w', listbox_width=24, dropdown=1,
                scrolledlist_items=None, history=1,
                unique=1, selectioncommand=None,
                addressfile=None):

        if scrolledlist_items == None:
             scrolledlist_items = self.addresses

        if selectioncommand == None:
             selectioncommand = self.getAddress

        ## Continue on as in the previous code
###

Here, we sidestep things by setting our defaults to some sentinel "None"
value.  By the time we get into the body of the __init__, self.addresses
and self.getAddress should be accessible, so we should be in safe waters.


I get the feeling I didn't explain this well, so please ask more questions
about the places where things feel fuzzy.  Talk to you later!



From dyoo@hkn.eecs.berkeley.edu  Wed Jul 31 07:40:17 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Jul 2002 23:40:17 -0700 (PDT)
Subject: [Tutor] Sorting  [array slicing for copying arrays]
In-Reply-To: <001801c2385a$977f2720$9c21840a@tmbrau00>
Message-ID: <Pine.LNX.4.44.0207302338180.19701-100000@hkn.eecs.berkeley.edu>


> And how I do it now, which works:
>
>     def cmp_alpha1(self, x, y):
>         return cmp((x.last, x.first),
>                    (y.last, y.first))
>
>     def sort_alpha1(self):
>         self.results = []
>         for item in self.roster:
>             self.results.append(item)
>         self.results.sort(self.cmp_alpha1)
>         return self.results
>
> But, more importantly, I understand how the new way works.  And, it is
> much cleaner and easier to understand.

There's always room for improvement.  *grin* You can copy the roster in
one shot by using a whole array slice, like this:

    self.results = self.roster[:]


I hope this helps!



From alan.gauld@bt.com  Wed Jul 31 16:23:56 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 31 Jul 2002 16:23:56 +0100
Subject: [Tutor] Dynamic/Weak Types and large projects
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7C3@mbtlipnt02.btlabs.bt.co.uk>

> 1) Dynamic vs. Weak Types 

Weak typing is where the environment doesn't much care 
about type or where there are relatively few types existing.

For example in the early versions of Tcl everything was 
a string. You could pass anything into a function and 
Tcl just saw it as a string, it was only when you tried 
to use it that it fell over because it didn't know how 
to take the square root of "spam" for instance.

Python is similar because everything is a reference so 
the type checking gets done when you try to use it

Example:
>>>def f(a,b):
...   if a < b: print "smaller"
...   return b
...
>>>f(1,2)   # works OK
>>>f('a',2)  # errrm, what happens here?
>>>f([1,2,3],3+4j)  # even more so!

Python doesn't object to the function calls, rather any 
complaints come inside the function where the comparison 
is made. That's weak typing.

> 2) General consensus is that for large projects 
> strongly typed languages are better. Is there any 
> statistical proof of this beside hearsay? 

Yes. The reason strong typing(usually static typing) 
is important for large projects is that they tend to 
be built by large teams of people, often in different 
geographic locations working to paper specifications. 
It is important that interface definitions are 
rigorously adhered to and strong typing checks that
by raising the error early - usually at compile time.

Because errors are cheaper to fix the earlier you catch 
them its much better to find these inconsistencies 
before shipping rather than during integration testing.

You might think it would be caught during component 
test but the people who write the code normally do 
component test and they will use the code as they 
expect it to be used, which may not be how the 
client programmers(located elsewhere) expect to use 
it. By having the interface explicitly stated in 
a header file(C or C++) or an IDL file
(DCOM/DCE/CORBA/RMI etc) the code will fail to compile 
for whoever is not using the interface correctly.
(That's the benefit of static typing)

That's the theory. Unfortunately there's a lot that 
can still go wrong. 

int f(int, int);

defines a func that takes two integers but says nothing 
about the semantics of those integers, so the order 
could be interpreted differently at each end of the 
interface. Languages like ADA, Pascal, C++ allow us to 
define very strict types so that we can reduce that 
problem by using enums or sets which restrict the range 
of valid values(one reason the C #define approach 
discussed recently is a "Bad Thing")(This is obviously
a more "strict" typing) However that only reduces the 
problem not overcome it.

Nonetheless studies have shown that incompatible 
type usage is a significant problem on large projects 
and static/strict typing does help ameliorate it.

What is important to realize however is that this is 
a cost saving feature it is NOT a reliability issue. 
With a decent exception handling system (like Pythons)
the code either way will be equally reliable, its 
just a matter of when/how you catch the bug.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld


From rseguin@shaw.ca  Wed Jul 31 16:36:48 2002
From: rseguin@shaw.ca (Richard Seguin)
Date: Wed, 31 Jul 2002 11:36:48 -0400
Subject: [Tutor] Distribution of Python programs
Message-ID: <200207311136.55192.rseguin@shaw.ca>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hey guys,

Im just a little curious about something. In the Linux world I have no 
problems with letting someone use a .py file that I made...Its open 
source...Its suppose to be that way... My question is... If I want to give 
something that I made to a company that only runs Win* and they don't want to 
install Python, are there any wrappers that I could use (Like freewrap for 
tcl/tk) to make it into a .exe file?

My second question is along the same lines... With C and C++ you compile 
programs and run them.. With Python you don't have to, its all interpreted... 
Does anyone know if there is a major speed difference? Or is speed even an 
issue with Python? I know with TCL/TK there is a major slowdown.

Richard
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)

iD8DBQE9SAQXn9670YZTFEcRArizAJ0TqtEejQhhQOG+GgETPD1L5NcAcgCfWI4R
ZuWzgmAgAtnkTDapxgTbjlo=
=687S
-----END PGP SIGNATURE-----



From alan.gauld@bt.com  Wed Jul 31 16:41:12 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 31 Jul 2002 16:41:12 +0100
Subject: [Tutor] Dynamic/Weak Types and large projects
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7C4@mbtlipnt02.btlabs.bt.co.uk>

> > 1) Dynamic vs Weak Types
> >
> > I have heard python referred to as having "weak" types - how does
> > this differ from "dynamic types" ?
> 
> This is actually exactly the opposite of how most Pythonistas would
> describe Python's type system -- Python has *strong* but dynamic
> typing.  

In its builtin functions yes, but not in its user defined 
functions. Thats why I drew the comparison with early Tcl
(which is now improved BTW) because Python is stronger typed
than Tcl but weaker than VB say which can specify the types 
of function parameters.

> biggest drawback of static languages -- since you don't need to test
> everything for type mismatches, most programmers *won't* test

Thats a drawback of the organization's culture not the language!
Thorough testing should be done in any language!

> > 2) General consensus is that for large projects strongly typed
> > languages are better.

> No, there is no proof of this -- or at least, there's no proof that
> *statically* typed languages are better 

There is quite a body of proof that static typing catches 
one particular type of error early - and hence more cheaply.
That particular type of error is particularly common on 
large projects buoilt by distributed teams. Hence it is 
an advantage for that specific type of large project.

However....

> of the experimental evidence these days supports the 
> idea that dynamic langauges are "better" in most 
> senses of the word -- shorter code, fewer errors, 
> faster release times.  

This is also true and for ,most projects built in a single 
location by a single team I would tend towards dynamic 
typing backed up by thorough exception hanbdling.

In fact even the distributed case cost dsavings may be 
negated since the increased develop[ment speed of dynamically 
typed languages may more than make up for the savings 
in compile time checking. But the jury ius still out on 
that one... 

There are all sorts of legalistic/contractual advantages 
to static typechecking at compile time - contractors are 
only allowed to deliver cleanly compiling code(no lint 
errors etc) so it can be used as a stick to beat up 
your suppliers and ensure minimal quality standards. 
Frankly if thats your reason you have bigger problems 
to deal with IMHO! but then I'm not a lawyer....

Alan G.


From kalle@lysator.liu.se  Wed Jul 31 16:56:02 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Wed, 31 Jul 2002 17:56:02 +0200
Subject: [Tutor] Distribution of Python programs
In-Reply-To: <200207311136.55192.rseguin@shaw.ca>
References: <200207311136.55192.rseguin@shaw.ca>
Message-ID: <20020731155602.GC17547@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Richard Seguin]
> Im just a little curious about something. In the Linux world I have
> no problems with letting someone use a .py file that I made...Its
> open source...Its suppose to be that way... My question is... If I
> want to give something that I made to a company that only runs Win*
> and they don't want to install Python, are there any wrappers that I
> could use (Like freewrap for tcl/tk) to make it into a .exe file?

Yeah.  There's the McMillan Installer and py2exe.  I can't comment on
the relative strengths of them, but I guess Google should be able to
find them for you together with comments by users.

> My second question is along the same lines... With C and C++ you
> compile programs and run them.. With Python you don't have to, its
> all interpreted...  Does anyone know if there is a major speed
> difference? Or is speed even an issue with Python? I know with
> TCL/TK there is a major slowdown.

It depends.  Yes, interpreted code runs slower.  Depending on the type
of computations, Python code can be very much slower than C.  On the
other hand, for most tasks the difference isn't that big.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9SAhwdNeA1787sd0RApdSAKCDVvFuLt4id9UN1YTpZRJfiCO5YACgjstD
ocpLUSI8oHVXLZskrA/jx5s=
=FLBL
-----END PGP SIGNATURE-----


From alan.gauld@bt.com  Wed Jul 31 16:55:08 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 31 Jul 2002 16:55:08 +0100
Subject: [Tutor] Newbie Help on reading files.
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7C5@mbtlipnt02.btlabs.bt.co.uk>

> So if I was to use split, what search pattern needs to be 
> used to keep split from breaking up the last?

You don't, you rely on the fact that you can extract the 
first two items then join the rest back together again...

> Test = "alias ls 'ls -l'"
> Word = string.split(test, sep=??)

alias = Word[1]  # ignore literal 'alias' at pos 0
cmd = string.joinfields(Word[2:])  # join the rest as a string

Alan g.


From alan.gauld@bt.com  Wed Jul 31 17:06:24 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 31 Jul 2002 17:06:24 +0100
Subject: [Tutor] Distribution of Python programs
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C7C7@mbtlipnt02.btlabs.bt.co.uk>

> install Python, are there any wrappers that I could use (Like 
> freewrap for tcl/tk) to make it into a .exe file?

Yes. Freeze comes in the standard distro but is a bit 
limited. py2exe and Gordon MacMillans installer are 
the most popular tools for this. py2exe is reputedly 
the easiest to use.

> My second question is along the same lines... With C and C++ 
> you compile programs and run them.. 
> Does anyone know if there is a major speed difference? 

Yes, on average Python is about 5-10 times slower than 
C/C++ Of course if you are mainly using libraries written 
in C then it might only be a factor of 2 or 3, and if 
you are doing a lot ogf database access you might not 
even notice the difference! OTOH if you try writing 
a big number crunching app in pure python you will see 
it for sure!

> speed even an issue with Python? 

Depends on what you are doing. Speed is only an issue 
if its too slow. If its a batch job that runs overnight 
while you are sleeping do you care if it finishes 5 
minutes later? OTOH if its a missile avoidance system 
on a fighter jet that 10ms difference might matter a lot!

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld


From terjeja@hotmail.com  Wed Jul 31 18:26:09 2002
From: terjeja@hotmail.com (Terje Johan Abrahamsen)
Date: Wed, 31 Jul 2002 17:26:09 +0000
Subject: [Tutor] Tkinter Editor
Message-ID: <F8BxoZBgvf5B5nJE0lD00020b12@hotmail.com>

Hello,

   Does anyone know about a good editor for graphical Python creation? I 
would like to know if there is an editor that can help me create the code 
for boxes, pictures and so forth. Then I can paste that code into my own 
code, without having to write it. For example something along the lines of 
the object creator for VBA that comes with Excel. Preferably one that has 
somewhat more possibilities. However, just something that simple would also 
save me some time..

Thanks in advance,
Terje



_________________________________________________________________
Chat with friends online, try MSN Messenger: http://messenger.msn.com



From wilson@visi.com  Wed Jul 31 19:14:12 2002
From: wilson@visi.com (Tim Wilson)
Date: Wed, 31 Jul 2002 13:14:12 -0500
Subject: [Tutor] Tkinter Editor
In-Reply-To: <F8BxoZBgvf5B5nJE0lD00020b12@hotmail.com>
References: <F8BxoZBgvf5B5nJE0lD00020b12@hotmail.com>
Message-ID: <20020731181411.GA24666@isis.visi.com>

On Wed, Jul 31, 2002 at 05:26:09PM +0000, Terje Johan Abrahamsen wrote:
> 
>   Does anyone know about a good editor for graphical Python creation?

It's not Tkinter, but the Boa Constructor project
(http://boa-constructor.sourceforge.net/) is doing something like that
wiith wxWindows. Never tried it though.

-Tim

-- 
Tim Wilson      |   Visit Sibley online:   | Check out:
Henry Sibley HS |  http://www.isd197.org   | http://www.zope.com
W. St. Paul, MN |                          | http://slashdot.org
wilson@visi.com |  <dtml-var pithy_quote>  | http://linux.com


From printers@sendme.cz  Wed Jul 31 19:54:41 2002
From: printers@sendme.cz (A)
Date: Wed, 31 Jul 2002 20:54:41 +0200
Subject: [Tutor] Problem - how to solve it ?
Message-ID: <3D484E91.4394.15F5A3@localhost>

Hi,
I have a program that I compiled( with Installer) into exe for using 
on Win32 systems. It works well on Windows Me, Windows 9x but 
on some computers with Windows 2000 it causes General 
Protection Error and the programs is finished. It would be nice if the 
program wrote a line number or something similar that could help a 
user find out which command caused that General Protection 
Error. Is there any solution for that?
Thank you for help
Ladislav




From pooryorickprivate@pooryorick.com  Wed Jul 31 21:09:17 2002
From: pooryorickprivate@pooryorick.com (Poor Yorick)
Date: Wed, 31 Jul 2002 14:09:17 -0600
Subject: [Tutor] listdir, ispath and unicode (followup question)
Message-ID: <3D4843ED.4000200@pooryorick.com>

Thank you for your previous responses.  I am still having this difficulty:

 >>> filename = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])
 >>> filename
'd:\\tmp2\\???????'
 >>> os.path.isfile(filename)
0


The file, 'd:\\tmp2\\???????', is a text file which I created for 
testing this problem.  Any ideas why os.path.isfile function does not 
recognize this file?



From terjeja@hotmail.com  Wed Jul 31 21:29:33 2002
From: terjeja@hotmail.com (Terje Johan Abrahamsen)
Date: Wed, 31 Jul 2002 20:29:33 +0000
Subject: [Tutor] wxPython
Message-ID: <F160F5ldfZWjSeKg1bz00016725@hotmail.com>

I downloaded wxPython and started to look around. It seems to be a great 
tool. However, I haven't found much documentation. Ok, there is, but not 
that I understand much of. Most seems to be for C++.

So, I took one of the examples and tried to run it in Python. But, it wanted 
some arguments. However, I have no idea what arguments to give, and all my 
guesses ended in failure. Could somebody look at this code, and let me know 
what arguments are needed? And hopefully also write a few sentences about 
how this thing work. I guess, when I get it first running, I can modify and 
play around... PS!! This is all I can find about it. No more 
documentation...

Thanks in advance,
Terje

from wxPython.wx import *

#---------------------------------------------------------------------------

class TestCheckBox(wxPanel):
    def __init__(self, parent, log):
        self.log = log
        wxPanel.__init__(self, parent, -1)

        wxStaticText(self, -1, "This example uses the wxCheckBox control.",
                               wxPoint(10, 10))

        cID = NewId()
        cb1 = wxCheckBox(self, cID,   "  Apples", wxPoint(65, 40), 
wxSize(150, 20), wxNO_BORDER)
        cb2 = wxCheckBox(self, cID+1, "  Oranges", wxPoint(65, 60), 
wxSize(150, 20), wxNO_BORDER)
        cb2.SetValue(true)
        cb3 = wxCheckBox(self, cID+2, "  Pears", wxPoint(65, 80), 
wxSize(150, 20), wxNO_BORDER)

        EVT_CHECKBOX(self, cID,   self.EvtCheckBox)
        EVT_CHECKBOX(self, cID+1, self.EvtCheckBox)
        EVT_CHECKBOX(self, cID+2, self.EvtCheckBox)


    def EvtCheckBox(self, event):
        self.log.WriteText('EvtCheckBox: %d\n' % event.Checked())

#---------------------------------------------------------------------------

def runTest(frame, nb, log):
    win = TestCheckBox(nb, log)
    return win

#---------------------------------------------------------------------------















overview = """\
A checkbox is a labelled box which is either on (checkmark is visible) or 
off (no checkmark).

"""




_________________________________________________________________
MSN Photos is the easiest way to share and print your photos: 
http://photos.msn.com/support/worldwide.aspx



From rob@uselesspython.com  Wed Jul 31 21:40:45 2002
From: rob@uselesspython.com (Rob)
Date: Wed, 31 Jul 2002 15:40:45 -0500
Subject: [Tutor] wxPython
In-Reply-To: <F160F5ldfZWjSeKg1bz00016725@hotmail.com>
Message-ID: <MPEOIFCOPCIHEDCLBLPBGEKOCBAA.rob@uselesspython.com>

I'm away from all my documentation and stuff in a secluded hole where I can
study for my final exam in this C++ and Win32 API class I'm taking, or I'd
try to take a bit of a stab at this one.

I've seen it stated before that there would be more wxPython documentation,
but that the documentation for wxWindows is supposed to be quite good and
carries over to wxPython directly to a great degree.

Rob

> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Terje Johan Abrahamsen
> Sent: Wednesday, July 31, 2002 3:30 PM
> To: tutor@python.org
> Subject: [Tutor] wxPython
>
>
> I downloaded wxPython and started to look around. It seems to be a great
> tool. However, I haven't found much documentation. Ok, there is, but not
> that I understand much of. Most seems to be for C++.
>
> So, I took one of the examples and tried to run it in Python.
> But, it wanted
> some arguments. However, I have no idea what arguments to give,
> and all my
> guesses ended in failure. Could somebody look at this code, and
> let me know
> what arguments are needed? And hopefully also write a few sentences about
> how this thing work. I guess, when I get it first running, I can
> modify and
> play around... PS!! This is all I can find about it. No more
> documentation...
>
> Thanks in advance,
> Terje
>
> from wxPython.wx import *
>
> #-----------------------------------------------------------------
> ----------
>
> class TestCheckBox(wxPanel):
>     def __init__(self, parent, log):
>         self.log = log
>         wxPanel.__init__(self, parent, -1)
>
>         wxStaticText(self, -1, "This example uses the wxCheckBox
> control.",
>                                wxPoint(10, 10))
>
>         cID = NewId()
>         cb1 = wxCheckBox(self, cID,   "  Apples", wxPoint(65, 40),
> wxSize(150, 20), wxNO_BORDER)
>         cb2 = wxCheckBox(self, cID+1, "  Oranges", wxPoint(65, 60),
> wxSize(150, 20), wxNO_BORDER)
>         cb2.SetValue(true)
>         cb3 = wxCheckBox(self, cID+2, "  Pears", wxPoint(65, 80),
> wxSize(150, 20), wxNO_BORDER)
>
>         EVT_CHECKBOX(self, cID,   self.EvtCheckBox)
>         EVT_CHECKBOX(self, cID+1, self.EvtCheckBox)
>         EVT_CHECKBOX(self, cID+2, self.EvtCheckBox)
>
>
>     def EvtCheckBox(self, event):
>         self.log.WriteText('EvtCheckBox: %d\n' % event.Checked())
>
> #-----------------------------------------------------------------
> ----------
>
> def runTest(frame, nb, log):
>     win = TestCheckBox(nb, log)
>     return win
>
> #-----------------------------------------------------------------
> ----------
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> overview = """\
> A checkbox is a labelled box which is either on (checkmark is visible) or
> off (no checkmark).
>
> """
>
>
>
>
> _________________________________________________________________
> MSN Photos is the easiest way to share and print your photos:
> http://photos.msn.com/support/worldwide.aspx
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From shalehperry@attbi.com  Wed Jul 31 21:38:32 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 31 Jul 2002 13:38:32 -0700 (PDT)
Subject: [Tutor] listdir, ispath and unicode (followup question)
In-Reply-To: <3D4843ED.4000200@pooryorick.com>
Message-ID: <XFMail.20020731133832.shalehperry@attbi.com>

On 31-Jul-2002 Poor Yorick wrote:
> Thank you for your previous responses.  I am still having this difficulty:
> 
>  >>> filename = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])
>  >>> filename
> 'd:\\tmp2\\???????'
>  >>> os.path.isfile(filename)
> 0
> 
> 
> The file, 'd:\\tmp2\\???????', is a text file which I created for 
> testing this problem.  Any ideas why os.path.isfile function does not 
> recognize this file?
> 

os.path is a wrapper for various operating systems.  The isfile() function is
itself a wrapper around os.stat()

    try:
        st = os.stat(path)
    except os.error:
        return 0
    return stat.S_ISREG(st[stat.ST_MODE])

so, does os.stat() raise os.error? or is the stat info returned incorrect.  If
os.error is raised there should be more information available as well.  Try
doing the os.stat() call from the interactive interpreter.


From troels@kvaksalver.dk  Wed Jul 31 22:00:12 2002
From: troels@kvaksalver.dk (Troels Leth Petersen)
Date: Wed, 31 Jul 2002 23:00:12 +0200
Subject: [Tutor] Tkinter Editor
References: <F8BxoZBgvf5B5nJE0lD00020b12@hotmail.com>
Message-ID: <02e901c238d5$4315b200$0a01a8c0@allah>

>    Does anyone know about a good editor for graphical Python
>   creation?

Try using the ressource editor that comes with PythonCard (tutorial on
the subject : http://pythoncard.sourceforge.net/walkthrough2.html )

Regards,
Troels



From gp@pooryorick.com  Wed Jul 31 22:15:41 2002
From: gp@pooryorick.com (Poor Yorick)
Date: Wed, 31 Jul 2002 15:15:41 -0600
Subject: [Tutor] listdir, ispath and unicode (followup question)
References: <XFMail.20020731133832.shalehperry@attbi.com>
Message-ID: <3D48537D.8090300@pooryorick.com>

I am running Windows 2000 English edition.  The filename contains 
cyrillic characters typed with a standard Windows 2000 IME when I 
created the file.  Here is  the result of your suggestion:

filename = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])

 >>> filename
'd:\\tmp2\\???????'
 >>> os.stat(filename)
Traceback (most recent call last):
 File "<pyshell#5>", line 1, in ?
   os.stat(filename)
OSError: [Errno 2] No such file or directory: 'd:\\tmp2\\???????'



Sean 'Shaleh' Perry wrote:

>On 31-Jul-2002 Poor Yorick wrote:
>
>>Thank you for your previous responses.  I am still having this difficulty:
>>
>> >>> filename = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])
>> >>> filename
>>'d:\\tmp2\\???????'
>> >>> os.path.isfile(filename)
>>0
>>
>>
>>The file, 'd:\\tmp2\\???????', is a text file which I created for 
>>testing this problem.  Any ideas why os.path.isfile function does not 
>>recognize this file?
>>
>
>os.path is a wrapper for various operating systems.  The isfile() function is
>itself a wrapper around os.stat()
>
>    try:
>        st = os.stat(path)
>    except os.error:
>        return 0
>    return stat.S_ISREG(st[stat.ST_MODE])
>
>so, does os.stat() raise os.error? or is the stat info returned incorrect.  If
>os.error is raised there should be more information available as well.  Try
>doing the os.stat() call from the interactive interpreter.
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>




From gp@pooryorick.com  Wed Jul 31 22:16:56 2002
From: gp@pooryorick.com (Poor Yorick)
Date: Wed, 31 Jul 2002 15:16:56 -0600
Subject: [Tutor] listdir, ispath and unicode (followup question)
References: <XFMail.20020731133832.shalehperry@attbi.com>
Message-ID: <3D4853C8.8070507@pooryorick.com>

I am running Windows 2000 English edition.  The filename contains 
cyrillic characters typed with a standard Windows 2000 IME when I 
created the file.  Here is  the result of your suggestion:

filename = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])

 >>> filename
'd:\\tmp2\\???????'
 >>> os.stat(filename)
Traceback (most recent call last):
 File "<pyshell#5>", line 1, in ?
   os.stat(filename)
OSError: [Errno 2] No such file or directory: 'd:\\tmp2\\???????'



Sean 'Shaleh' Perry wrote:

>On 31-Jul-2002 Poor Yorick wrote:
>
>>Thank you for your previous responses.  I am still having this difficulty:
>>
>> >>> filename = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])
>> >>> filename
>>'d:\\tmp2\\???????'
>> >>> os.path.isfile(filename)
>>0
>>
>>
>>The file, 'd:\\tmp2\\???????', is a text file which I created for 
>>testing this problem.  Any ideas why os.path.isfile function does not 
>>recognize this file?
>>
>
>os.path is a wrapper for various operating systems.  The isfile() function is
>itself a wrapper around os.stat()
>
>    try:
>        st = os.stat(path)
>    except os.error:
>        return 0
>    return stat.S_ISREG(st[stat.ST_MODE])
>
>so, does os.stat() raise os.error? or is the stat info returned incorrect.  If
>os.error is raised there should be more information available as well.  Try
>doing the os.stat() call from the interactive interpreter.
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>




From jeff@ccvcorp.com  Wed Jul 31 22:30:48 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed, 31 Jul 2002 14:30:48 -0700
Subject: [Tutor] listdir, ispath and unicode (followup question)
References: <XFMail.20020731133832.shalehperry@attbi.com> <3D4853C8.8070507@pooryorick.com>
Message-ID: <3D485708.69B95EC7@ccvcorp.com>

Poor Yorick wrote:

> filename = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])

This is tangential to your real problem, but the above snippet can be made a little
clearer by using os.path.abspath(), which combines relative path information with
the current working directory to calculate an absolute path.

>>> os.chdir('c:/temp')
>>> os.listdir(os.getcwd())[0]
'textfile.txt'
>>> os.path.abspath('textfile.txt')
'c:\\temp\\textfile.txt'
>>>

Combined all together, you would use

filename = os.path.abspath( os.listdir(os.getcwd())[0] )

Still not exactly transparent, but a little less ugly than the os.path.join()
solution.  :)

Jeff Shannon
Technician/Programmer
Credit International




From glingl@aon.at  Wed Jul 31 22:53:03 2002
From: glingl@aon.at (Gregor Lingl)
Date: Wed, 31 Jul 2002 23:53:03 +0200
Subject: [Tutor] Use? Abuse? Amusement? Amendments?
Message-ID: <3D485C3F.3060304@aon.at>

This is a multi-part message in MIME format.
--------------070104060008060808070206
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit

Hi!
If you, incidentally, are going to have a coffee-break,
please, run the code of the attachment.
Your opinion?
Gregor


--------------070104060008060808070206
Content-Type: text/plain;
 name="trees.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="trees.py"

from __future__ import generators
from turtle import *
        
def ttree(t,l):
    if l > 12.0:
        t.forward(l)
        yield 1
        t.left(25)
        for x in ttree(t, l * 0.65 ):
            yield x
        t.right(60)
        yield 1
        for x in ttree(t, l * 0.52 ):
            yield x
        t.left(35)
        t.backward(l)
        yield 1

turtles = (leonardo, raphael, donatello) = (Pen(), Pen(), Pen())
for turtle in turtles:
    turtle.left(90)
    turtle.up()

leonardo.goto(-100,-100)
leonardo.color("red")
raphael.goto( 0, -100)
raphael.color("green")
donatello.goto(100,-100)
donatello.color("orange")

for turtle in turtles:
    turtle.down()
    turtle.width(3)

ltree = ttree(leonardo,79.0)
rtree = ttree(raphael, 100.0)
dtree = ttree(donatello, 66.0)

done = 0
while done < 3:
    done = 0
    for tree in (ltree, rtree, dtree):
        try:
            tree.next()
        except:
            done += 1

leonardo.up()
leonardo.goto(-140,-135)
leonardo.write("HOW CAN THIS BE DONE WITHOUT GENERATORS?")

raw_input("Press Enter!")


--------------070104060008060808070206--




From rob@uselesspython.com  Wed Jul 31 23:01:25 2002
From: rob@uselesspython.com (Rob)
Date: Wed, 31 Jul 2002 17:01:25 -0500
Subject: [Tutor] Use? Abuse? Amusement? Amendments?
In-Reply-To: <3D485C3F.3060304@aon.at>
Message-ID: <MPEOIFCOPCIHEDCLBLPBCELCCBAA.rob@uselesspython.com>

That was novel.

> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Gregor Lingl
> Sent: Wednesday, July 31, 2002 4:53 PM
> To: tutor@python.org
> Cc: edu-sig@python.org
> Subject: [Tutor] Use? Abuse? Amusement? Amendments?
> 
> 
> Hi!
> If you, incidentally, are going to have a coffee-break,
> please, run the code of the attachment.
> Your opinion?
> Gregor
> 
> 



From shalehperry@attbi.com  Wed Jul 31 22:57:34 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 31 Jul 2002 14:57:34 -0700 (PDT)
Subject: [Tutor] Use? Abuse? Amusement? Amendments?
In-Reply-To: <3D485C3F.3060304@aon.at>
Message-ID: <XFMail.20020731145734.shalehperry@attbi.com>

On 31-Jul-2002 Gregor Lingl wrote:
> Hi!
> If you, incidentally, are going to have a coffee-break,
> please, run the code of the attachment.
> Your opinion?
> Gregor
> 

where does one get turtle?


From dyoo@hkn.eecs.berkeley.edu  Wed Jul 31 23:04:44 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 31 Jul 2002 15:04:44 -0700 (PDT)
Subject: [Tutor] listdir, ispath and unicode (followup question)
In-Reply-To: <3D4853C8.8070507@pooryorick.com>
Message-ID: <Pine.LNX.4.44.0207311503360.11041-100000@hkn.eecs.berkeley.edu>


On Wed, 31 Jul 2002, Poor Yorick wrote:

> I am running Windows 2000 English edition.  The filename contains
> cyrillic characters typed with a standard Windows 2000 IME when I
> created the file.  Here is  the result of your suggestion:
>
> filename = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])
>
>  >>> filename
> 'd:\\tmp2\\???????'
>  >>> os.stat(filename)
> Traceback (most recent call last):
>  File "<pyshell#5>", line 1, in ?
>    os.stat(filename)
> OSError: [Errno 2] No such file or directory: 'd:\\tmp2\\???????'


Hmmm... now I'm suspecting that the cyrillic characters might be making a
difference.  I did a scan through the Python Enhancement Proposal 277:

    http://www.python.org/peps/pep-0277.html

which implies that Unicode filenames might not work out-of-the-box.  If
your locale at that point where you're running the Python script isn't
Cyrillic, that can potentially cause problems.


The PEP above provides an implementation that's supposed to handle Unicode
filenames properly, without the intermediate LOCALE translation stuff; can
you see if this works for you?  Sorry about the roundabout way of
answering your question.



From kalle@lysator.liu.se  Wed Jul 31 23:26:41 2002
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Thu, 1 Aug 2002 00:26:41 +0200
Subject: [Tutor] Use? Abuse? Amusement? Amendments?
In-Reply-To: <XFMail.20020731145734.shalehperry@attbi.com>
References: <3D485C3F.3060304@aon.at> <XFMail.20020731145734.shalehperry@attbi.com>
Message-ID: <20020731222641.GA1856@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Sean 'Shaleh' Perry]
> where does one get turtle?

It seems to be a part of the standard library.
http://www.python.org/doc/current/lib/module-turtle.html

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9SGQadNeA1787sd0RAngkAKCdbxhdNJd6J4zawWLAYVhbh9vWDwCgtIA4
acTGCIaZTaeik061IPDr6BM=
=GtY4
-----END PGP SIGNATURE-----


From printers@sendme.cz  Wed Jul 31 19:54:41 2002
From: printers@sendme.cz (A)
Date: Wed, 31 Jul 2002 20:54:41 +0200
Subject: [Tutor] Problem - how to solve it ?
Message-ID: <3D484E91.4394.15F5A3@localhost>

Hi,
I have a program that I compiled( with Installer) into exe for using 
on Win32 systems. It works well on Windows Me, Windows 9x but 
on some computers with Windows 2000 it causes General 
Protection Error and the programs is finished. It would be nice if the 
program wrote a line number or something similar that could help a 
user find out which command caused that General Protection 
Error. Is there any solution for that?
Thank you for help
Ladislav


_______________________________________________
ActivePython mailing list
ActivePython@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython



From miracle@paradise.net.nz  Wed Jul 31 23:08:16 2002
From: miracle@paradise.net.nz (Matthew Sherborne)
Date: Thu, 01 Aug 2002 10:08:16 +1200
Subject: [Tutor] Re: Problem - how to solve it ?
References: <3D484E91.4394.15F5A3@localhost>
Message-ID: <3D485FD0.7080504@paradise.net.nz>

GPFs are fired when some C code crashes not python code. In the error it 
should give the name of a DLL or say python.exe.

To find what part of your code is causing the error, do print messages, 
or write to a log file in the area around where the program crashes.

Start in the highest level of the code, print a line before and after 
each sub routine is called, where the print outs stop, go to the sub 
routine after the last print out and put a bunch of print lines between 
all the sections in that and re-run. Keep narrowing it down like this. :)

It may a bug in some windows DLL, so you could either fix it, or release 
a "Known Issues.txt" file with the program, letting them know that they 
must update their windows release if this happens. :)

GBU
Matthew Sherborne

A wrote:

>Hi,
>I have a program that I compiled( with Installer) into exe for using 
>on Win32 systems. It works well on Windows Me, Windows 9x but 
>on some computers with Windows 2000 it causes General 
>Protection Error and the programs is finished. It would be nice if the 
>program wrote a line number or something similar that could help a 
>user find out which command caused that General Protection 
>Error. Is there any solution for that?
>Thank you for help
>Ladislav
>
>
>_______________________________________________
>ActivePython mailing list
>ActivePython@listserv.ActiveState.com
>To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
>Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython
>
>
>
>  
>