From urnerk@qwest.net  Sat Dec  1 00:35:43 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 30 Nov 2001 16:35:43 -0800
Subject: [Tutor] the class struggle
In-Reply-To: <20011130150431.D27400@hal>
References: <4.2.0.58.20011129160411.019fcce0@pop3.norton.antivirus>
 <20011129170901.B27400@hal>
 <4.2.0.58.20011129160411.019fcce0@pop3.norton.antivirus>
Message-ID: <4.2.0.58.20011130161852.00c5d400@pop3.norton.antivirus>

Hi Rob --

It occurred to me later that maybe what you were trying
to do was write a factory class that'd spawn instances
which had different behaviors depending on the name used
to instance them (as an arg to __init__).

It'd be like a computer game, where your factory produces
game characters, and if you pass it 'King' (as a name),
then the instantiated character should do something
different when you go myking.says(), then if you
instantiate using the name 'Peasant' and go myguy.says().

Anyway, even if that's not what you meant, the code below
might provide useful grist for the mill anyway.  I stick
possible behaviors in a Behaviors class, and then use the
Factory class (which inherits from Behavior) to assign
different Behavior methods to self.behavior:

   class Behaviors:
        "Ways we might define children's behavior()"
	def namer(self):
	    return self.name
	def rand(self):
	    return randint(1,10)
	def deter(self):
	    return "Go away!"
	
   class Factory(Behaviors):
        """
        Spawn instances with different ideas about
        behavior() depending on arg name
        """
	def __init__(self,name):
	    self.name = name
	    if name == "Boring":
		self.behavior = self.namer
	    elif name == "Randomizer":
		self.behavior = self.rand
	    else:
		self.behavior = self.deter

		
  >>> obj1 = Factory("Boring")
  >>> obj2 = Factory("Randomizer")
  >>> obj3 = Factory("Anybody")
  >>> obj1.behavior()
  'Boring'
  >>> obj2.behavior()
  10
  >>> obj3.behavior()
  'Go away!'

Kirby



From i812@iname.com  Sat Dec  1 01:19:39 2001
From: i812@iname.com (Rob McGee)
Date: Fri, 30 Nov 2001 19:19:39 -0600
Subject: [Tutor] the class struggle
In-Reply-To: <Pine.LNX.4.21.0111301356400.4193-100000@hkn.eecs.berkeley.edu>; from dyoo@hkn.eecs.berkeley.edu on Fri, Nov 30, 2001 at 02:22:32PM -0800
References: <20011130150431.D27400@hal> <Pine.LNX.4.21.0111301356400.4193-100000@hkn.eecs.berkeley.edu>
Message-ID: <20011130191939.C5837@hal>

On Fri, Nov 30, 2001 at 02:22:32PM -0800, Danny Yoo wrote:
> >     How, in a class __init__ function, can you get the name of the
> >     instance?
> 
> 
> This depends on what you mean by "name".  An example might clarify:
> 
> ###
> >>> class Person:
> ...     def __init__(self, name):
> ...         self.name = name
> ...     def sayHello(self):
> ...         print "Hello, my name is", self.name
> [snip]
> Is this what you mean?  What's tricky about your question is the ambiguity
> of the word "name", so if you can give an example, that will help a lot.  
> Hope this helps!

That is exactly what I mean. I simply pass the "name" variable to the
class instantiation. I don't really even need to set a "self.name"
variable -- for my purposes all I need is to evaluate that "name"
parameter inside the __init__ function:

{code}
soviet = ['Lenin', 'Trotsky', 'Stalin']

class Struggle:
  def __init__(self, list, name):
    self.Communist = 1
    if name in list:
      self.Soviet = 1
    else:
      self.Soviet = 0

myList = ['Marx', 'Engels', 'Lenin', 'Mao']

for x in myList:
  execString = x + ' = Struggle(soviet, "' + x + '")'
  exec(execString)
  evalCommunist = x + '.Communist'
  evalSoviet = x + '.Soviet'
  if eval(evalCommunist):
    print x, 'was a known Communist.'
  if eval(evalSoviet):
    print x, 'was a Soviet leader.'

print "rob0 is winning the struggle to understand Python classes."
{/code}

That did it!! Thank you all for turning the light on. :)

    Rob - /dev/rob0


From arazak@kansai.com.my  Sat Dec  1 02:44:09 2001
From: arazak@kansai.com.my (Mr. Abd Razak)
Date: Sat, 1 Dec 2001 10:44:09 +0800
Subject: [Tutor] Setting path for module
Message-ID: <003701c17a12$11293dc0$6a01a8c0@com.my>

This is a multi-part message in MIME format.

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

Hi to all,

I need some here, Until now i still don't know how to set path for my =
own module.
I put my module in the c:\python21\ownmodule.
But every time i call the module i get the answer, python cannot locate =
for the module.

I know i have to set the environmment, can anyone help me.

Thanks.

Razak.

------=_NextPart_000_0034_01C17A55.1CBDE3A0
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>Hi to all,</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial>I need some here, Until now i still don't know =
how to set=20
path for my own module.</FONT></DIV>
<DIV><FONT face=3DArial>I put my module in the =
c:\python21\ownmodule.</FONT></DIV>
<DIV><FONT face=3DArial>But every time i call the module i get the =
answer, python=20
cannot locate for&nbsp;the module.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial>I know i have to set the environmment, can =
anyone help=20
me.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial>Thanks.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial>Razak.</FONT></DIV></BODY></HTML>

------=_NextPart_000_0034_01C17A55.1CBDE3A0--



From i812@iname.com  Sat Dec  1 02:42:53 2001
From: i812@iname.com (Rob McGee)
Date: Fri, 30 Nov 2001 20:42:53 -0600
Subject: [Tutor] Newbie Question:  IDLE, is there a HOWTO use...
In-Reply-To: <5.1.0.14.0.20011130140831.02dda470@mail45566.popserver.pop.net>; from fpeavy@pop.net on Fri, Nov 30, 2001 at 02:10:22PM -0800
References: <5.1.0.14.0.20011130140831.02dda470@mail45566.popserver.pop.net>
Message-ID: <20011130204253.E27400@hal>

On Fri, Nov 30, 2001 at 02:10:22PM -0800, Frank Peavy wrote:
> So far, I have used the IDLE to edit py's but it seems that there is more 
> to it than that.
> Is there a HOWTO for the use of IDLE?

http://www.python.org/idle/doc/

    Rob - /dev/rob0


From dyoo@hkn.eecs.berkeley.edu  Sat Dec  1 02:32:05 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 30 Nov 2001 18:32:05 -0800 (PST)
Subject: [Tutor] the class struggle
In-Reply-To: <20011130191939.C5837@hal>
Message-ID: <Pine.LNX.4.21.0111301830130.9757-100000@hkn.eecs.berkeley.edu>

On Fri, 30 Nov 2001, Rob McGee wrote:

> That is exactly what I mean. I simply pass the "name" variable to the
> class instantiation. I don't really even need to set a "self.name"
> variable -- for my purposes all I need is to evaluate that "name"
> parameter inside the __init__ function:
> 
> {code}
> soviet = ['Lenin', 'Trotsky', 'Stalin']
> 
> class Struggle:
>   def __init__(self, list, name):
>     self.Communist = 1
>     if name in list:
>       self.Soviet = 1
>     else:
>       self.Soviet = 0
> 
> myList = ['Marx', 'Engels', 'Lenin', 'Mao']
> 
> for x in myList:
>   execString = x + ' = Struggle(soviet, "' + x + '")'
>   exec(execString)
>   evalCommunist = x + '.Communist'
>   evalSoviet = x + '.Soviet'
>   if eval(evalCommunist):
>     print x, 'was a known Communist.'
>   if eval(evalSoviet):
>     print x, 'was a Soviet leader.'


By the way, you don't need to use eval() so much.  Instead of:

    eval('x' + ".Soviet")

you can just use:

    x.Soviet

with the same effect.

Have a good weekend!



From urnerk@qwest.net  Sat Dec  1 02:40:37 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 30 Nov 2001 18:40:37 -0800
Subject: [Tutor] the class struggle
In-Reply-To: <20011130191939.C5837@hal>
References: <Pine.LNX.4.21.0111301356400.4193-100000@hkn.eecs.berkeley.edu>
 <20011130150431.D27400@hal>
 <Pine.LNX.4.21.0111301356400.4193-100000@hkn.eecs.berkeley.edu>
Message-ID: <4.2.0.58.20011130182547.00c66d70@pop3.norton.antivirus>

>
>myList = ['Marx', 'Engels', 'Lenin', 'Mao']
>
>for x in myList:
>   execString = x + ' = Struggle(soviet, "' + x + '")'
>   exec(execString)
>   evalCommunist = x + '.Communist'
>   evalSoviet = x + '.Soviet'
>   if eval(evalCommunist):
>     print x, 'was a known Communist.'
>   if eval(evalSoviet):
>     print x, 'was a Soviet leader.'
>
>print "rob0 is winning the struggle to understand Python classes."
>{/code}

Although these exec-intensive code segments are fun to
write, I think they obscure your demonstration.  If the
point is to show what your Struggle class is doing, it'd
be best to not automate all the keystrokes here (lots
of extraneous overhead), and simply quote some
straightforward shell, e.g.

  >>> Marx = Struggle(['Lenin', 'Trotsky', 'Stalin'],'Marx')
  >>> if Marx.Communist:
         print 'Marx', 'was a known Communist'

  "Marx was a known Communist"

Queuing up a bunch of variable names in a list and
looping through an exec to assign them, and then
evaluate their properties, might make sense in some
bigger program (might), but for sharing purposes (i.e.
making your meanings clear), all this exec stuff seems
unnecessarily obfuscatory.

Just for future reference, in case you're trying
to present another case study.

>That did it!! Thank you all for turning the light on. :)

In any case, you've achieved your goal, and that's
the important thing.

Kirby



From cow@esweeet.com  Sat Dec  1 03:44:01 2001
From: cow@esweeet.com (Cow)
Date: Fri, 30 Nov 2001 19:44:01 -0800 (PST)
Subject: [Tutor] Programming Networking Software with Python
Message-ID: <20011201034401.C4BC23ECD@sitemail.everyone.net>

Does anyone know of any good sites or tutorials that explain how to program internet/networking programs in Python.  Is there something similiar to Winsock (what you use in VB to program networking software) in Python that i can use to program networking software in Python?  i want to be able to connect to servers, send information, recieve information, and other stuff like that...

Thanks a lot!
-Ryan

_____________________________________________________________
Free eSweeet Mail - http://www.esweeet.com


From ak@silmarill.org  Sat Dec  1 03:52:13 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 30 Nov 2001 22:52:13 -0500
Subject: [Tutor] Programming Networking Software with Python
In-Reply-To: <20011201034401.C4BC23ECD@sitemail.everyone.net>
References: <20011201034401.C4BC23ECD@sitemail.everyone.net>
Message-ID: <20011130225213.A9931@sill.silmarill.org>

On Fri, Nov 30, 2001 at 07:44:01PM -0800, Cow wrote:
> Does anyone know of any good sites or tutorials that explain how to program internet/networking programs in Python.  Is there something similiar to Winsock (what you use in VB to program networking software) in Python that i can use to program networking software in Python?  i want to be able to connect to servers, send information, recieve information, and other stuff like that...
> 
> Thanks a lot!
> -Ryan

Take a look at socket module in library reference.

> 
> _____________________________________________________________
> Free eSweeet Mail - http://www.esweeet.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 urnerk@qwest.net  Sat Dec  1 04:04:04 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 30 Nov 2001 20:04:04 -0800
Subject: [Tutor] Programming Networking Software with Python
In-Reply-To: <20011201034401.C4BC23ECD@sitemail.everyone.net>
Message-ID: <4.2.0.58.20011130195329.019fd440@pop3.norton.antivirus>

At 07:44 PM 11/30/2001 -0800, you wrote:
>Does anyone know of any good sites or tutorials that explain
>how to program internet/networking programs in Python.

Certain Python comes with batteries included.  The
Standard Library will do all that.

In addition to 'The Standard Python Library' by
Fredrik Lundh (latest version) I also think
'Python 2.1 Bible' by Dave Brueck and Stephen Tanner
(Hungry Minds, 2001) is one of the better ones, and
not cited nearly enough.

It has lots about doing internet stuff, plus multi-
threading, GUI widgets (both Tk and wxPython), XML,
pickling, extension modules and more.  It's friendly
in style and starts with the basics.

Like, a few times I've tried to get whoever maintains
http://www.amk.ca/bookstore/python.html to list it,
but to no avail.

Oh well.

Kirby




From karthikg@aztec.soft.net  Sat Dec  1 07:28:03 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Sat, 1 Dec 2001 12:58:03 +0530
Subject: [Tutor] Setting path for module
In-Reply-To: <003701c17a12$11293dc0$6a01a8c0@com.my>
Message-ID: <NEBBJNMDEKBIBCMCNMBDAEIPCKAA.karthikg@aztec.soft.net>

This is a multi-part message in MIME format.

------=_NextPart_000_0016_01C17A67.D00986F0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

can be done in the code itself..

import sys
sys.path.append("c:\\python21\\ownmodule")

karthik.
  -----Original Message-----
  From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Mr. Abd Razak
  Sent: Saturday, December 01, 2001 8:14 AM
  To: tutor@python.org
  Subject: [Tutor] Setting path for module


  Hi to all,

  I need some here, Until now i still don't know how to set path for my own
module.
  I put my module in the c:\python21\ownmodule.
  But every time i call the module i get the answer, python cannot locate
for the module.

  I know i have to set the environmment, can anyone help me.

  Thanks.

  Razak.

------=_NextPart_000_0016_01C17A67.D00986F0
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.4616.200" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><SPAN class=3D454292607-01122001><FONT face=3DArial color=3D#0000ff =
size=3D2>can be=20
done in the code itself..</FONT></SPAN></DIV>
<DIV><SPAN class=3D454292607-01122001><FONT face=3DArial color=3D#0000ff =

size=3D2></FONT></SPAN><SPAN class=3D454292607-01122001><FONT =
face=3DArial=20
color=3D#0000ff size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D454292607-01122001><FONT face=3DArial color=3D#0000ff =
size=3D2>import=20
sys</FONT></SPAN></DIV>
<DIV><SPAN class=3D454292607-01122001><FONT face=3DArial color=3D#0000ff =

size=3D2>sys.path.append("<FONT color=3D#000000=20
size=3D3>c:\\python21\\ownmodule")</FONT></FONT></SPAN></DIV>
<DIV><SPAN class=3D454292607-01122001><FONT =
face=3DArial></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D454292607-01122001><FONT=20
face=3DArial>karthik.</FONT></SPAN></DIV>
<BLOCKQUOTE dir=3Dltr style=3D"MARGIN-RIGHT: 0px">
  <DIV class=3DOutlookMessageHeader dir=3Dltr align=3Dleft><FONT =
face=3DTahoma=20
  size=3D2>-----Original Message-----<BR><B>From:</B> =
tutor-admin@python.org=20
  [mailto:tutor-admin@python.org]<B>On Behalf Of </B>Mr. Abd=20
  Razak<BR><B>Sent:</B> Saturday, December 01, 2001 8:14 =
AM<BR><B>To:</B>=20
  tutor@python.org<BR><B>Subject:</B> [Tutor] Setting path for=20
  module<BR><BR></FONT></DIV>
  <DIV><FONT face=3DArial>Hi to all,</FONT></DIV>
  <DIV><FONT face=3DArial color=3D#0000ff size=3D2></FONT>&nbsp;</DIV>
  <DIV><FONT face=3DArial>I need some here, Until now i still don't know =
how to=20
  set path for my own module.</FONT></DIV>
  <DIV><FONT face=3DArial>I put my module in the=20
  c:\python21\ownmodule.</FONT></DIV>
  <DIV><FONT face=3DArial>But every time i call the module i get the =
answer,=20
  python cannot locate for&nbsp;the module.</FONT></DIV>
  <DIV><FONT face=3DArial color=3D#0000ff size=3D2></FONT>&nbsp;</DIV>
  <DIV><FONT face=3DArial>I know i have to set the environmment, can =
anyone help=20
  me.</FONT></DIV>
  <DIV>&nbsp;</DIV>
  <DIV><FONT face=3DArial>Thanks.</FONT></DIV>
  <DIV>&nbsp;</DIV>
  <DIV><FONT face=3DArial>Razak.</FONT></DIV></BLOCKQUOTE></BODY></HTML>

------=_NextPart_000_0016_01C17A67.D00986F0--



From deliberatus@my995internet.com  Sat Dec  1 17:23:27 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sat, 01 Dec 2001 12:23:27 -0500
Subject: [Tutor] Tutorials
Message-ID: <3C09120F.91E1F54E@my995internet.com>

The severral tutorials at the python site seem to cover basics, jump to
select parts of intermediate materials, and stop.

I ned a good solid read (webwise) on the language, filling in some blank
spots, and gradually building up to the advanced material. I have  been
pointed at the total language reference in reply to questions about
advanced material- but I am not ready to fully understand this yet.
Alas, many holes in my knowledge still exist, but the totorials also
seem to have considerable gaps. Any advice?

I have GOT to hammer this thing into my concrete skull, or I am going to
bloody EXPLODE from fustration. I KNOW what I want to do,. I can
FLOWCHART it. 

But I can't CODE it. ARG.

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From ak@silmarill.org  Sat Dec  1 17:35:53 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Sat, 01 Dec 2001 12:35:53 -0500
Subject: [Tutor] Tutorials
In-Reply-To: <3C09120F.91E1F54E@my995internet.com>
References: <3C09120F.91E1F54E@my995internet.com>
Message-ID: <20011201123553.A16290@sill.silmarill.org>

On Sat, Dec 01, 2001 at 12:23:27PM -0500, Kirk Bailey wrote:
> The severral tutorials at the python site seem to cover basics, jump to
> select parts of intermediate materials, and stop.
> 
> I ned a good solid read (webwise) on the language, filling in some blank
> spots, and gradually building up to the advanced material. I have  been
> pointed at the total language reference in reply to questions about
> advanced material- but I am not ready to fully understand this yet.
> Alas, many holes in my knowledge still exist, but the totorials also
> seem to have considerable gaps. Any advice?
> 
> I have GOT to hammer this thing into my concrete skull, or I am going to
> bloody EXPLODE from fustration. I KNOW what I want to do,. I can
> FLOWCHART it. 
> 
> But I can't CODE it. ARG.

What's so horrible about buying a book? I mean, if you read all the
dozen or so web tutorials, and that's not enough, you ought to go for
dead trees.

You did read Alan Gauld's tutorial and How to think like a computer
scientist one? 

> 
> -- 
> Respectfully,
>              -Kirk D Bailey (C)2001
>               Addme! icq #27840081
> end
> 
> 
> Within the sweep of his sword, Each man is an Ubar.
> 
> http://www.howlermonkey.net/
> http://www.sacredelectron.org/
> 
> _______________________________________________
> 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 mennosimons@gmx.net  Sat Dec  1 18:02:49 2001
From: mennosimons@gmx.net (Willi Richert)
Date: Sat, 1 Dec 2001 19:02:49 +0100
Subject: [Tutor] 1,5 hours of Python lecture
Message-ID: <200112011802.fB1I2oc01235@wr.richert>

Hi,

in one lecture "Scripting languages" I escaped from doing a Perl/Javascript 
project as a lecture project in favor of giving the class a lecture in 
Python. Hehe...
I want to do some "Perl vs. Python" for about 30 minutes and then present a 
project in Python which grows incrementally. I.e. that I start from "Hello 
World" and end up in some program that shows the most important 
advantages/possibilities in Python. It is not that everybody can program 
Python afterwards, but that everybody wants to learn it ;-) 
I will not type in front of the class, but copy/paste preprogrammed code 
blocks.

I would like to ask you now, which topics I should cover in the online 
tutorial?

Some topics I figured out, which should be covered:

Language Basics:
----------------------
OOP, 
Functional Programming, 
Multithreading

Libs:
-----
Web Clients: Email, FTP, etc
Web Server: TCPServer, 
Regexp

Any help is appreciated,
willi



From myuen@ucalgary.ca  Sat Dec  1 19:28:31 2001
From: myuen@ucalgary.ca (Mike Yuen)
Date: Sat, 1 Dec 2001 12:28:31 -0700 (MST)
Subject: [Tutor] Help with lists
Message-ID: <Pine.A41.4.10.10112011222010.59280-100000@acs2.acs.ucalgary.ca>

I've got a bit of a problem with lists that I need some help with.

What I have is a pair of sub-elements (20 and A4) within each element such
as: 
[20, A4] <-- We'll call this pair "big element"

There are over 20000 such big elements.  Not all of them are going to have
a unique 1st sub-element (ie: the above big element has 20 as it's 1st
sub element)

What i'm trying to do is group them all the big elements with
the same 1st subelements together.
For example:
[20, A4]
[20, A2]
[20, E] 

Will make the following big element:
[20, A4, A2, E]

Can someone help me out?  I have to stick with lists as the structure
meaning I can't use tuples or dictionaries.

Thanks,
M



From myuen@ucalgary.ca  Sat Dec  1 20:22:35 2001
From: myuen@ucalgary.ca (Mike Yuen)
Date: Sat, 1 Dec 2001 13:22:35 -0700 (MST)
Subject: [Tutor] Need more precise digits
Message-ID: <Pine.A41.4.10.10112011319300.59282-100000@acs2.acs.ucalgary.ca>

I've trying to calculate an average and it looks like i'm losing some
precision in digits.

For example: i've got the following formula
avgsize = float(totalsize/groups)

both totalsize and groups are integers
I've got 10 groups
sizes are:
2+3+2+2+3+2+2+2+2+2 = 22

I should get 22/10 = 2.2.

What I get is 2.0.  How do I get this missing 2 tenths?  As you can see
from the above, I already casted to a float.

Thanks,
M




From pythontutor@venix.com  Sat Dec  1 21:00:20 2001
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat, 01 Dec 2001 16:00:20 -0500
Subject: [Tutor] Need more precise digits
References: <Pine.A41.4.10.10112011319300.59282-100000@acs2.acs.ucalgary.ca>
Message-ID: <3C0944E4.1000209@venix.com>

You really want something like:
avgsize = float(totalsize)/float(groups)

In older Python's:
	22/10 = 2
	float(22/10) = float(2) = 2.0

You need to convert to float BEFORE doing the division.


Mike Yuen wrote:

> I've trying to calculate an average and it looks like i'm losing some
> precision in digits.
> 
> For example: i've got the following formula
> avgsize = float(totalsize/groups)
> 
> both totalsize and groups are integers
> I've got 10 groups
> sizes are:
> 2+3+2+2+3+2+2+2+2+2 = 22
> 
> I should get 22/10 = 2.2.
> 
> What I get is 2.0.  How do I get this missing 2 tenths?  As you can see
> from the above, I already casted to a float.
> 
> Thanks,
> M
> 
> 
> 
> _______________________________________________
> 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 pythontutor@venix.com  Sat Dec  1 22:00:13 2001
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat, 01 Dec 2001 17:00:13 -0500
Subject: [Tutor] Help with lists
References: <Pine.A41.4.10.10112011222010.59280-100000@acs2.acs.ucalgary.ca>
Message-ID: <3C0952ED.30503@venix.com>

My understanding:
You have a list of pairs.  You wish to combine those pairs where the first element is the
same into a longer list without duplicating the first element.

One approach is to sort the list based upon the first pair value.  Then step through the
list appending each pair to a new list.  If the last element in the new list matches our
current pair, combine them rather than appending.

In Python:
def combine(listlist,list_a):
   if listlist == []:
     listlist.append(list_a)
   elif listlist[-1][0] == list_a[0]:
     listlist[-1].extend(list_a[1:])
   else:
     listlist.append(list_a)
   return listlist
l1 = [ [1,'a'],[2,'a'],[3,'a'],[2,'b'],[4,'b'],[2,'c']]+[[20, 'A4'],[20, 'A2'],[20, 'E']]
l1.sort()
l2 = reduce(combine, l1, [])
print l2
 >>> [[1, 'a'], [2, 'a', 'b', 'c'], [3, 'a'], [4, 'b'], [20, 'A2', 'A4', 'E']]

reduce is one of the "functional" functions in Python.  The first argument is a function that
will be applied to each element in a list along with the functions prior return value.  The
second argument is the list to be processed.  The optional third argument represents the
initial function return value.

reduce is most commonly used to turn a list into a single value such as by adding up the list
elements.  It is also handy for this kind of list transformation.

Mike Yuen wrote:

> I've got a bit of a problem with lists that I need some help with.
> 
> What I have is a pair of sub-elements (20 and A4) within each element such
> as: 
> [20, A4] <-- We'll call this pair "big element"
> 
> There are over 20000 such big elements.  Not all of them are going to have
> a unique 1st sub-element (ie: the above big element has 20 as it's 1st
> sub element)
> 
> What i'm trying to do is group them all the big elements with
> the same 1st subelements together.
> For example:
> [20, A4]
> [20, A2]
> [20, E] 
> 
> Will make the following big element:
> [20, A4, A2, E]
> 
> Can someone help me out?  I have to stick with lists as the structure
> meaning I can't use tuples or dictionaries.
> 
> Thanks,
> M
> 
> 
> _______________________________________________
> 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 urnerk@qwest.net  Sat Dec  1 22:37:53 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 01 Dec 2001 14:37:53 -0800
Subject: [Tutor] 1,5 hours of Python lecture
In-Reply-To: <200112011802.fB1I2oc01235@wr.richert>
Message-ID: <4.2.0.58.20011201143504.019ccad0@pop3.norton.antivirus>

At 07:02 PM 12/1/2001 +0100, Willi Richert wrote:


>I want to do some "Perl vs. Python" for about 30 minutes


Does 'Perl vs. Python' really have to be the focus?

In my circles, people who do language war schticks
immediately lose propaganda points -- kinda like
doing 'English vs. Spanish' or 'Hindi vs. Tibetan'.

The more credible approach (in my neck of the woods)
is to simply show Python jumping through hoops, to
please and amaze people, but to not spend a lot of time
on a negative campaign against Perl (or any other
language).

After all, some of the best Python programmers also
use Perl sometimes, and vice versa.

That being said, a few wise cracks are OK.

Kirby



From lha2@columbia.edu  Sat Dec  1 21:03:04 2001
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Sat, 01 Dec 2001 16:03:04 -0500
Subject: [Tutor] Need more precise digits
References: <Pine.A41.4.10.10112011319300.59282-100000@acs2.acs.ucalgary.ca>
Message-ID: <3C094588.79737ACE@mail.verizon.net>

It's enough to cast either of the arguments to division as a float (in
Python <= 2.1--haven't tried 2.2 yet, and can't remember whether integer
division was canned yet by then, or if that's 2.3).

So 

avgsize = float(totalsize)/groups

will work (you don't have to float both)

Mike Yuen wrote:
> 
> I've trying to calculate an average and it looks like i'm losing some
> precision in digits.
> 
> For example: i've got the following formula
> avgsize = float(totalsize/groups)
> 
> both totalsize and groups are integers
> I've got 10 groups
> sizes are:
> 2+3+2+2+3+2+2+2+2+2 = 22
> 
> I should get 22/10 = 2.2.
> 
> What I get is 2.0.  How do I get this missing 2 tenths?  As you can see
> from the above, I already casted to a float.
> 
> Thanks,
> M
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From dyoo@hkn.eecs.berkeley.edu  Sat Dec  1 23:49:13 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 1 Dec 2001 15:49:13 -0800 (PST)
Subject: [Tutor] Tutorials
In-Reply-To: <3C09120F.91E1F54E@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112011544200.31870-100000@hkn.eecs.berkeley.edu>

On Sat, 1 Dec 2001, Kirk Bailey wrote:

> The severral tutorials at the python site seem to cover basics, jump
> to select parts of intermediate materials, and stop.
> 
> I ned a good solid read (webwise) on the language, filling in some
> blank spots, and gradually building up to the advanced material. I
> have been pointed at the total language reference in reply to
> questions about advanced material- but I am not ready to fully
> understand this yet. Alas, many holes in my knowledge still exist, but
> the totorials also seem to have considerable gaps. Any advice?

You might be interested in the "Programming Python" book by Mark Lutz;
it's a comprehensive walk through the language.  Personally I think it's
way too large; I like books that I can hold in one hand.  *grin* Still, it
might be worth browsing.

But don't forget; we're here too!  What in particular are you trying to
do?  We might be able to find some resources that might help you write
your program.



From urnerk@qwest.net  Sat Dec  1 23:56:17 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 01 Dec 2001 15:56:17 -0800
Subject: [Tutor] Need more precise digits
In-Reply-To: <3C094588.79737ACE@mail.verizon.net>
References: <Pine.A41.4.10.10112011319300.59282-100000@acs2.acs.ucalgary.ca>
Message-ID: <4.2.0.58.20011201155341.019dbdb0@pop3.norton.antivirus>

At 04:03 PM 12/1/2001 -0500, Lloyd Hugh Allen wrote:
>It's enough to cast either of the arguments to division as a float (in
>Python <= 2.1--haven't tried 2.2 yet, and can't remember whether integer
>division was canned yet by then, or if that's 2.3).


In 2.2 you have to go:

from __future__ import division

if you want division to default to floating point "true
division" i.e.

   >>> 3/2    # 3 and 2 are both type int
   1.5

That'll be phased out over time, meaning this type of
division will be the default.

Without importing anything, you can use the new // operator
any time, which forces an integer result e.g.

   >>> 3.0//2.0
   1.0

Kirby



Kirby



From dyoo@hkn.eecs.berkeley.edu  Sun Dec  2 00:05:46 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 1 Dec 2001 16:05:46 -0800 (PST)
Subject: [Tutor] Help with lists
In-Reply-To: <Pine.A41.4.10.10112011222010.59280-100000@acs2.acs.ucalgary.ca>
Message-ID: <Pine.LNX.4.21.0112011557260.31870-100000@hkn.eecs.berkeley.edu>

On Sat, 1 Dec 2001, Mike Yuen wrote:

> I've got a bit of a problem with lists that I need some help with.
> 
> What I have is a pair of sub-elements (20 and A4) within each element such
> as: 
> [20, A4] <-- We'll call this pair "big element"
> 
> There are over 20000 such big elements.  Not all of them are going to have
> a unique 1st sub-element (ie: the above big element has 20 as it's 1st
> sub element)
> 
> What i'm trying to do is group them all the big elements with
> the same 1st subelements together.
> For example:
> [20, A4]
> [20, A2]
> [20, E] 
> 
> Will make the following big element:
> [20, A4, A2, E]
> 
> Can someone help me out?  I have to stick with lists as the structure
> meaning I can't use tuples or dictionaries.


Can we use dictionaries to help us construct the big elements?  If so,
then your problem isn't too bad.  Here's one idea: we can use a dictionary
to help group our lists by the first element:

###
def cluster(elements):
    holder = {}
    for e in elements:
        first, second = e
        holder[first] = holder.get(first, []) + [second]
    return holder.items()
###


Let's see how this works:

###
>>> cluster(l)
[(17, ['seventeen']), (20, ['A4', 'A2', 'E'])]
###

It's not perfect yet, but you can bend cluster() a bit to make it solve
your problem.



From dyoo@hkn.eecs.berkeley.edu  Sun Dec  2 00:10:17 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 1 Dec 2001 16:10:17 -0800 (PST)
Subject: [Tutor] Need more precise digits
In-Reply-To: <Pine.A41.4.10.10112011319300.59282-100000@acs2.acs.ucalgary.ca>
Message-ID: <Pine.LNX.4.21.0112011606060.31870-100000@hkn.eecs.berkeley.edu>

On Sat, 1 Dec 2001, Mike Yuen wrote:

> I've trying to calculate an average and it looks like i'm losing some
> precision in digits.
> 
> For example: i've got the following formula
> avgsize = float(totalsize/groups)

The problem is one of timing: by the time float() works on its argument,
we've already lost precision.  In Python,

###
>>> float(1/2)
0.0
###

is evaluated in steps: first, Python needs to figure out what '1/2' looks
like:

###
>>> 1/2
0
###

and then Python can call float() on '0'.

###
>>> float(0)
0.0
###


When we call functions, Python needs to figure out first what the
arguments will look like.  This is the bug that you're running into.


Hope this helps!



From sarnold@earthling.net  Sun Dec  2 00:23:13 2001
From: sarnold@earthling.net (Steve Arnold)
Date: 01 Dec 2001 16:23:13 -0800
Subject: [Tutor] Need more precise digits
In-Reply-To: <Pine.LNX.4.21.0112011606060.31870-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.21.0112011606060.31870-100000@hkn.eecs.berkeley.edu>
Message-ID: <1007252593.8525.0.camel@rama>

On Sat, 2001-12-01 at 16:10, Danny Yoo wrote:
> On Sat, 1 Dec 2001, Mike Yuen wrote:
> 
> > I've trying to calculate an average and it looks like i'm losing some
> > precision in digits.
> > 
> > For example: i've got the following formula
> > avgsize = float(totalsize/groups)
> 
> The problem is one of timing: by the time float() works on its argument,
> we've already lost precision.  In Python,
> 
> ###
> >>> float(1/2)
> 0.0
> ###
[snip]

So either 1 or 2 needs to be a float; but what's with the 1 in the
following (python2 on redhat 7.2):

>>> float(1./2)
0.5
>>> float(1./3)
0.33333333333333331
>>> float(.1/3)
0.033333333333333333

Isn't the last one correct?

Steve





From dsh8290@rit.edu  Sun Dec  2 01:16:24 2001
From: dsh8290@rit.edu (dman)
Date: Sat, 1 Dec 2001 20:16:24 -0500
Subject: [Tutor] Tutorials
In-Reply-To: <3C09120F.91E1F54E@my995internet.com>; from deliberatus@my995internet.com on Sat, Dec 01, 2001 at 12:23:27PM -0500
References: <3C09120F.91E1F54E@my995internet.com>
Message-ID: <20011201201624.A16707@harmony.cs.rit.edu>

On Sat, Dec 01, 2001 at 12:23:27PM -0500, Kirk Bailey wrote:
...
| I have GOT to hammer this thing into my concrete skull, or I am going to
| bloody EXPLODE from fustration. I KNOW what I want to do,. I can
| FLOWCHART it. 
| 
| But I can't CODE it. ARG.

So why not draw the flowchart and post it somewhere so people can help
you?  If you can iterate enough times the flowchart can become
detailed enough to be an abstract syntax tree, and then you're all set
:-).

-D

-- 

"...the word HACK is used as a verb to indicate a massive amount
of nerd-like effort."  -Harley Hahn, A Student's Guide to Unix



From urnerk@qwest.net  Sun Dec  2 01:17:40 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 01 Dec 2001 17:17:40 -0800
Subject: [Tutor] Need more precise digits
In-Reply-To: <1007252593.8525.0.camel@rama>
References: < <Pine.LNX.4.21.0112011606060.31870-100000@hkn.eecs.berkeley.edu>
 <Pine.LNX.4.21.0112011606060.31870-100000@hkn.eecs.berkeley.edu>
Message-ID: <4.2.0.58.20011201170919.00c1aec0@pop3.norton.antivirus>

>
> >>> float(1./2)
>0.5
> >>> float(1./3)
>0.33333333333333331
> >>> float(.1/3)
>0.033333333333333333
>
>Isn't the last one correct?
>
>Steve

Note:  it's reduntant to go float(1./2) as the decimal
point alone, after the numerator or the denominator,
is sufficient to make this a floating point operation.

  >>> .1/3
  0.033333333333333333

pushes the answer to the right by one decimal place,
so the trailing 1 drops off, but 0.33333333333333331 is
what binary math (vs. decimally based arithemetic)
really gives us -- i.e. this is all according to floating
point specifications.

Floating point numbers are not the same as real numbers.
They're actually "more real" in the sense of actually being
a part of the physical number crunching experience. No
one has ever multiplied pi x pi using a whole number based
positional representation without converting it from an
irrational to a rational number first.

Kirby



From dsh8290@rit.edu  Sun Dec  2 01:45:36 2001
From: dsh8290@rit.edu (dman)
Date: Sat, 1 Dec 2001 20:45:36 -0500
Subject: [Tutor] Need more precise digits
In-Reply-To: <1007252593.8525.0.camel@rama>; from sarnold@earthling.net on Sat, Dec 01, 2001 at 04:23:13PM -0800
References: <Pine.LNX.4.21.0112011606060.31870-100000@hkn.eecs.berkeley.edu> <1007252593.8525.0.camel@rama>
Message-ID: <20011201204536.B16707@harmony.cs.rit.edu>

On Sat, Dec 01, 2001 at 04:23:13PM -0800, Steve Arnold wrote:
 
| So either 1 or 2 needs to be a float; but what's with the 1 in the
| following (python2 on redhat 7.2):
| 
| >>> float(1./2)
| 0.5
| >>> float(1./3)
| 0.33333333333333331
| >>> float(.1/3)
| 0.033333333333333333
| 
| Isn't the last one correct?

They're all correct, to the given precision.  

>>> print "%.40f" % (1.0/3)
0.3333333333333333148296162562473909929395
>>> print "%.40f" % ( .1/3 )
0.0333333333333333328707404064061847748235
>>> 


floating point is completely accurate, but is limited (as any
representation is) to representing only certain numbers.  Any time it
is asked to represent a number that it can't, it uses the closes
approximation.  Be aware, though, that repetitive arithmatic compounds
the approximation and increases the "uncertainty" in the result.
(uncertainty is also created any time you measure something -- you can
never measure something 100% perfectly accurately and precisely).

For example :

>>> print "%.40f" % .1 
0.1000000000000000055511151231257827021182
>>> 
>>> i = 0
>>> for blah in xrange( 1000000 ) : i += .1
... 
>>> print "%.40f" % i
100000.0000013328826753422617912292480468750000
>>>
>>> print "%.40f" % ( .1 * 1000000 )
100000.0000000000000000000000000000000000000000
>>> 


this is one reason that range() doesn't allow float values for start,
stop, or increment.

-D

-- 

It took the computational power of three Commodore 64s to fly to the moon.
It takes at least a 486 to run Windows 95.
Something is wrong here.



From deliberatus@my995internet.com  Sun Dec  2 02:20:40 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sat, 01 Dec 2001 21:20:40 -0500
Subject: [Tutor] further ignorant babbling
Message-ID: <3C098FF8.C030F4E7@my995internet.com>

OK, newest and latest shot at looking like an idiot in front of my
betters.

---------------stubbling code attempt---------------
#!/usr/sbin/python
# preceeeding line must point to the python executable!
import strings
import mail
#
# define path information and domain name in the lines below
domainname = 'howlermonkey.net'
pathtosubscribers = '/www/www.howlermonkey.net/cgi-bin/lists'
#
# receive the incoming letter from <stdin>
incoming=raw_input()
#
# parse the letter into a dictionary
letter{}=Mail.parse(incoming)
#
# clip off preceeding and trailing whitespace chars if any
to=string.string(to)
#
# this next gives us the part after 'To:' and before '@'
to = string.string( letter, string.pos("@",3, 'to:'))
#
# ok, we now know the name of the list to referr to.
in.open(pathtosubscribers+to,'r')
# Dig, this tupple is the total subscriber file loaded,
# and is referred to with a index number!
subscribers = in
close in
# the subscriber list is now in the tupple 'in'
#
# note the 'from' field is LISTNAME.DOMAINNAME!
letter{'From:') = to + domainname
#
# append [listname] in FRONT of the existing subject.
X = '['+ to + ']' + letter{Subject:}
letter{subject:} = X
#
# open the footer file and read it into the variable footer
# then close it.
c = b.open(pathtostuff+footer,'r')
footer= raw_input(c)
close b
#
# append footer to the end of 'Body:' in dictionary 'letter'.
letter{'Body:'} = letter{'Body:'}+footer
#
#now send a seperate envlope and letter to each person in that
subscriber file
for i in subscribers():
	letter{'To:'}=subscribers[i]
	# This feeds a copy of the complete letter to sendmail
	# with To: coming from the tupple subscribers
	mail.send(letter{})

--------end of fumbling about--------------

ok, I know, it won't work, but it's improving.

General scheme of operation:

*It's a real list. This is because it came here from the alias file,
 so it must be a list you created, so we assume it exists and there
 is a subscriber file for it.

*We want FROM to point at the listname@domainname so they can reply to
it easily.

*The footer rile provides useful information for people using the list,
such as how to unsubscribe

	
Oh, and the library called, and said the interlibrary loan about python
just arrived, I will pick it up monday.	
	
-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/



From urnerk@qwest.net  Sun Dec  2 03:51:01 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 01 Dec 2001 19:51:01 -0800
Subject: [Tutor] Need more precise digits
In-Reply-To: <20011201204536.B16707@harmony.cs.rit.edu>
References: <1007252593.8525.0.camel@rama>
 <Pine.LNX.4.21.0112011606060.31870-100000@hkn.eecs.berkeley.edu>
 <1007252593.8525.0.camel@rama>
Message-ID: <4.2.0.58.20011201195017.00c3f5c0@pop3.norton.antivirus>

At 08:45 PM 12/1/2001 -0500, dman wrote:

>this is one reason that range() doesn't allow float values for start,
>stop, or increment.
>
>-D

... a trap I feel into very recently, with my lazyrange()
alternative (illustrating the generator feature).

Kirby



From dsh8290@rit.edu  Sun Dec  2 03:57:23 2001
From: dsh8290@rit.edu (dman)
Date: Sat, 1 Dec 2001 22:57:23 -0500
Subject: [Tutor] Need more precise digits
In-Reply-To: <4.2.0.58.20011201195017.00c3f5c0@pop3.norton.antivirus>; from urnerk@qwest.net on Sat, Dec 01, 2001 at 07:51:01PM -0800
References: <1007252593.8525.0.camel@rama> <Pine.LNX.4.21.0112011606060.31870-100000@hkn.eecs.berkeley.edu> <1007252593.8525.0.camel@rama> <20011201204536.B16707@harmony.cs.rit.edu> <4.2.0.58.20011201195017.00c3f5c0@pop3.norton.antivirus>
Message-ID: <20011201225723.B16876@harmony.cs.rit.edu>

On Sat, Dec 01, 2001 at 07:51:01PM -0800, Kirby Urner wrote:
| At 08:45 PM 12/1/2001 -0500, dman wrote:
| 
| >this is one reason that range() doesn't allow float values for start,
| >stop, or increment.
| >
| >-D
| 
| ... a trap I fell into very recently, with my lazyrange()
| alternative (illustrating the generator feature).

Yep, but you noticed it in time.  BTW, did you check the range's
terminating condition with == or >=?  Checking equality with floats is
bad because of the approximations that happen.  It is unlikely that,
after some arithmatic, a float will exactly equal what you want.  It
is better to check if it is equal with some epsilon (that is, close
enough to consider equal).  This applies in general, not just to your
lazyrange().

-D

-- 

Microsoft: "Windows NT 4.0 now has the same user-interface as Windows 95"
    Windows 95: "Press CTRL-ALT-DEL to reboot"
Windows NT 4.0: "Press CTRL-ALT-DEL to login"



From urnerk@qwest.net  Sun Dec  2 04:32:20 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 01 Dec 2001 20:32:20 -0800
Subject: [Tutor] further ignorant babbling
In-Reply-To: <3C098FF8.C030F4E7@my995internet.com>
Message-ID: <4.2.0.58.20011201195204.00c3fc80@pop3.norton.antivirus>

At 09:20 PM 12/1/2001 -0500, Kirk Bailey wrote:
>OK, newest and latest shot at looking like an idiot in
>front of my betters.

We're all idiots of one kind or another, not to worry.

># parse the letter into a dictionary
>letter{}=Mail.parse(incoming)
   ^^^^^^^

I'm not able to do a comprehensive debug of your pseudocode,
but want to point out that you're not quite getting dictionary
syntax.  Curly braces are never used in this subscript
position.

># clip off preceeding and trailing whitespace chars if any
>to=string.string(to)
>#

string doesn't have a 'string' method.  If 'to' is already
a string and you want to clip off any whitespace, the
function to use is string.strip().

Also, in recent Pythons, most string functions may be
invoked as methods against primitive string objects, without
importing the string module; in other words:

   >>> '  baaaa   '.strip()
   'baaaa'

># this next gives us the part after 'To:' and before '@'
>to = string.string( letter, string.pos("@",3, 'to:'))

If you're *sure* that "To:" and "@" will be in 'to', then
you can do it in one line with string methods:

   >>> to = "To:  joeblow@smallworld.com"
   >>> to
   'To:  joeblow@smallworld.com'

   >>> to[to.index("To:")+3:to.index("@")].strip()
   'joeblow'

(in this case, we're basically getting to[3:12] and
stripping off the leading spaces).  to.index("To:")
returns where "To:" begins in to (position 0).

>#
># ok, we now know the name of the list to referr to.
>in.open(pathtosubscribers+to,'r')

open(filename,'r') returns a file object to a variable.
This file object now has methods applied to it, such
as readlines().

So you probably want to go:

   in = open(whatever,'r')

'to' just contains the name of one email person, as per
your above example.  Does that person have his own file?

># Dig, this tupple is the total subscriber file loaded,
># and is referred to with a index number!
>subscribers = in

You might be wanting

   subscribers = in.readlines()

which will make a list containing every line in whatever
(the file opened above) as an element in the list.

>close in

in.close()

># the subscriber list is now in the tupple 'in'
>#

No, 'in' is now closed and done with.  We read the
subscriber list into 'subscribers' using in.readlines()
-- I think is what you're getting at.

># note the 'from' field is LISTNAME.DOMAINNAME!
>letter{'From:') = to + domainname

Again, illegal syntax.  If letter is a dictionary, you
key into it using square brackets.  Example:

    >>> mydict = {}  # empty dictionary
    >>> mydict['to'] = 'joeblow@mydomain.com'
    >>> mydict['subject'] = 'The end of the world'

... like that (showing it in shell mode, interactively
-- the best place to experiment with Python syntax
even as you write longer code in another window, to
test out whether you're getting it right).

>#
># append [listname] in FRONT of the existing subject.
>X = '['+ to + ']' + letter{Subject:}

Yeah, you can do something like this.  Remember to
insert '\n' strings where you want to code a line
break (newline).

>letter{subject:} = X

Confusing.  letter['subject'] should just be the subject,
no?  We don't want to stick the 'to' stuff in there too.

Can't we keep letter['to'], letter['subject'], letter['body']
and letter['footer'] all as separate entries until later?

# append footer to the end of 'Body:' in dictionary 'letter'.
>letter{'Body:'} = letter{'Body:'}+footer
>#

   body = open(somepath/file,'r')
   letter['body'] = body.readlines()
   body.close()

Except now letter['body'] keys to a list, not one long text
string.  If you need to convert a list of text lines into
one long string, with newlines between each line, you can
do something like this:

   >>> linelist = ['this is a line', 'this is another line']
   >>> letter = {}
   >>> letter['body'] = '\n'.join(linelist)
   >>> letter['body']
   'this is a line\nthis is another line'
   >>> print letter['body']
   this is a line
   this is another line

And:

   footer = raw_input('Enter footer:  ')
   letter['footer'] = footer

>#now send a seperate envlope and letter to each person in that
>subscriber file
>for i in subscribers():
>         letter{'To:'}=subscribers[i]
>         # This feeds a copy of the complete letter to sendmail
>         # with To: coming from the tupple subscribers
>         mail.send(letter{})

'subscribers' is a list, so you don't want to put () after it,
as if it were a function.  Your indexing i will become each
subscriber in turn, so just go letter('to') = i -- and when
you pass your letter to mail.send, just send 'letter' -- no
need for the {} tacked on (Python knows it's a dictionary).

This presumes mail.send is something *you* write.  If its
part of a Standard Library module named mail, then
mail.send(letter) will only work if send() expects a dictionary
with those specific entries.  Is that what's happening, or
was the idea of formatting a letter as a dictionary your
idea (not a bad one, by the way -- certainly workable)?

 > Oh, and the library called, and said the interlibrary
 > loan about python just arrived, I will pick it up monday.

You're doin' great.  The kind of program you're writing is
quite ambitious and wouldn't normally be tackled by a
beginner to *any* language (except maybe rebol).  That you
are willing to tackle such a thing is testament both to
Python's power, and your bravery as would-be snake charmer.

Kirby



From urnerk@qwest.net  Sun Dec  2 05:03:31 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 01 Dec 2001 21:03:31 -0800
Subject: [Tutor] Need more precise digits
In-Reply-To: <20011201225723.B16876@harmony.cs.rit.edu>
References: <4.2.0.58.20011201195017.00c3f5c0@pop3.norton.antivirus>
 <1007252593.8525.0.camel@rama>
 <Pine.LNX.4.21.0112011606060.31870-100000@hkn.eecs.berkeley.edu>
 <1007252593.8525.0.camel@rama>
 <20011201204536.B16707@harmony.cs.rit.edu>
 <4.2.0.58.20011201195017.00c3f5c0@pop3.norton.antivirus>
Message-ID: <4.2.0.58.20011201203547.00c3e660@pop3.norton.antivirus>

In tutor@python.org, "dman" <dsh8290@rit.edu> wrote:

>Checking equality with floats is bad because of the
>approximations that happen.

Oh so true.

    def lazyrange(start,stop,inc):
         if (start<stop and inc<0) or \
            (start>stop and inc>0):
            raise ValueError,"Illegal parameters"
         while start<stop:
            yield start
            start += inc
         return

Didn't have *that* problem at least.

By the way, another application of the generator feature
came up for me on another list recently.  I was chatting
with a community college prof about continued fractions,
which have the standard form:

            q0 +    1
                 --------
                  q1 +  1
                       ----
                        q2 + ....

Where q0, q1... are positive integers.  I had this recursive
way of doing it which amounted to a right to left evaluation,
but he showed me a way of going left to right.  That was cool,
because one thing I wanted to see was how some continued
fractions gradually converge to a key constant.  For example,
the simplest of all continued fractions is just:

            1  +    1
                 --------
                  1  +  1
                       ----
                        1 + ....

and so on.

The professor had written his algorithm for the TI calculator,
but I adapted with hardly any modifications to Python, and
now it looks like this:

     from __future__ import generators

     def conv(cf):
        """
        Generate partial fractions from partial quotients
        of a continued fraction, with thanks to:
        RWW Taylor
        National Technical Institute for the Deaf
        Rochester Institute of Technology
        Rochester NY 14623
        """
        cfsize = len(cf)
        n = [0 for i in range(cfsize+2)]  # all 0s
        d = n[:]                          # copy of n
        n[1] = d[0] = 1
        for i in range(cfsize):
          n[i+2] = n[i] + cf[i] * n[i + 1]
          d[i+2] = d[i] + cf[i] * d[i + 1]
          yield str(n[i])+"/"+str(d[i]) # interim result
        return

So if I feed this a list like [1,1,1,1,1,1,1,1,1,1,1,1,1],
it'll yield an approximation with each iteration, because
I wrote it as a generator.

For example:

  >>> genphi = conv([1,1,1,1,1,1,1,1,1,1,1,1,1])
  >>> for fraction in genphi: print fraction

  0/1
  1/0
  1/1
  2/1
  3/2
  5/3
  8/5
  13/8
  21/13
  34/21
  55/34
  89/55
  144/89

Of course a 'print' statement in place of yield would accomplish
the same thing in this context (that's what a yield is like,
a print).  But I can imagine an application where I'd want
to return the partial fraction, then maybe ask for more
precision later on, and conv() would be there, ready to pick
up right where it left off.

I've written class definitions like this for square roots --
you ask for 30 digits of precision, then come back later and
ask for 100 digits, and it doesn't have to start over from
the beginning, just goes out from 30, and so on.

BTW, as some might already know, the constant we're
approaching with this simplest of continued fractions is
phi = (sqrt(5)+1)/2 = golden ratio = approx.
1.6180339887498949

   >>> 144/89.
   1.6179775280898876

Not so close yet.  But let's go out to 50 iterations:

   >>> genphi = conv([1 for i in range(50)])
   >>> for fraction in genphi:  result = fraction

   >>> result
   '7778742049/4807526976'
   >>> 7778742049/4807526976.
   1.6180339887498949

Better.

This is where we could write a loop that continues until the
difference between the fraction and the floating point goes
below some very small value, like 1E-12.  Just modify conv()
to never stop on its own, and keep looping until you hit the
break condition, which should *not* involve an ==, for the
reason you mention.

Kirby



From deliberatus@my995internet.com  Sun Dec  2 07:25:26 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sun, 02 Dec 2001 02:25:26 -0500
Subject: [Tutor] other languages
Message-ID: <3C09D766.85959103@my995internet.com>

I like the extensibility of python. I see you can evern write your own
modules and have them available as optional extensions for use at need,
which I like. Reminds me of a fun thing, a strange state of mind, or
state of computer, called FORTH.



Ah, forth. A top down bottom up compiling interpeting language, stack
oriented, and using reverse polish notation, infinately exensible, with
all possible and not yet existing asembly language as a subset of the
language.

Sheesh.

Helloworld in forth:

:helloworld ."Hello world!" ;

By the time your mind registered the movement of the cursor, it was
finished. IT IS NOW PART OF *YOUR* FORTH.

now add to it:
:better CLR 3 do[helloworld];

$better
Helloworld!
Helloworld!
Helloworld!
OK
_

OK means it finished executing with no problems, and is waiting for a
command. _ is the cursor.

That 'program' is A WORD, and is used in the definition of other words.
It has to exist before it can be used in other words, so this is bottom
up. But we conceive and write top down, from most general to most
specific, so we use the editor to write the source file FROM THE BOTTOM
OF THE FILE, with the most general definitions, and above them
sucessively define more and more detailed specific functions. Then we
compile. Doint it interactive mode is a little hairyier. 

Leo Brodie wrote (Thinking Forth? [He wrote severalbooks on it, is one
of the prime suspects responsible for the language]) in one of his books
that it is so different that beginners pick it up much easier than
experienced programmers. Experienced programmers tend to go a little
banannas trying to grok forth. It is agglutinative, like Hawaiian or
German.

As an example, the German word for glove is translated in it's parts as
'hand & shoe'. Hawaiian is much easier to pronounce, and has a very
useful body of metaphors in it in their system of mysticism- HUNA. As
all programs are in fact new WORDS, and are defined in terms of
primitives and other existing WORDS, there are words of power.
Primitives are written in assembler- elements or 'spirits'. Were I to
write forth in hawaiian I would call it HUNA (after the Hawaiian system
of mysticism) and a master of it a Kahuna. As could then have fun with
all the bits about places of power, elements and spirits, words of
power, kahunas, the great kahuna, etc. But I digresss from the subject
of PYTHON.

A search at yahoo would prove fruitful for those wishing to read about
or play with forth. there is a compiler versionout there with integrated
devlopment environment. Turns out NICE TIGHT code- I used it to write a
hello world, free standing. 453 bytes.

Microsoft C took 47K. Someone slap bill gates around with a largemouth
Bass.

Will slack off for sunday and do errands, get book from library monday.
Expect more rom me monday night. 

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From cow@esweeet.com  Sun Dec  2 07:47:32 2001
From: cow@esweeet.com (Cow)
Date: Sat, 1 Dec 2001 23:47:32 -0800 (PST)
Subject: [Tutor] Bookmarks
Message-ID: <20011202074732.EEC4E36F9@sitemail.everyone.net>

I know in VB, you can make bookmarks such as:

goto Cat

msgbox "bla bla"

Cat:
msgbox "You are at Cat"

and it will go to the "Cat" bookmark and perform the commands...
how can you do that in Python?

thanks a lot!
-Ryan

_____________________________________________________________
Free eSweeet Mail - http://www.esweeet.com


From scarblac@pino.selwerd.nl  Sun Dec  2 08:53:43 2001
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Sun, 2 Dec 2001 09:53:43 +0100
Subject: [Tutor] Bookmarks
In-Reply-To: <20011202074732.EEC4E36F9@sitemail.everyone.net>; from cow@esweeet.com on Sat, Dec 01, 2001 at 11:47:32PM -0800
References: <20011202074732.EEC4E36F9@sitemail.everyone.net>
Message-ID: <20011202095343.A23786@pino.selwerd.nl>

On  0, Cow <cow@esweeet.com> wrote:
> I know in VB, you can make bookmarks such as:
> 
> goto Cat
> 
> msgbox "bla bla"
> 
> Cat:
> msgbox "You are at Cat"
> 
> and it will go to the "Cat" bookmark and perform the commands...

There is a problem with this construct. What will VB do *after* the commands
at the label Cat? It doesnn't go back to the command after the goto statement.

So the programs "jumps around" in a way that's hard to read - you can't see
at one glance that now it does that, then it does that, then it does that.

This sort of thing is why the goto statement is usually frowned upon in
programming languages - the classical text is from Edsger Dijkstra, called
"Go To statement considered harmful", from 1968 (!). Nothing is new in
programming :). Although it has been argued that there are situations in
which goto can be the right way to program something, Python is much too
clean to have the command.

> how can you do that in Python?

You put the commands in a function.


Like:

def cat_messagebox():
   # There is no function 'message_box' without some preparation,
   # this is just an example.
   message_box("This is the function cat_messagebox.")
 

Now you can call cat_messagebox() from other places in your program - and
after doing it's thing, the program will always return to the command after
the function. This gives your program more structure.


(The paper is at <http://www.acm.org/classics/oct95/>)
-- 
Remco Gerlich


From tim.one@home.com  Sun Dec  2 09:57:49 2001
From: tim.one@home.com (Tim Peters)
Date: Sun, 2 Dec 2001 04:57:49 -0500
Subject: [Tutor] Need more precise digits
In-Reply-To: <4.2.0.58.20011201203547.00c3e660@pop3.norton.antivirus>
Message-ID: <LNBBLJKPBEHFEDALKOLCAEGAMKAA.tim.one@home.com>

[Kirby Urner]
> ...
> By the way, another application of the generator feature
> came up for me on another list recently.  I was chatting
> with a community college prof about continued fractions,
> which have the standard form:
>
>             q0 +    1
>                  --------
>                   q1 +  1
>                        ----
>                         q2 + ....
>
> Where q0, q1... are positive integers.  I had this recursive
> way of doing it which amounted to a right to left evaluation,
> but he showed me a way of going left to right.  That was cool,
> because one thing I wanted to see was how some continued
> fractions gradually converge to a key constant.  For example,
> the simplest of all continued fractions is just:
>
>             1  +    1
>                  --------
>                   1  +  1
>                        ----
>                         1 + ....
>
> and so on.

Note that the numerators and denominators of the convergents to this are the
Fibonacci numbers; that is, this:

> ...
>   1/1
>   2/1
>   3/2
>   5/3
>   8/5
>   13/8
>   21/13
> ...

should look familiar <wink>.

> The professor had written his algorithm for the TI calculator,
> but I adapted with hardly any modifications to Python, and
> now it looks like this:
>
>      from __future__ import generators
>
>      def conv(cf):
>         """
>         Generate partial fractions from partial quotients
>         of a continued fraction, with thanks to:
>         RWW Taylor
>         National Technical Institute for the Deaf
>         Rochester Institute of Technology
>         Rochester NY 14623
>         """
>         cfsize = len(cf)
>         n = [0 for i in range(cfsize+2)]  # all 0s

Simpler as

        n = [0] * (cfsize + 2)

but, as shown later, you don't need a list here at all.

>         d = n[:]                          # copy of n
>         n[1] = d[0] = 1
>         for i in range(cfsize):
>           n[i+2] = n[i] + cf[i] * n[i + 1]
>           d[i+2] = d[i] + cf[i] * d[i + 1]
>           yield str(n[i])+"/"+str(d[i]) # interim result

Consider the last iteration of the loop:  the n[i+2]/d[i+2] and
n[i+1]/d[i+1] convergents are computed but never returned (when
i==len(cfsize)-1).

>         return

Not needed -- "falling off the end" of a generator is the same as a
"return".

> So if I feed this a list like [1,1,1,1,1,1,1,1,1,1,1,1,1],

Easier written as [1]*13 (see the similar trick with [0] above).

> it'll yield an approximation with each iteration, because
> I wrote it as a generator.

However, because you compute len(cf) at the start, cf can't *itself* be a
generator.  It's more flexible (and the code gets simpler!) if you let cf be
any iterable object.  For example, then you could feed it this:

def ones():
    while 1:
        yield 1

That is, an unbounded sequence of ones.

> For example:
>
>   >>> genphi = conv([1,1,1,1,1,1,1,1,1,1,1,1,1])
>   >>> for fraction in genphi: print fraction
>
>   0/1
>   1/0
>   1/1
>   2/1
>   3/2
>   5/3
>   8/5
>   13/8
>   21/13
>   34/21
>   55/34
>   89/55
>   144/89
>
> Of course a 'print' statement in place of yield would accomplish
> the same thing in this context (that's what a yield is like,
> a print).  But I can imagine an application where I'd want
> to return the partial fraction, then maybe ask for more
> precision later on, and conv() would be there, ready to pick
> up right where it left off.

Yes indeed!  There are many applications for this, although it's hard to
give an obvious example <wink>.

Here's an alternative that accepts any iterable object (incl. a generator,
if you like) as argument, generates all the convergents (including the last
two), and doesn't use any internal lists:

from __future__ import generators, division

# Generate continued-fraction pairs (num, den) from a sequence of
# partial quotients.

def conv(pqs):
    x0, y0 = 0, 1  # zero
    x1, y1 = 1, 0  # infinity
    yield x0, y0
    yield x1, y1
    for q in pqs:
        x0, y0, x1, y1 = x1, y1, x0 + q*x1, y0 + q*y1
        yield x1, y1

import math
x = (1 + math.sqrt(5))/2

for n, d in conv([1] * 50):
    approx = n/(d or 1e-300)
    print "%d/%d ~= %.17g %.17g" % (n, d, approx, x - approx)

> ...
> This is where we could write a loop that continues until the
> difference between the fraction and the floating point goes
> below some very small value, like 1E-12.  Just modify conv()
> to never stop on its own, and keep looping until you hit the
> break condition, which should *not* involve an ==, for the
> reason you mention.

Continued fractions are lovely.  One of the things you can prove is that
successive convergents are alternately larger and smaller than the true
value (e.g., 0/1 < phi, 1/0 > phi, 1/1 < phi, 2/1 > phi, <, >, <, >, ...).
Another is that if p/q and r/s are successive convergents, then abs(p/q -
r/s) == 1/(q*s) (e.g., 13/8-21/13 == (13*13-21*8)/(8*13) == 1/(8*13)).
Together, those imply that the true value is within 1/(q*s) of both
convergents.  A weaker but more useful relation is that, since the
denominators increase once the sequence gets going, the convergent following
p/q has a denominator at least as large as q, so the "1/(q*s)" is no larger
than 1/q**2.  IOW, once you get beyond the trivial convergents at the start,
any particular convergent p/q is within 1/q**2 of the true value.  This can
be used to determine a stopping point good to a given level of accuracy even
when you don't know the true value in advance.

One other factoid of use:  if p/q is a convergent to a real number x, p/q is
the best rational approximation to x among all rationals with denominator no
greater than q -- although, as usual with continued fraction, that really
needs some weasle words to exempt the trivial 0/1 and 1/0 convergents at the
start.

more-fun-than-apple-pi-ly y'rs  - tim



From glingl@aon.at  Sun Dec  2 16:59:24 2001
From: glingl@aon.at (Gregor Lingl)
Date: Sun, 2 Dec 2001 17:59:24 +0100
Subject: [Tutor] Division
Message-ID: <00aa01c17b52$b1da1a00$1664a8c0@mega>

This is a multi-part message in MIME format.

------=_NextPart_000_00A7_01C17B5B.13645F30
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hi!

As I'm starting to give a new course 'Introduction to
programming' in Jan 2002. It's for young students in the
age of 15/16. (Of course) I shall use Python.
I'd consider it an advantage not to confuse my students
in the beginning with the specialities the overlaoding of=20
the division-operator (although I had to do so for several times
until now). But neither with the import from future
statement.

So my question is: Is there a way to start the Python-Interpreter
with new division enabled, so one needs not to write=20
'from __future__ import division' at the beginning of every program
file which uses division (using some switch, editing some startup=20
file or similar)?

Although this is not an issue of major importance, I'm curious about
it.

Thanks in advance
Gregor
=20


------=_NextPart_000_00A7_01C17B5B.13645F30
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=3D"Courier New" size=3D2>Hi!</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>As I'm starting to give a new =
course=20
'Introduction to</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>programming' in Jan 2002. It's =
for young=20
students in the</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>age of 15/16. (Of course) I =
shall=20
use&nbsp;Python.</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>I'd consider it an advantage =
not to confuse=20
my students</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>in the beginning with the =
specialities the=20
overlaoding of </FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>the division-operator (although =
I had to do=20
so&nbsp;for several times</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>until now). But neither with =
the import=20
from future</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>statement.</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>So my question is: Is there a =
way to start=20
the Python-Interpreter</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>with new division enabled, so =
one needs not=20
to write </FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>'from __future__ import =
division' at the=20
beginning of every program</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>file which uses division (using =
some=20
switch, editing some startup </FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>file or similar)?</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>Although this is not an issue =
of major=20
importance, I'm curious about</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>it.</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" size=3D2>Thanks in advance</FONT></DIV>
<DIV><FONT face=3D"Courier New" size=3D2>Gregor</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3D"Courier New" =
size=3D2></FONT>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_00A7_01C17B5B.13645F30--



From tim.one@home.com  Sun Dec  2 19:10:16 2001
From: tim.one@home.com (Tim Peters)
Date: Sun, 2 Dec 2001 14:10:16 -0500
Subject: [Tutor] Division
In-Reply-To: <00aa01c17b52$b1da1a00$1664a8c0@mega>
Message-ID: <LNBBLJKPBEHFEDALKOLCEEHBMKAA.tim.one@home.com>

[Gregor Lingl]
> As I'm starting to give a new course 'Introduction to
> programming' in Jan 2002. It's for young students in the
> age of 15/16. (Of course) I shall use Python.
> I'd consider it an advantage not to confuse my students
> in the beginning with the specialities the overlaoding of 
> the division-operator (although I had to do so for several times
> until now). But neither with the import from future
> statement.
>
> So my question is: Is there a way to start the Python-Interpreter
> with new division enabled, so one needs not to write 
> 'from __future__ import division' at the beginning of every program
> file which uses division (using some switch, editing some startup 
> file or similar)?

Skip down to the "Command Line Option" section of PEP 238:

    http://python.sf.net/peps/pep-0238.html

As it says,

    The "new" option is only intended for use in certain educational
    environments, where true division is required, but asking the
    students to include the future division statement in all their
    code would be a problem.

C:\Code\python\PCbuild>python -Qnew
Python 2.2b2+ (#26, Nov 28 2001, 19:17:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 1/2
0.5
>>> 1//2
0
>>>


From fleet@teachout.org  Sun Dec  2 20:15:16 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Sun, 2 Dec 2001 15:15:16 -0500 (EST)
Subject: [Tutor] class again
Message-ID: <Pine.LNX.4.33.0112021509080.14740-100000@fleet1.paxp.com>

I have followed the example in Core Python Programming (pg 403) re;
AddrBookEntry class.  If I type it in at the interactive Python prompt
everything works fine.  When I try to put the class in a file
(addrbook.py) and 'import addrbook' I get no complaints; but I can't
instantiate the class.  (Ie, john = AddrBookEntry('John Doe',
'405-555-1212'). I get NameError: AddrBookEntry.

Where did I fall off the track?

Thanks,
				- fleet -

So you don't have to look it up, here's the class:

class AddrBookEntry:
   'address book entry class'
   def __init__(self, nm, ph):
      self.name = nm
      self.phone = ph
      print 'Created instance for:', self.name

   def updatePhone(self, newph):
      self.phone = newph
      print 'Updated phone# for:', self.name





From scarblac@pino.selwerd.nl  Sun Dec  2 20:19:34 2001
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Sun, 2 Dec 2001 21:19:34 +0100
Subject: [Tutor] class again
In-Reply-To: <Pine.LNX.4.33.0112021509080.14740-100000@fleet1.paxp.com>; from fleet@teachout.org on Sun, Dec 02, 2001 at 03:15:16PM -0500
References: <Pine.LNX.4.33.0112021509080.14740-100000@fleet1.paxp.com>
Message-ID: <20011202211934.A24869@pino.selwerd.nl>

On  0, fleet@teachout.org wrote:
> I have followed the example in Core Python Programming (pg 403) re;
> AddrBookEntry class.  If I type it in at the interactive Python prompt
> everything works fine.  When I try to put the class in a file
> (addrbook.py) and 'import addrbook' I get no complaints; but I can't
> instantiate the class.  (Ie, john = AddrBookEntry('John Doe',
> '405-555-1212'). I get NameError: AddrBookEntry.
> 
> Where did I fall off the track?

After you do 'import addrbook', you can access the module addrbook.

AddBookEntry is a class inside that module, so you have to instantiate it like

john = addrbook.AddrBookEntry(.....)

-- 
Remco Gerlich


From fleet@teachout.org  Sun Dec  2 20:45:07 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Sun, 2 Dec 2001 15:45:07 -0500 (EST)
Subject: [Tutor] RE: class again
Message-ID: <Pine.LNX.4.33.0112021519310.14744-100000@fleet1.paxp.com>

Why can't these blinding flashes of instant knowledge occur *BEFORE* one
hits the send button.  I had simply failed to precede the class name with
the module name.  john = addrbook.AddrBookEntry('John Doe',
'405-555-1212') works just fine.

However, I do have a class question:

Somewhere (in Core Python Programming) I recall seeing something that
implied data in a class was not preserved in lists or dictionaries. I
don't think I understand this.  In the address book example; where would
the information about "john" be stored for later retrieval if not in a
dictionary (or at least a flat file database).?

(I can't seem to find this reference now; but then, I haven't hit the send
key yet!)

				- fleet -



From dsh8290@rit.edu  Sun Dec  2 21:04:41 2001
From: dsh8290@rit.edu (dman)
Date: Sun, 2 Dec 2001 16:04:41 -0500
Subject: [Tutor] Need more precise digits
In-Reply-To: <LNBBLJKPBEHFEDALKOLCAEGAMKAA.tim.one@home.com>; from tim.one@home.com on Sun, Dec 02, 2001 at 04:57:49AM -0500
References: <4.2.0.58.20011201203547.00c3e660@pop3.norton.antivirus> <LNBBLJKPBEHFEDALKOLCAEGAMKAA.tim.one@home.com>
Message-ID: <20011202160441.A17536@harmony.cs.rit.edu>

On Sun, Dec 02, 2001 at 04:57:49AM -0500, Tim Peters wrote:
| [Kirby Urner]
| > ...
| > By the way, another application of the generator feature
| > came up for me on another list recently.  I was chatting
| > with a community college prof about continued fractions,
| > which have the standard form:
...
| Note that the numerators and denominators of the convergents to this are the
| Fibonacci numbers; that is, this:

Interesting stuff here :-).  I've never seen continued fractions
before (SE majors don't need any math beyond Calc 3, Discrete 2,
Prob & Stat 1, and Diff. Eq.).  I've also never seen the Fibonacci
numbers except in CS examples.  This is the first time I've seen them
applied somewhere.

-D

-- 

Failure is not an option.  It is bundled with the software.



From dyoo@hkn.eecs.berkeley.edu  Sun Dec  2 21:18:10 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 2 Dec 2001 13:18:10 -0800 (PST)
Subject: [Tutor] RE: class again
In-Reply-To: <Pine.LNX.4.33.0112021519310.14744-100000@fleet1.paxp.com>
Message-ID: <Pine.LNX.4.21.0112021312310.19586-100000@hkn.eecs.berkeley.edu>

On Sun, 2 Dec 2001 fleet@teachout.org wrote:

> Why can't these blinding flashes of instant knowledge occur *BEFORE* one
> hits the send button.  I had simply failed to precede the class name with
> the module name.  john = addrbook.AddrBookEntry('John Doe',
> '405-555-1212') works just fine.

No problem.  This happens to me all the time.  *grin* I think it's the
same sort of effect that Gregor noticed: the act of asking a question
usually jogs the mental gears enough to start rolling again.


> Somewhere (in Core Python Programming) I recall seeing something that
> implied data in a class was not preserved in lists or dictionaries. I
> don't think I understand this.  In the address book example; where
> would the information about "john" be stored for later retrieval if
> not in a dictionary (or at least a flat file database).?

Hmmm... if you can give a page number, we can check up on that.  I finally
have a copy of Wesley's Core Python Programming book.  (Thanks Wes!)

I'm not familiar with the term "implied data" though; can someone clarify?


Good luck to you!



From tim.one@home.com  Sun Dec  2 21:35:13 2001
From: tim.one@home.com (Tim Peters)
Date: Sun, 2 Dec 2001 16:35:13 -0500
Subject: [Tutor] Need more precise digits
In-Reply-To: <20011202160441.A17536@harmony.cs.rit.edu>
Message-ID: <LNBBLJKPBEHFEDALKOLCMEHKMKAA.tim.one@home.com>

[dman]
> Interesting stuff here :-).  I've never seen continued fractions
> before (SE majors don't need any math beyond Calc 3, Discrete 2,
> Prob & Stat 1, and Diff. Eq.).  I've also never seen the Fibonacci
> numbers except in CS examples.  This is the first time I've seen them
> applied somewhere.

Whether you're required to or not <wink>, you should pick up "Concrete
Mathematics", by Knuth, Graham and Patashnik.  It's a wonderful intro to the
particular areas of discrete math of most use in Comp Sci.  Some of it is
hard going, but you'll quickly learn to skim over those parts ...

The Fibonacci numbers have a surprising connection to Euclid's GCD (greatest
common divisor) algorithm:  it turns out that pairs of successive Fibonacci
numbers are the worst cases for that algorithm, and, in fact, that in turn
"is because" every partial quotient in the continued fraction expansion of
phi is 1.  How is all this connected?  Read the book <wink>.



From fleet@teachout.org  Sun Dec  2 21:33:43 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Sun, 2 Dec 2001 16:33:43 -0500 (EST)
Subject: [Tutor] RE: class again
In-Reply-To: <Pine.LNX.4.21.0112021312310.19586-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.33.0112021632500.14852-100000@fleet1.paxp.com>

On Sun, 2 Dec 2001, Danny Yoo wrote:

> > Somewhere (in Core Python Programming) I recall seeing something that
> > implied data in a class was not preserved in lists or dictionaries. I
> > don't think I understand this.  In the address book example; where
> > would the information about "john" be stored for later retrieval if
> > not in a dictionary (or at least a flat file database).?
>
> Hmmm... if you can give a page number, we can check up on that.  I finally
> have a copy of Wesley's Core Python Programming book.  (Thanks Wes!)
>
> I'm not familiar with the term "implied data" though; can someone clarify?

Replace "implied" with "hinted" - it's a verb not an adjective. :) (And
I'm still looking!)

				- fleet -



From lha2@columbia.edu  Sun Dec  2 21:55:48 2001
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Sun, 02 Dec 2001 16:55:48 -0500
Subject: [Fwd: Re: [Tutor] Need more precise digits]
Message-ID: <3C0AA364.2769774C@mail.verizon.net>

I'll get a hang of this replying thing one of these days.

-------- Original Message --------
From: Lloyd Hugh Allen <vze2f978@mail.verizon.net>
Subject: Re: [Tutor] Need more precise digits
To: dman <dsh8290@rit.edu>

dman wrote:
> 
> On Sun, Dec 02, 2001 at 04:57:49AM -0500, Tim Peters wrote:
> | [Kirby Urner]
> | > ...
> | > By the way, another application of the generator feature
> | > came up for me on another list recently.  I was chatting
> | > with a community college prof about continued fractions,
> | > which have the standard form:
> ...
> | Note that the numerators and denominators of the convergents to this are the
> | Fibonacci numbers; that is, this:
> 
> Interesting stuff here :-).  I've never seen continued fractions
> before (SE majors don't need any math beyond Calc 3, Discrete 2,
> Prob & Stat 1, and Diff. Eq.).  I've also never seen the Fibonacci
> numbers except in CS examples.  This is the first time I've seen them
> applied somewhere.

That's ironic, that you hadn't seen continued fractions: as a mathie, I
had them in "Combinatorial Number Theory", which was described as
Computer Science without Computers (except that by the time that I took
it, comfort with Mathematica, and weekly meditation with Mathematica,
were requisite). (I still remember when the Academic Computing people
got really mad at our section the weekend that we were supposed to sieve
for all of the primes <= 10**6, and brought one of the servers to a
screeching halt with our poor algorithms--I think mine did a bunch of
comparisons of two or three lists with 10**5 or 10**6 elements to start
with, but then got more efficient).


From jrm@videotron.ca  Sun Dec  2 15:01:43 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Sun, 2 Dec 2001 17:01:43 +0200
Subject: [Tutor] "from this import *" or "import this"
Message-ID: <000d01c17b42$41855680$0100c0a8@videotron.ca>

    Be ready for a whole lot of very newbie questions. I've never programmed
before and do not intend to make a career out of what I am learning : pure
amateurism here which does not necessarily implies triviality but that
shouldn't be a surprise.

    So :
        is there a real use for the form "from this_module import * " since
                (a) there seems to be a real danger to get some functions or
variables which would have the same name if more than one module are open
that way
                (b) nothing shows the relation to the module which is to
some extent documenting the program
                (c) it imports the whole module (I guess) just as "import
this_module" seems to be doing
        ?
        Or is it much safer and wiser to avoid using it ?

        Thanks

       Jean M.






From dyoo@hkn.eecs.berkeley.edu  Sun Dec  2 21:58:14 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 2 Dec 2001 13:58:14 -0800 (PST)
Subject: [Tutor] further ignorant babbling
In-Reply-To: <3C098FF8.C030F4E7@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112021330250.19586-100000@hkn.eecs.berkeley.edu>

On Sat, 1 Dec 2001, Kirk Bailey wrote:

> import strings

This might be a typo: you probably mean "import string" instead.



> import mail
> #
> # define path information and domain name in the lines below
> domainname = 'howlermonkey.net'
> pathtosubscribers = '/www/www.howlermonkey.net/cgi-bin/lists'
> #
> # receive the incoming letter from <stdin>
> incoming=raw_input()
> #
> # parse the letter into a dictionary
> letter{}=Mail.parse(incoming)

Python is "dynamically typed", so you don't need to tell Python that
"letter" will be a dictionary.  If 'Mail.parse(incoming)' returns a
dictionary, then:

    letter = Mail.parse(incoming)

should be enough.  Be careful!  'Mail' is uppercased here, but your import
uses a lowercased 'mail'.  I'm not sure which one is right, but you'll
need to check this.



> # clip off preceeding and trailing whitespace chars if any
> to=string.string(to)

You probably mean:

    to = string.strip(to)


There's some documentation on the 'string' module here:

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



> # this next gives us the part after 'To:' and before '@'
> to = string.string( letter, string.pos("@",3, 'to:'))


Hmmm... You might want to write this as a separate function, because it
does seem like a useful thing to have.  Here's an example function that
knows how to strip the domain out of an email address:

###
def stripDomain(email):
    end = string.find(email, '@')
    return email[:end]
###

Once we have a function like this, we can use it as if it were part of
Python itself:

###
>>> stripDomain("deliberatus@my995internet.com")
'deliberatus'
###

Functions are often fun to write: by writing functions, we can expand the
number of "verbs" we can use in our programs.



From fleet@teachout.org  Sun Dec  2 22:04:00 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Sun, 2 Dec 2001 17:04:00 -0500 (EST)
Subject: [Tutor] class data
Message-ID: <Pine.LNX.4.33.0112021646300.14857-100000@fleet1.paxp.com>

Ok.  I found the reference I was talking about (that implies the data
contained in classes are not stored in dictionaries or "standard" type
containers).  Python Core Programming, pg 412, about half way down (under
the "def" and "class" examples) and continuing through the first paragraph
on the next page.  For those that don't have the book, here's the excerpt:

   "The fact that such a declaration is "larger" than a standard type
declaration should be proof that classes in Python are much more than
standard types.  (Note: I don't understand this statement at all.) A class
is like a Python container type on steroids.  Not only can it hold
multiple data items but it can also support its own set of functions,
which we have seen before, called methods.  You may be asking what other
advantages classes have over standard container types such as lists and
dictionaries.

   Standard types are fixed, cannot be customized, and come with a
hard-coded set of attributes.  Data types also do not provide individual
namespaces for objects nor can they be used to derive "sub-types."
Objects contained in lists are unrelated except for the name of their
container.  Its members are accessed only via an index offset into an
array-like data structure.  All lists have a common set of methods and
provide key access to their members (who are also unrelated except for
their container name).

   In this section, we will take a close look at classes and what types of
attributes they have.  Just remember to keep in mind that even though
classes are objects (everything in Python is an object), they are not
realizations of the objects they are defining. We will look at instances
in the next chapter, so stay tuned for that.  For now, the limelight is
strictly beamed on class objects.

   When you create a class, you are practically creating your own kind of
data entity.  All instances of that class are similar, but classes differ
from each other (and so will instances of different classes by nature).
Rather than playing with toys that come from the manufacturer and were
bestowed upon you as gifts, why not design and build your own toys to play
with?"

So if class data is not stored in standard containers, where is it stored
(and how)?  (I'm talking about the names, phone numbers, e-mail addresses,
etc. in the AddrBookEntry class example.)

				- fleet -



From pobrien@orbtech.com  Sun Dec  2 22:13:24 2001
From: pobrien@orbtech.com (Patrick K. O'Brien)
Date: Sun, 2 Dec 2001 16:13:24 -0600
Subject: [Tutor] "from this import *" or "import this"
In-Reply-To: <000d01c17b42$41855680$0100c0a8@videotron.ca>
Message-ID: <NBBBIOJPGKJEKIECEMCBIEGDLEAA.pobrien@orbtech.com>

You have a perfectly good grasp on the situation. Avoid import * for all the
reasons you cite, unless you don't really have a choice. For example, the
wxPython gui toolkit pretty much requires you to do "from wxPython.wx import
*". The good thing is that the wxPython folks are fully aware of the issues
and do what they can to minimize problems. One example is that all
wx-related things are prefixed with "wx" to avoid naming conflicts.

---
Patrick K. O'Brien
Orbtech.com - Your Source For Python Development Services


> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Jean Montambeault
> Sent: Sunday, December 02, 2001 9:02 AM
> To: tutor@python.org
> Subject: [Tutor] "from this import *" or "import this"
>
>
>     Be ready for a whole lot of very newbie questions. I've never
> programmed
> before and do not intend to make a career out of what I am learning : pure
> amateurism here which does not necessarily implies triviality but that
> shouldn't be a surprise.
>
>     So :
>         is there a real use for the form "from this_module import
> * " since
>                 (a) there seems to be a real danger to get some
> functions or
> variables which would have the same name if more than one module are open
> that way
>                 (b) nothing shows the relation to the module which is to
> some extent documenting the program
>                 (c) it imports the whole module (I guess) just as "import
> this_module" seems to be doing
>         ?
>         Or is it much safer and wiser to avoid using it ?
>
>         Thanks
>
>        Jean M.
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



From dyoo@hkn.eecs.berkeley.edu  Sun Dec  2 22:06:54 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 2 Dec 2001 14:06:54 -0800 (PST)
Subject: [Tutor] "from this import *" or "import this"
In-Reply-To: <000d01c17b42$41855680$0100c0a8@videotron.ca>
Message-ID: <Pine.LNX.4.21.0112021358490.19586-100000@hkn.eecs.berkeley.edu>

On Sun, 2 Dec 2001, Jean Montambeault wrote:

>     Be ready for a whole lot of very newbie questions. I've never
> programmed before and do not intend to make a career out of what I am
> learning : pure amateurism here which does not necessarily implies
> triviality but that shouldn't be a surprise.

Very true.  Welcome aboard!


>         is there a real use for the form "from this_module import * "
> since

>         (a) there seems to be a real danger to get some functions or
> variables which would have the same name if more than one module are
> open that way
>                 (b) nothing shows the relation to the module which is to
> some extent documenting the program
>                 (c) it imports the whole module (I guess) just as "import
> this_module" seems to be doing


Yes; you've just listed all the reasons why 'from this_module import *' is
heavily frowned upon.  *grin*  Good observations.



>         Or is it much safer and wiser to avoid using it ?

It's usually safer to avoid it.  It's convenient because one doesn't need
to type in the module name, so there's less typing.  On the other hand,
there are all those disadvantages that you've listed.

There are special situations where it's useful, particularly in Tkinter
GUI programming.  In that case, the designers of Tkinter kept as a design
goal that 'from Tkinter import *" should be safe.  In general, though,
'from this_module import *' is not a good idea.



From i812@iname.com  Sun Dec  2 22:18:27 2001
From: i812@iname.com (Rob McGee)
Date: Sun, 2 Dec 2001 16:18:27 -0600
Subject: [Tutor] destroying classes
Message-ID: <20011202161827.G27400@hal>

First some amusement:
{fun}
On Sat, Dec 01, 2001 at 08:32:20PM -0800, Kirby Urner wrote about
    "Re: [Tutor] further ignorant babbling":
> At 09:20 PM 12/1/2001 -0500, Kirk Bailey wrote:
> >OK, newest and latest shot at looking like an idiot in
> >front of my betters.
> 
> We're all idiots of one kind or another, not to worry.

Kirk wasn't saying we're "better" than him. It was just a typo. He meant
to say "bettors". See, a bunch of us were making some wagers on the side
about when Kirk would finish his program. :)

So okay everybody, listen up: the bets are off. Somebody must have told
Kirk about the pool. All bets will be returned to bettors -- of course
the house will retain its 10% cut. :)
{/fun}

But I don't want to waste bandwidth on a list this busy with pure
silliness, so I have some questions. You may recall my "class struggle"
thread from a couple of days ago. All is going quite well in that
project, and class namespaces are making the result much better than its
classless predecessor.

Anyway, one of my classes has a method which should result in the
destruction of the class instance. But the method also wants to return a
value. If I put a "del self" command in there, would the method end at
that point, or would it continue to completion?

{code}
class InSession:
  def __init__(self, name):
    self.name = name
  def dismissal(self, grade):
    reportCard = 'You get a grade of ' + grade
    del self
    return reportCard

algebra = InSession('algebra')

reportCard = algebra.dismissal('D')
print reportCard
{/code}

The code above works, but the "algebra" instance of InSession still
exists. I changed the "del self" to "exec('del ' + self.name)", and sure
enough it kills the instance, but it doesn't return the value (something
like a NameError exception because "algebra" doesn't exist.)

Would I be able to do this all in the __del__() method instead? If so I
don't have to do anything other than "del algebra"? Can I give my method
values like "def __del__(self, grade):"? How would I pass the grade
variable? And to assign a value to a variable, would it be like this:
    reportCard = algebra.__del__('F')
Would that delete the instance?

Anyway, I've tried it, and I can't figure out how to delete the instance
and return a value at the same time. Using that last example of
__del__(), there seems to be nothing special about the __del__ name.
The string is returned, but "algebra" still exists. I guess I'm going to
have to do this from outside the function ...
    reportCard = algebra.dismissal("C")
    del algebra

Now moving on, I will have saved pointers to this instance in instances
of another class. Suppose I have a School instance called "highSchool",
and one attribute of that class instance is "highSchool.subject =
algebra". And another might be "highSchool.algebra = 'math'". What will
happen to those highSchool attributes when algebra is dismissed?

Thanks again -- this list (and Python itself) is great.

    Rob - /dev/rob0


From dyoo@hkn.eecs.berkeley.edu  Sun Dec  2 22:17:35 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 2 Dec 2001 14:17:35 -0800 (PST)
Subject: [Tutor] class data
In-Reply-To: <Pine.LNX.4.33.0112021646300.14857-100000@fleet1.paxp.com>
Message-ID: <Pine.LNX.4.21.0112021407140.19586-100000@hkn.eecs.berkeley.edu>

On Sun, 2 Dec 2001 fleet@teachout.org wrote:

> "In this section, we will take a close look at classes and what types
> of attributes they have.  Just remember to keep in mind that even
> though classes are objects (everything in Python is an object), they
> are not realizations of the objects they are defining. We will look at
> instances in the next chapter, so stay tuned for that.  For now, the
> limelight is strictly beamed on class objects."

I think the author is making the distinction between the class
'AddrBookEntry':

##
>>> AddrBookEntry
<class __main__.AddrBookEntry at 0x8119034>
##

and an instance of that class:

###
>>> a = AddrBookEntry('John Doe', '405-555-1212')
>>> a
<__main__.AddrBookEntry instance at 0x8110e5c>
###



> "When you create a class, you are practically creating your own kind
> of data entity.  All instances of that class are similar, but classes
> differ from each other (and so will instances of different classes by
> nature). Rather than playing with toys that come from the manufacturer
> and were bestowed upon you as gifts, why not design and build your own
> toys to play with?"


> So if class data is not stored in standard containers, where is it
> stored (and how)?  (I'm talking about the names, phone numbers, e-mail
> addresses, etc. in the AddrBookEntry class example.)

>From what I remember, instance data actually is stored in a standard
dictionary container:

###
>>> a = AddrBookEntry('John Doe', '405-555-1212')
Created instance for: John Doe
>>> a.__dict__
{'phone': '405-555-1212', 'name': 'John Doe'}
###

Python usually hides this dictionary so that, in casual use, we never
really need to worry about it --- we can just access the 'properties' of
our class with the special Python notation:

###
>>> a.phone, a.name
('405-555-1212', 'John Doe')
###


Still, nothing stops us from saying:

##
>>> a.__dict__['phone'], a.__dict__['name']
('405-555-1212', 'John Doe')
###

It's just uglier that way.


Hope this helps!



From dsh8290@rit.edu  Sun Dec  2 22:25:30 2001
From: dsh8290@rit.edu (dman)
Date: Sun, 2 Dec 2001 17:25:30 -0500
Subject: [Tutor] destroying classes
In-Reply-To: <20011202161827.G27400@hal>; from i812@iname.com on Sun, Dec 02, 2001 at 04:18:27PM -0600
References: <20011202161827.G27400@hal>
Message-ID: <20011202172530.D17679@harmony.cs.rit.edu>

On Sun, Dec 02, 2001 at 04:18:27PM -0600, Rob McGee wrote:

| Anyway, one of my classes has a method which should result in the
| destruction of the class instance.

You can't do this.

| But the method also wants to return a value. If I put a "del self"
| command in there, would the method end at that point, or would it
| continue to completion?

The only effect 'del self' would have is to remove the name "self"
from the local scope (now you have no way to access the instance any
more) and decrement its ref count by 1.  Everything else continues as
usual, and the client still has a reference to the instance so it
doesn't go away.

If you were using C++ you could do this ("delete this ;") but then the
client would have a dangling pointer that would at best give a
segmentation fault later, or at worst just cause weird data corruption
and behavior.

The reason you can't destroy an object is an object should only be
destroyed when it is impossible to use it anymore (that is, there are
no more references to it).  As hinted above, C++ makes you, the
prorgrammer, keep track and decide when the object should go away.
Python is the opposite - it keeps track for you and destroys the
object when you no longer have any references to it.

HTH,
-D

-- 

Contrary to popular belief, Unix is user friendly.
It just happens to be selective about who it makes friends with.
                                               -- Dave Parnas



From i812@iname.com  Sun Dec  2 22:25:13 2001
From: i812@iname.com (Rob McGee)
Date: Sun, 2 Dec 2001 16:25:13 -0600
Subject: [Tutor] destroying classes
In-Reply-To: <20011202161827.G27400@hal>; from i812@iname.com on Sun, Dec 02, 2001 at 04:18:27PM -0600
References: <20011202161827.G27400@hal>
Message-ID: <20011202162513.H27400@hal>

On Sun, Dec 02, 2001 at 04:18:27PM -0600, Rob McGee wrote:
> The string is returned, but "algebra" still exists. I guess I'm going to
> have to do this from outside the function ...
                                   ^^^^^^^^
>     reportCard = algebra.dismissal("C")
>     del algebra

I meant to say outside the "class", not function.

    Rob - /dev/rob0


From pobrien@orbtech.com  Sun Dec  2 22:49:17 2001
From: pobrien@orbtech.com (Patrick K. O'Brien)
Date: Sun, 2 Dec 2001 16:49:17 -0600
Subject: [Tutor] "from this import *" or "import this"
In-Reply-To: <003101c17b47$248b7be0$0100c0a8@videotron.ca>
Message-ID: <NBBBIOJPGKJEKIECEMCBOEGELEAA.pobrien@orbtech.com>

You're welcome. I think wxPython is quite nice and prefer it for myself.
There is a new version due out in about a week or two, which has made quite
a number of improvements and is very stable. I would look for that one. Good
luck.

---
Patrick K. O'Brien
Orbtech.com - Your Source For Python Development Services


> -----Original Message-----
> From: Jean Montambeault [mailto:jrm@videotron.ca]
> Sent: Sunday, December 02, 2001 9:37 AM
> To: pobrien@orbtech.com
> Subject: Re: [Tutor] "from this import *" or "import this"
>
>
>
> ----- Original Message -----
> From: "Patrick K. O'Brien" <pobrien@orbtech.com>
> To: "Jean Montambeault" <jrm@videotron.ca>; <tutor@python.org>
> Sent: Monday, December 03, 2001 12:13 AM
> Subject: RE: [Tutor] "from this import *" or "import this"
>
>
> > You have a perfectly good grasp on the situation. Avoid import * for all
> the
> > reasons you cite, unless you don't really have a choice. For
> example, the
> > wxPython gui toolkit pretty much requires you to do "from wxPython.wx
> import
> > *".
>
> Thanks for the precision over what had been already said for the case of
> Tkinter.
> I've had no more than a look at GUI programming till now but I'm getting
> there. WmPython seems to me to be more attractive than Tkinter
> todate and I
> intend to avoid any system linked to one platform more than another.
>
> Ciao.
>
> Jean M.
>



From dyoo@hkn.eecs.berkeley.edu  Sun Dec  2 23:20:53 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 2 Dec 2001 15:20:53 -0800 (PST)
Subject: [Tutor] "from this import *" or "import this"
In-Reply-To: <002801c17b46$63ea2120$0100c0a8@videotron.ca>
Message-ID: <Pine.LNX.4.21.0112021518430.21349-100000@hkn.eecs.berkeley.edu>

On Sun, 2 Dec 2001, Jean Montambeault wrote:

> 
> ----- Original Message -----
> From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
> 
> >  It's convenient because one doesn't need
> > to type in the module name, so there's less typing.
> 
> I'm a fan of "Alt+/" so I hardly notice.  I regret that it doesn't
> search in all of the opened buffers in IDLE though.

By the way, the Emacs text editor actually does search through files when
you use the "M-/" expansion command, which is very very cool.  *grin*

Talk to you later!



From dyoo@hkn.eecs.berkeley.edu  Sun Dec  2 23:39:38 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 2 Dec 2001 15:39:38 -0800 (PST)
Subject: [Tutor] destroying classes  [reference counting]
In-Reply-To: <20011202172530.D17679@harmony.cs.rit.edu>
Message-ID: <Pine.LNX.4.21.0112021521570.21349-100000@hkn.eecs.berkeley.edu>

On Sun, 2 Dec 2001, dman wrote:

> The reason you can't destroy an object is an object should only be
> destroyed when it is impossible to use it anymore (that is, there are
> no more references to it).  As hinted above, C++ makes you, the
> prorgrammer, keep track and decide when the object should go away.
> Python is the opposite - it keeps track for you and destroys the
> object when you no longer have any references to it.

As a side note: Python even allows us to see the reference count of an
object in Python if we use the sys.getrefcount() function:

###
from sys import getrefcount

def test():
    ref = getrefcount  ## I just want to make it easier to type.
    x = "some object"
    print ref(x)
    y = x
    print ref(x)
    z = x
    print ref(x)
    del y
    print ref(x)
###

When we run test(), we can see that the reference count of an object
increments every time we assign a new variable name for it:

###
>>> test()
3
4
5
4
###

Note that test() doesn't start at 1 because the very act of calling
getrefcount() on an object adds a few more references to that object!  


Hope this helps!



From fleet@teachout.org  Sun Dec  2 23:53:17 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Sun, 2 Dec 2001 18:53:17 -0500 (EST)
Subject: [Tutor] class data
In-Reply-To: <Pine.LNX.4.21.0112021407140.19586-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.33.0112021846220.15026-100000@fleet1.paxp.com>

On Sun, 2 Dec 2001, Danny Yoo wrote:

> > "When you create a class, you are practically creating your own kind
> > of data entity.  All instances of that class are similar, but classes
> > differ from each other (and so will instances of different classes by
> > nature). Rather than playing with toys that come from the manufacturer
> > and were bestowed upon you as gifts, why not design and build your own
> > toys to play with?"
>
>
> > So if class data is not stored in standard containers, where is it
> > stored (and how)?  (I'm talking about the names, phone numbers, e-mail
> > addresses, etc. in the AddrBookEntry class example.)
>
> >From what I remember, instance data actually is stored in a standard
> dictionary container:
>
> ###
> >>> a = AddrBookEntry('John Doe', '405-555-1212')
> Created instance for: John Doe
> >>> a.__dict__
> {'phone': '405-555-1212', 'name': 'John Doe'}
> ###
>
> Python usually hides this dictionary so that, in casual use, we never
> really need to worry about it --- we can just access the 'properties' of
> our class with the special Python notation:
>

I load the module, add a name and phone number, exit python, turn off the
computer, come back in two days, turn on computer, load the module.  Data
is gone.

Do I (or should I) use a dictionary to store the data?  Long term.  And if
I do need to use the dictionary, what advantage do I gain by funneling
everything through a class structure?

				- fleet -



From urnerk@qwest.net  Mon Dec  3 03:11:59 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 02 Dec 2001 19:11:59 -0800
Subject: [Tutor] Need more precise digits
In-Reply-To: <LNBBLJKPBEHFEDALKOLCAEGAMKAA.tim.one@home.com>
References: <4.2.0.58.20011201203547.00c3e660@pop3.norton.antivirus>
Message-ID: <4.2.0.58.20011202184351.00c5c100@pop3.norton.antivirus>

>
>more-fun-than-apple-pi-ly y'rs  - tim

Excellent stuff on continued fractions from our
resident math-through-Python (and Python-thru-math)
guru Tim Peters.

Going the other direction, you might want to take some
ordinary fraction p/q, and convert it into a continued
fraction, expressed as a list of partial quotients
[q0,q1,q2...].

Here's an algorithm for doing that from my algebra.py,
based on stuff I'm pretty sure I learned from another
good math book: 'Number' by Midhat Gazale.

  def cfract(a,b):
      """
      Return partial quotients of a regular
      continued fraction equivalent to a/b"""
      rcf = []
      while b<>0:
         p = a//b
         rcf.append(p)
         b, a = a - p*b, b
      return rcf

It's sort of a modification of the EEA (Euclid's Extended
Algorithm).

So suppose we want the continued fraction expression of phi,
starting from x = (1 + sqrt(5)/2.  You can just put the
floating point decimal over a big power of 10, and run
it through:

  >>> import algebra, math
  >>> phi = (1 + math.sqrt(5))/2
  >>> phi
  1.6180339887498949
  >>> 16180339887498949/10000000000000000.
  1.6180339887498949
  >>> algebra.cfract(16180339887498949,10000000000000000)
  [1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
  1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
  1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 10L, 8L, 5L, 37L, 1L,
  10L, 1L, 2L, 3L, 3L, 1L, 1L, 1L, 1L, 2L]

OK, so it goes off the rails there after awhile, or
actually, it doesn't, because this is an exact translation
of the above fraction, which isn't phi, but an approximation
of phi.

Another interesting true fact about continued fractions, is
the square root of any natural number will generate a
*repeating pattern* of partial quotients.  Taking this as
a given, we can use the same trick as above to get a handle
on what this pattern might be:

  >>> math.sqrt(3)
  1.7320508075688772
  >>> algebra.cfract(17320508075688772,10000000000000000)[:15]
  [1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L]

I truncated the list to 15 elements, knowing it'll diverge
from the pattern later, given I'm feeding it an approximation.
This is enough to give me the idea.

OK, so it looks like I've got a repeating 1,2 pattern, with
a 1 up front.  I could yield that with a generator, as we've
seen:

   def root3pqs():
       yield 1
       flipper = 1
       while 1:
          if flipper:
              yield 1
              flipper = 0
          else:
              yield 2
              flipper = 1

(that could be made more streamlined I'm sure).  Testing:

   >>> genpqs = root3pqs()
   >>> [genpqs.next() for i in range(10)]
   [1, 1, 2, 1, 2, 1, 2, 1, 2, 1]

Lookin' good.

So now I can use Tim's cf() generator with this generator as
input, to get successively more accurate fractional
representations of the square root of 3:

  def conv(pqs):
     x0, y0 = 0, 1  # zero
     x1, y1 = 1, 0  # infinity
     yield x0, y0
     yield x1, y1
     for q in pqs:
         x0, y0, x1, y1 = x1, y1, x0 + q*x1, y0 + q*y1
         yield x1, y1

  >>> genpqs = root3pqs()
  >>> root3gen = conv(genpqs)
  >>> root3gen.next()
  (0, 1)
  >>> root3gen.next()
  (1, 0)
  >>> root3gen.next()
  (1, 1)
  >>> root3gen.next()
  (2, 1)
  >>> root3gen.next()
  (5, 3)
  >>> root3gen.next()
  (7, 4)
  >>> for i in range(30):      # skip ahead in a hurry
         val = root3gen.next()

  >>> val
  (2642885282L, 1525870529)
  >>> 2642885282L/1525870529.
  1.7320508075688772
  >>> math.sqrt(3)
  1.7320508075688772

Our fraction is already quite accurate.

BTW, I second Tim's recommendation of 'Concrete Mathematics'
-- bought it awhile ago on his recommendation and never
regretted it, even though I'm not a CS major (philosophy
over here).

Kirby




From dyoo@hkn.eecs.berkeley.edu  Mon Dec  3 04:26:28 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 2 Dec 2001 20:26:28 -0800 (PST)
Subject: [Tutor] class data
In-Reply-To: <Pine.LNX.4.33.0112021846220.15026-100000@fleet1.paxp.com>
Message-ID: <Pine.LNX.4.21.0112022022010.26319-100000@hkn.eecs.berkeley.edu>

On Sun, 2 Dec 2001 fleet@teachout.org wrote:

> On Sun, 2 Dec 2001, Danny Yoo wrote:
> > > So if class data is not stored in standard containers, where is it
> > > stored (and how)?  (I'm talking about the names, phone numbers, e-mail
> > > addresses, etc. in the AddrBookEntry class example.)
> >
> > >From what I remember, instance data actually is stored in a standard
> > dictionary container:
> >
> > ###
> > >>> a = AddrBookEntry('John Doe', '405-555-1212')
> > Created instance for: John Doe
> > >>> a.__dict__
> > {'phone': '405-555-1212', 'name': 'John Doe'}
> > ###
> >
> > Python usually hides this dictionary so that, in casual use, we never
> > really need to worry about it --- we can just access the 'properties' of
> > our class with the special Python notation:
> >
> 
> I load the module, add a name and phone number, exit python, turn off the
> computer, come back in two days, turn on computer, load the module.  Data
> is gone.
> 
> Do I (or should I) use a dictionary to store the data?  Long term.  And if
> I do need to use the dictionary, what advantage do I gain by funneling
> everything through a class structure?


Ah!  Take a look at the 'pickle' module:

    http://python.org/doc/lib/module-pickle.html

'pickle' knows how to deal with instances, and will properly allow you to
save data structures as a byte stream.

It doesn't work on pathological cases (like C extension modules or files),
at least, not without a bit of hacking with the 'copy_reg' module.  

Try it out, and if you have problems with it, please email the list, and
we can ferment an example.



From ak@silmarill.org  Mon Dec  3 05:03:42 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 03 Dec 2001 00:03:42 -0500
Subject: [Tutor] "from this import *" or "import this"
In-Reply-To: <000d01c17b42$41855680$0100c0a8@videotron.ca>
References: <000d01c17b42$41855680$0100c0a8@videotron.ca>
Message-ID: <20011203000342.A23411@sill.silmarill.org>

On Sun, Dec 02, 2001 at 05:01:43PM +0200, Jean Montambeault wrote:
>     Be ready for a whole lot of very newbie questions. I've never programmed
> before and do not intend to make a career out of what I am learning : pure
> amateurism here which does not necessarily implies triviality but that
> shouldn't be a surprise.
> 
>     So :
>         is there a real use for the form "from this_module import * " since
>                 (a) there seems to be a real danger to get some functions or
> variables which would have the same name if more than one module are open
> that way
>                 (b) nothing shows the relation to the module which is to
> some extent documenting the program
>                 (c) it imports the whole module (I guess) just as "import
> this_module" seems to be doing
>         ?
>         Or is it much safer and wiser to avoid using it ?

Aside from all other things mentioned, from mod import * is useful in
the interactive interpreter. If you just started it up to check
something in 10 seconds, it'll save you time and isn't dangerous cause
you (hopefully) can remember what module you imported from for 10
seconds :-). If not, don't use it at all!

> 
>         Thanks
> 
>        Jean M.
> 
> 
> 
> 
> 
> _______________________________________________
> 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  Mon Dec  3 06:48:40 2001
From: glingl@aon.at (Gregor Lingl)
Date: Mon, 3 Dec 2001 07:48:40 +0100
Subject: [Tutor] Division
References: <LNBBLJKPBEHFEDALKOLCEEHBMKAA.tim.one@home.com>
Message-ID: <001001c17bc6$8adf0fe0$1664a8c0@mega>

Dear Tim!

Thanks! This works fine.

But unfortunataly there remains the problem of starting
IDLE - which I use to use with my students - in this new mode:

C:\python22\tools\idle -Qnew idle.py

starts IDLE without problems, but doesn't have the 
desired result:

Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> 3/2
1
>>> 

So the interpreter working in the REP-loop inside IDLE seems not to 
be aware of the -Qnew option. How can this also be changed?

Gregor

----- Original Message ----- 
From: "Tim Peters" <tim.one@home.com>
To: "Gregor Lingl" <glingl@aon.at>; <tutor@python.org>
Sent: Sunday, December 02, 2001 8:10 PM
Subject: RE: [Tutor] Division


> [Gregor Lingl]
> > As I'm starting to give a new course 'Introduction to
> > programming' in Jan 2002. 
.....
> >
> > So my question is: Is there a way to start the Python-Interpreter
> > with new division enabled, 
.....
> Skip down to the "Command Line Option" section of PEP 238:
> 
>     http://python.sf.net/peps/pep-0238.html
> 
> As it says,
> 
>     The "new" option is only intended for use in certain educational
>     environments, where true division is required, but asking the
>     students to include the future division statement in all their
>     code would be a problem.
> 
> C:\Code\python\PCbuild>python -Qnew
> Python 2.2b2+ (#26, Nov 28 2001, 19:17:11) [MSC 32 bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> 1/2
> 0.5
> >>> 1//2
> 0
> >>>
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



From cow@esweeet.com  Mon Dec  3 07:23:32 2001
From: cow@esweeet.com (Cow)
Date: Sun, 2 Dec 2001 23:23:32 -0800 (PST)
Subject: [Tutor] FTPlib Module
Message-ID: <20011203072332.83E0D2757@sitemail.everyone.net>

I am currently learning to use the ftplib module, and i am getting most of it but i am running into a problem when i try to send a file.  Here is my code:

from ftplib import FTP

cow= FTP("127.0.0.1") #Pretend that that address is the address of a FTP
cow.login()
cow.cwd("/")
cow.set_pasv(0)
cow.transfercmd("STOR test1.txt")
cow.close()

when i run the code, it sends the file to the sever, but there is nothing in the file (it is blank).  i am learning from this explanation:

transfercmd(cmd[, rest])
 
Initiate a transfer over the data connection. If the transfer is active, send a "EPRT" or "PORT" command and the transfer command specified by cmd, and accept the connection. If the server is passive, send a "EPSV" or "PASV" command, connect to it, and start the transfer command. Either way, return the socket for the connection. 

i get most of it, but when i actually use code, it only sends a blank file.  can someone please clear up how i can get my code to send the file with its data in it?

Thanks
-Ryan




_____________________________________________________________
Free eSweeet Mail - http://www.esweeet.com


From karthikg@aztec.soft.net  Mon Dec  3 05:49:03 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Mon, 3 Dec 2001 11:19:03 +0530
Subject: [Tutor] integers are also objects?
In-Reply-To: <Pine.LNX.4.21.0112021521570.21349-100000@hkn.eecs.berkeley.edu>
Message-ID: <NEBBJNMDEKBIBCMCNMBDGELLCKAA.karthikg@aztec.soft.net>

hi all!,

I'm having a very basic python doubt.

Are integers objects in python?

d:\>python
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> i = 10
>>> a = 5+5
>>> id(a)
8136016
>>> id(i)
8136016

In both cases, i and a, the id of the objects happened to be same though i
created 2 different integer objects.
so (i == a) obviously works.

So my question is that does "==" work on contents in case of integers or it
works only on
references and python makes sure that integer references with same content
point to the
same location, the way it works for strings.

thanks in advance,
karthik.








From ak@silmarill.org  Mon Dec  3 07:48:02 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 03 Dec 2001 02:48:02 -0500
Subject: [Tutor] integers are also objects?
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDGELLCKAA.karthikg@aztec.soft.net>
References: <Pine.LNX.4.21.0112021521570.21349-100000@hkn.eecs.berkeley.edu>
 <NEBBJNMDEKBIBCMCNMBDGELLCKAA.karthikg@aztec.soft.net>
Message-ID: <20011203024802.A24176@sill.silmarill.org>

On Mon, Dec 03, 2001 at 11:19:03AM +0530, karthik Guru wrote:
> hi all!,
> 
> I'm having a very basic python doubt.
> 
> Are integers objects in python?
> 
> d:\>python
> Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> >>> i = 10
> >>> a = 5+5
> >>> id(a)
> 8136016
> >>> id(i)
> 8136016
> 
> In both cases, i and a, the id of the objects happened to be same though i
> created 2 different integer objects.
> so (i == a) obviously works.
> 
> So my question is that does "==" work on contents in case of integers or it
> works only on
> references and python makes sure that integer references with same content
> point to the
> same location, the way it works for strings.
> 
> thanks in advance,
> karthik.

0 to 99 are pre-created integer objects, for speed. whenever you have a
variable that is 0 to 99, one of these objects gets assigned to it..

> 
> 
> 
> 
> 
> 
> 
> _______________________________________________
> 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 scarblac@pino.selwerd.nl  Mon Dec  3 07:57:37 2001
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Mon, 3 Dec 2001 08:57:37 +0100
Subject: [Tutor] integers are also objects?
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDGELLCKAA.karthikg@aztec.soft.net>; from karthikg@aztec.soft.net on Mon, Dec 03, 2001 at 11:19:03AM +0530
References: <Pine.LNX.4.21.0112021521570.21349-100000@hkn.eecs.berkeley.edu> <NEBBJNMDEKBIBCMCNMBDGELLCKAA.karthikg@aztec.soft.net>
Message-ID: <20011203085737.A25849@pino.selwerd.nl>

On  0, karthik Guru <karthikg@aztec.soft.net> wrote:
> hi all!,
> 
> I'm having a very basic python doubt.
> 
> Are integers objects in python?

Everything is an object.

> d:\>python
> Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> >>> i = 10
> >>> a = 5+5
> >>> id(a)
> 8136016
> >>> id(i)
> 8136016
> 
> In both cases, i and a, the id of the objects happened to be same though i
> created 2 different integer objects.

In the case of literals of immutable objects, Python sometimes caches some
of them and re-uses the same object. Since they're immutable anyway, this is
no problem. Python caches for instance all integers between -1 and 100, or
some such. Those numbers may be wrong and may change.

Try:
i = 106
a = 106
id(i)
id(a)


> so (i == a) obviously works.
> 
> So my question is that does "==" work on contents in case of integers or it
> works only on
> references and python makes sure that integer references with same content
> point to the
> same location, the way it works for strings.

Not all strings with the same content point to the same location; some of
them are cached, but not all of them. Typically only strings that you use as
literals (the ones you "spell out" in program code) are cached, not strings
that are the result of a computation.

Any == check on any two objects first compares the two references, if
they're the same then the objects are equal (since they're the same object).
Only if they're not the same, are the objects then compared for value.

-- 
Remco Gerlich


From karthikg@aztec.soft.net  Mon Dec  3 06:43:38 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Mon, 3 Dec 2001 12:13:38 +0530
Subject: [Tutor] integers are also objects?
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDGELLCKAA.karthikg@aztec.soft.net>
Message-ID: <NEBBJNMDEKBIBCMCNMBDGELMCKAA.karthikg@aztec.soft.net>

hi all!,

I'm having a very basic python doubt.

Are integers objects in python?

d:\>python
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> i = 10
>>> a = 5+5
>>> id(a)
8136016
>>> id(i)
8136016

In both cases, i and a, the id of the objects happened to be same though i
created 2 different integer objects.
so (i == a) obviously works.

So my question is that does "==" work on contents in case of integers or it
works only on
references and python makes sure that integer references with same content
point to the
same location, the way it works for strings.

thanks in advance,
karthik.








From dyoo@hkn.eecs.berkeley.edu  Mon Dec  3 08:20:59 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 3 Dec 2001 00:20:59 -0800 (PST)
Subject: [Tutor] integers are also objects?
In-Reply-To: <20011203085737.A25849@pino.selwerd.nl>
Message-ID: <Pine.LNX.4.21.0112030016330.3441-100000@hkn.eecs.berkeley.edu>

On Mon, 3 Dec 2001, Remco Gerlich wrote:

> > So my question is that does "==" work on contents in case of
> integers or it works only on references and python makes sure that
> integer references with same content point to the same location, the
> way it works for strings.
> 
> Not all strings with the same content point to the same location; some of
> them are cached, but not all of them. Typically only strings that you use as
> literals (the ones you "spell out" in program code) are cached, not strings
> that are the result of a computation.

And if we do want computed string to be cached, we can use the
intern() function:

###
>>> s = "hello world"
>>> s2 = "hello" + " world"
>>> id(s)
135314088
>>> id(s2)
135166088
>>> s = intern(s)
>>> s2 = intern(s2)
>>> id(s)
135314088
>>> id(s2)
135314088
###


> Any == check on any two objects first compares the two references, if
> they're the same then the objects are equal (since they're the same
> object). Only if they're not the same, are the objects then compared
> for value.

If we do want to check to see if two things refer to the same object, we
can use ths 'is' operator:

###
>>> 1 + 1 is 2
1                       ## ... but this works just because of the
                        ## caching behavior of small integers.
>>> 1 + 1 == 2
1
>>> 101 + 1 is 102      ## Let's try this on larger numbers
0
>>> 101 + 1 == 102 
1
###



From karthikg@aztec.soft.net  Mon Dec  3 09:09:42 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Mon, 3 Dec 2001 14:39:42 +0530
Subject: [Tutor] integers are also objects?
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDKEMACKAA.karthikg@aztec.soft.net>
Message-ID: <NEBBJNMDEKBIBCMCNMBDMEMDCKAA.karthikg@aztec.soft.net>

thanks a lot for the information.
since integer are objects, do integers also inherit from some class?? rather
are integers instance of some class?
Has the __eq__() been overridden for that class to return 1 if the content
happens to be the same. what is that class?

thanks for your patience,
karthik.



-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Andrei Kulakov
Sent: Monday, December 03, 2001 1:18 PM
To: tutor@python.org
Subject: Re: [Tutor] integers are also objects?


On Mon, Dec 03, 2001 at 11:19:03AM +0530, karthik Guru wrote:
> hi all!,
>
> I'm having a very basic python doubt.
>
> Are integers objects in python?
>
> d:\>python
> Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> >>> i = 10
> >>> a = 5+5
> >>> id(a)
> 8136016
> >>> id(i)
> 8136016
>
> In both cases, i and a, the id of the objects happened to be same
though i
> created 2 different integer objects.
> so (i == a) obviously works.
>
> So my question is that does "==" work on contents in case of integers
or
it
> works only on
> references and python makes sure that integer references with same
content
> point to the
> same location, the way it works for strings.
>
> thanks in advance,
> karthik.

0 to 99 are pre-created integer objects, for speed. whenever you have a
variable that is 0 to 99, one of these objects gets assigned to it..

>
>
>
>
>
>
>
> _______________________________________________
> 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

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



From scarblac@pino.selwerd.nl  Mon Dec  3 08:57:37 2001
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Mon, 3 Dec 2001 09:57:37 +0100
Subject: [Tutor] integers are also objects?
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDMEMDCKAA.karthikg@aztec.soft.net>; from karthikg@aztec.soft.net on Mon, Dec 03, 2001 at 02:39:42PM +0530
References: <NEBBJNMDEKBIBCMCNMBDKEMACKAA.karthikg@aztec.soft.net> <NEBBJNMDEKBIBCMCNMBDMEMDCKAA.karthikg@aztec.soft.net>
Message-ID: <20011203095737.A26077@pino.selwerd.nl>

On  0, karthik Guru <karthikg@aztec.soft.net> wrote:
> thanks a lot for the information.
> since integer are objects, do integers also inherit from some class?? rather
> are integers instance of some class?

No. They're objects, but not class instances. They're types.

This sort of thing is being changed in the very latest Pythons, and I
haven't followed the recent development, but as far as I know it's still
true. Soon there may be an Integer class that does this, but I don't know
the details.

-- 
Remco Gerlich


From dyoo@hkn.eecs.berkeley.edu  Mon Dec  3 09:40:23 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 3 Dec 2001 01:40:23 -0800 (PST)
Subject: [Tutor] integers are also objects?
In-Reply-To: <20011203095737.A26077@pino.selwerd.nl>
Message-ID: <Pine.LNX.4.21.0112030135240.5029-100000@hkn.eecs.berkeley.edu>

On Mon, 3 Dec 2001, Remco Gerlich wrote:

> On  0, karthik Guru <karthikg@aztec.soft.net> wrote:
> > thanks a lot for the information.
> > since integer are objects, do integers also inherit from some
> > class?? rather are integers instance of some class?
> 
> No. They're objects, but not class instances. They're types.
> 
> This sort of thing is being changed in the very latest Pythons, and I
> haven't followed the recent development, but as far as I know it's
> still true. Soon there may be an Integer class that does this, but I
> don't know the details.

There are details online about the type/class unification that's part of
the upcoming 2.2 release:

   http://www.python.org/2.2/descrintro.html

The __future__ looks quite exciting (and frightening) indeed.  *grin*



From m_konermann@gmx.de  Mon Dec  3 10:02:37 2001
From: m_konermann@gmx.de (Marcus Konermann)
Date: Mon, 03 Dec 2001 11:02:37 +0100
Subject: [Tutor] Installation problems
Message-ID: <3C0B4DBD.37617612@gmx.de>

Hi @ All !

I want to generate a python shadow class from an excisting c++ file by
using SWIG and VC++ 6.0 under Windows 2000 and i think that something
went wrong with the installation of SWIG under VC++. Can anyone give me
an advise where i can find detailed information of the installation
process ? It seems that there are some binding problems of SWIG with
VC++.

P.s: i also looked in the Installation section on www.swig.org

Greetings
Marcus



From dyoo@hkn.eecs.berkeley.edu  Mon Dec  3 10:00:37 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 3 Dec 2001 02:00:37 -0800 (PST)
Subject: [Tutor] FTPlib Module
In-Reply-To: <20011203072332.83E0D2757@sitemail.everyone.net>
Message-ID: <Pine.LNX.4.21.0112030156270.5029-100000@hkn.eecs.berkeley.edu>

On Sun, 2 Dec 2001, Cow wrote:

> I am currently learning to use the ftplib module, and i am getting most of it but i am running into a problem when i try to send a file.  Here is my code:
> 
> from ftplib import FTP
> 
> cow= FTP("127.0.0.1") #Pretend that that address is the address of a FTP
> cow.login()
> cow.cwd("/")
> cow.set_pasv(0)
> cow.transfercmd("STOR test1.txt")
> cow.close()
> 
> when i run the code, it sends the file to the sever, but there is nothing in the file (it is blank).  i am learning from this explanation:
> 
> transfercmd(cmd[, rest])
>  
> Initiate a transfer over the data connection. If the transfer is active, send a "EPRT" or "PORT" command and the transfer command specified by cmd, and accept the connection. If the server is passive, send a "EPSV" or "PASV" command, connect to it, and start the transfer command. Either way, return the socket for the connection. 
> 
> i get most of it, but when i actually use code, it only sends a blank file.  can someone please clear up how i can get my code to send the file with its data in it?

I took a closer look at:

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


You might want to use storbinary() or storlines() instead of
transfercmd(); I think that transfercmd() is meant for something
else.  See if:

###
cow.storlines("STOR test1.txt", open("test1.txt"))
###

works better for you.



From printers@sendme.cz  Mon Dec  3 10:06:04 2001
From: printers@sendme.cz (A)
Date: Mon, 3 Dec 2001 11:06:04 +0100
Subject: [Tutor] How to compare text?
Message-ID: <3C0B5C9C.10969.755101@localhost>

Hello,
How can I compare of one  parragraph of text with another
paragraph?Each paragraph can have about 100 words.
For example I have the first paragraph

I want to be very good at Python programming. Better than in Perl.

THe second paragraph might look loke this:

She works all day long to master Perl.

All that I need is to find out if any of word from the second is in the 
first paragraph. For the example above I should find out word

Perl


What is the best and quickest way?
Thank you for help.
Ladislav




From ak@silmarill.org  Mon Dec  3 10:14:25 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 03 Dec 2001 05:14:25 -0500
Subject: [Tutor] How to compare text?
In-Reply-To: <3C0B5C9C.10969.755101@localhost>
References: <3C0B5C9C.10969.755101@localhost>
Message-ID: <20011203051425.A25049@sill.silmarill.org>

On Mon, Dec 03, 2001 at 11:06:04AM +0100, A wrote:
> 
> Hello,
> How can I compare of one  parragraph of text with another
> paragraph?Each paragraph can have about 100 words.
> For example I have the first paragraph
> 
> I want to be very good at Python programming. Better than in Perl.
> 
> THe second paragraph might look loke this:
> 
> She works all day long to master Perl.
> 
> All that I need is to find out if any of word from the second is in the 
> first paragraph. For the example above I should find out word
> 
> Perl
> 
> 
> What is the best and quickest way?

Something along these lines:

paragraph1words = paragraph1.split()
paragraph2words = paragraph2.split()

common_words = []
for word in paragraph1words:
    if word in paragraph2words:
        common_words.append(word)
        
print "These words are in both paragraphs:",
for word in common_words:
    print word,

> Thank you for help.
> Ladislav
> 
> 
> 
> _______________________________________________
> 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 lha2@columbia.edu  Mon Dec  3 10:21:11 2001
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Mon, 03 Dec 2001 05:21:11 -0500
Subject: [Tutor] integers are also objects?
References: <NEBBJNMDEKBIBCMCNMBDGELMCKAA.karthikg@aztec.soft.net>
Message-ID: <3C0B5217.4C7738A8@mail.verizon.net>

My understanding is that integers are objects in python. Small integers
(less than 100), though, always have the same id in order to increase
speed, or something.

>>> a=99
>>> a is 99
1
>>> a == 99
1
>>> b=100
>>> b==100
1
>>> b is 100
0

(is compares the id of two objects)

karthik Guru wrote:
> 
> hi all!,
> 
> I'm having a very basic python doubt.
> 
> Are integers objects in python?
> 
> d:\>python
> Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> >>> i = 10
> >>> a = 5+5
> >>> id(a)
> 8136016
> >>> id(i)
> 8136016
> 
> In both cases, i and a, the id of the objects happened to be same though i
> created 2 different integer objects.
> so (i == a) obviously works.
> 
> So my question is that does "==" work on contents in case of integers or it
> works only on
> references and python makes sure that integer references with same content
> point to the
> same location, the way it works for strings.
> 
> thanks in advance,
> karthik.
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From alan.gauld@bt.com  Mon Dec  3 13:01:20 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 3 Dec 2001 13:01:20 -0000
Subject: [Tutor] Newbie Question:  IDLE, is there a HOWTO use...
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C148@mbtlipnt02.btlabs.bt.co.uk>

> So far, I have used the IDLE to edit py's but it seems that 
> there is more to it than that.

IDLE also has debugging tools and class browsing tools.
But the vast majority of use is just to create and run .py files.

> Is there a HOWTO for the use of IDLE?

There is a tutorial on the IDLE section of the python.org web site.

Danny was doing a tutor too I think? But I don't have his url.

Alan G


From alan.gauld@bt.com  Mon Dec  3 13:14:57 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 3 Dec 2001 13:14:57 -0000
Subject: [Tutor] the class struggle
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C149@mbtlipnt02.btlabs.bt.co.uk>

> soviet = ['Lenin', 'Trotsky', 'Stalin']
> 
> class Struggle:
>   def __init__(self, list, name):
>     self.Communist = 1
>     if name in list:
>       self.Soviet = 1
>     else:
>       self.Soviet = 0
> 
> myList = ['Marx', 'Engels', 'Lenin', 'Mao']
> 
> for x in myList:
>   execString = x + ' = Struggle(soviet, "' + x + '")'
>   exec(execString)
>   evalCommunist = x + '.Communist'
>   evalSoviet = x + '.Soviet'
>   if eval(evalCommunist):
>     print x, 'was a known Communist.'
>   if eval(evalSoviet):
>     print x, 'was a Soviet leader.'

Can I suggest that a dictionary would simplfy this?

people = {}

for x in myList:
  people[x] = Struggle(soviet,x)
  wasCommunist = people[x].Communist
  wasSoviet = people[x].Soviet
  if wasCommunist: 
    print x, ' was a communist'
  if wasSoviet: 
    print x, ' was a soviet leader'


You can either hold onto people for long term reference 
or just delete the entries as you go.

Maybe it's just me but all those evals hurt my head!

Alan G.


From alan.gauld@bt.com  Mon Dec  3 13:23:20 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 3 Dec 2001 13:23:20 -0000
Subject: [Tutor] Division
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C14A@mbtlipnt02.btlabs.bt.co.uk>

> > As I'm starting to give a new course 'Introduction to
> > programming' in Jan 2002. It's for young students in the
> > age of 15/16. (Of course) I shall use Python.
> > I'd consider it an advantage not to confuse my students
> > in the beginning with the specialities the overlaoding of 
> > the division-operator (although I had to do so for several times
> > until now). But neither with the import from future
> > statement.

Just one point is that maybe for an education in programming 
they should use the old style division behaviour - its how 
the vast majority of programming languages work and is a 
great way to seehow the computer is working under the covers.

If you want to use programming as part of another topic then 
use new division but if you want to teach programming 
principles stick to old style - its much more univesally 
applicable and infornative IMHO.

Alan G


From alan.gauld@bt.com  Mon Dec  3 13:31:44 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 3 Dec 2001 13:31:44 -0000
Subject: [Tutor] "from this import *" or "import this"
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C14B@mbtlipnt02.btlabs.bt.co.uk>

> never programmed before and do not intend to make a career 
> out of what I am learning 

>         is there a real use for the form "from this_module 
> import * " since

Its shorter to type but has several dangers attached, most of 
which you have correctly identified. For a beginner thats a 
great start :-)

Stick with 
import foo

and save much grief.
Use 'from foo import x,y' etc when you are absolutely SURE its OK
and you know you'll use the functions a lot. (Tkinter etc are the 
classic examples of sensible use)

Alan G


From alan.gauld@bt.com  Mon Dec  3 13:45:08 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 3 Dec 2001 13:45:08 -0000
Subject: [Tutor] destroying classes
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C14C@mbtlipnt02.btlabs.bt.co.uk>

> class InSession:
>   def __init__(self, name):
>     self.name = name
>   def dismissal(self, grade):
>     reportCard = 'You get a grade of ' + grade
>     del self
>     return reportCard

Getting objects to kill themselves in mid stream is not 
a good idea! Its a bit like asking your manservant to kill 
himself and then serve you dinner - tricky...

Better to send the kill from outside:
> reportCard = algebra.dismissal('D')
  del(algebra)
> print reportCard

> I changed the "del self" to "exec('del ' + self.name)", 

Boy, you really dig those exec statements :-)

> enough it kills the instance, but it doesn't return the value 

Coz its dead and gone before it hits the return...

> I'm going to have to do this from outside the function ...
>     reportCard = algebra.dismissal("C")
>     del algebra

Yes thats much nicer. You tell the object what to do and 
it does it - including killing itself.

Alan G.


From alan.gauld@bt.com  Mon Dec  3 13:55:48 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 3 Dec 2001 13:55:48 -0000
Subject: [Tutor] class data
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C14D@mbtlipnt02.btlabs.bt.co.uk>

I'll have a go at what I think is confusing you...

> A class is like a Python container type on steroids.  
> Not only can it hold multiple data items but it can 
> also support its own set of functions,
> ...
> Objects contained in lists are unrelated except for the name of their
> container.  Its members are accessed only via an index offset into an
> array-like data structure.  All lists have a common set of methods and
> provide key access to their members (who are also unrelated except for
> their container name).
> ...
> classes are objects (everything in Python is an object), they are not
> realizations of the objects they are defining. We will look 
> at instances in the next chapter, so stay tuned for that.  

> So if class data is not stored in standard containers, where 
> is it stored

In the class. The class is a type of container in its own right.

You can however save instances of the class(ie objects) in 
standard containers.

> I'm talking about the names, phone numbers, 
> e-mail addresses, etc. in the AddrBookEntry class example.)

class Entry:
   def __init__(s, nm,ph,em):
      s.name = nm
      s.phone = ph
      s.email = em
   def saveme(s,flnm):
      f = open(flnm,'a')
      f.write(`s.name`,'\t',`s.phone`,'\t',s.email`)

# We now have a class container which holds two methods

book = []
for i in range(10):
   book.append(Entry('al','1234','ag.co.com')

# we now have 10 instances stored in a standard list container

for e in book:
   e.saveme('book.txt')

# we now save the instance data from all 10 instances

Does that help?

Alan g.
      


From fleet@teachout.org  Mon Dec  3 14:37:52 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Mon, 3 Dec 2001 09:37:52 -0500 (EST)
Subject: [Tutor] class data
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C14D@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.33.0112030933500.17335-100000@fleet1.paxp.com>

Everything went fine until -

>>> for e in book:
...    e.saveme('book.txt')
...
Traceback (innermost last):
  File "<stdin>", line 2, in ?
  File "<stdin>", line 8, in saveme
TypeError: read-only buffer, tuple

				- fleet -

On Mon, 3 Dec 2001 alan.gauld@bt.com wrote:

> I'll have a go at what I think is confusing you...
>
> class Entry:
>    def __init__(s, nm,ph,em):
>       s.name = nm
>       s.phone = ph
>       s.email = em
>    def saveme(s,flnm):
>       f = open(flnm,'a')
>       f.write(`s.name`,'\t',`s.phone`,'\t',s.email`)
>
> # We now have a class container which holds two methods
>
> book = []
> for i in range(10):
>    book.append(Entry('al','1234','ag.co.com')
>
> # we now have 10 instances stored in a standard list container
>
> for e in book:
>    e.saveme('book.txt')
>
> # we now save the instance data from all 10 instances
>
> Does that help?
>
> Alan g.
>
>




From fleet@teachout.org  Mon Dec  3 15:35:53 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Mon, 3 Dec 2001 10:35:53 -0500 (EST)
Subject: [Tutor] class data
In-Reply-To: <Pine.LNX.4.21.0112022022010.26319-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.33.0112031027180.17542-100000@fleet1.paxp.com>

OK.  Using pickle and the associated example, I was able to save the class
and restore it.  Either none of the data was saved or I don't know how to
access it when the class is restored.

I don't see the utility in 'pickling' a class.  It's already saved in a
module (addrbook.py).  I haven't tried it; but I suspect if I pickled the
class, then deleted the addrbook.py module, I would no longer be able to
unpickle the class.  Or did I miss something?

				- fleet -

On Sun, 2 Dec 2001, Danny Yoo wrote:

> Ah!  Take a look at the 'pickle' module:
>
>     http://python.org/doc/lib/module-pickle.html
>
> 'pickle' knows how to deal with instances, and will properly allow you to
> save data structures as a byte stream.
>
> It doesn't work on pathological cases (like C extension modules or files),
> at least, not without a bit of hacking with the 'copy_reg' module.
>
> Try it out, and if you have problems with it, please email the list, and
> we can ferment an example.
>



From dsh8290@rit.edu  Mon Dec  3 15:49:11 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 10:49:11 -0500
Subject: [Tutor] integers are also objects?
In-Reply-To: <Pine.LNX.4.21.0112030135240.5029-100000@hkn.eecs.berkeley.edu>; from dyoo@hkn.eecs.berkeley.edu on Mon, Dec 03, 2001 at 01:40:23AM -0800
References: <20011203095737.A26077@pino.selwerd.nl> <Pine.LNX.4.21.0112030135240.5029-100000@hkn.eecs.berkeley.edu>
Message-ID: <20011203104911.B18525@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 01:40:23AM -0800, Danny Yoo wrote:
| On Mon, 3 Dec 2001, Remco Gerlich wrote:
| 
| > On  0, karthik Guru <karthikg@aztec.soft.net> wrote:
| > > thanks a lot for the information.
| > > since integer are objects, do integers also inherit from some
| > > class?? rather are integers instance of some class?
| > 
| > No. They're objects, but not class instances. They're types.
| > 
| > This sort of thing is being changed in the very latest Pythons, and I
| > haven't followed the recent development, but as far as I know it's
| > still true. Soon there may be an Integer class that does this, but I
| > don't know the details.
| 
| There are details online about the type/class unification that's part of
| the upcoming 2.2 release:
| 
|    http://www.python.org/2.2/descrintro.html
| 
| The __future__ looks quite exciting (and frightening) indeed.  *grin*

I think it looks cool.  Some of the new things are neat and I think
will work very naturally.

As far as integers go, in 2.2b2 they are instances of the "int"
class (or is it a metaclass, anyways it's the new-style classes) which
inherits from the "object" class.  You can create a subclass of it :

class MyInt( int ) :
    # override something here,
    # or add something here,
    # or both
    pass


Due to the potential for backwards-compatibility issues, old style
classes are the default, eg :

class AClass : pass

and new-style classes are used if the class inherits from a new-style
class, eg :

class AnotherClass( object ) : pass

the difference is irrelevant if you don't make use of any of the
advanced features.  The difference can be significant if you get into
dynamic attribute access (__getattribute__ and __setattribute__) and
the lookup order for inherited members/methods.

-D

-- 

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



From dsh8290@rit.edu  Mon Dec  3 15:51:24 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 10:51:24 -0500
Subject: [Tutor] Division
In-Reply-To: <001001c17bc6$8adf0fe0$1664a8c0@mega>; from glingl@aon.at on Mon, Dec 03, 2001 at 07:48:40AM +0100
References: <LNBBLJKPBEHFEDALKOLCEEHBMKAA.tim.one@home.com> <001001c17bc6$8adf0fe0$1664a8c0@mega>
Message-ID: <20011203105124.C18525@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 07:48:40AM +0100, Gregor Lingl wrote:
| Dear Tim!
| 
| Thanks! This works fine.
| 
| But unfortunataly there remains the problem of starting
| IDLE - which I use to use with my students - in this new mode:
| 
| C:\python22\tools\idle -Qnew idle.py

Open up the file C:\python22\tools\idle and see what it is.  I would
guess (but I don't have windows or idle installed) that it is a batch
script or something.  You need to put the -Qnew option in there such
that _python_, not idle, gets the option.  Right now I think you are
giving idle the -Qnew option, and it really doesn't care.

-D

--

He who finds a wife finds what is good
    and receives favor from the Lord.
        Proverbs 18:22



From dsh8290@rit.edu  Mon Dec  3 15:53:55 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 10:53:55 -0500
Subject: [Tutor] class data
In-Reply-To: <Pine.LNX.4.33.0112031027180.17542-100000@fleet1.paxp.com>; from fleet@teachout.org on Mon, Dec 03, 2001 at 10:35:53AM -0500
References: <Pine.LNX.4.21.0112022022010.26319-100000@hkn.eecs.berkeley.edu> <Pine.LNX.4.33.0112031027180.17542-100000@fleet1.paxp.com>
Message-ID: <20011203105355.D18525@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 10:35:53AM -0500, fleet@teachout.org wrote:
| OK.  Using pickle and the associated example, I was able to save the class
| and restore it.  Either none of the data was saved or I don't know how to
| access it when the class is restored.
| 
| I don't see the utility in 'pickling' a class.  It's already saved in a
| module (addrbook.py).  I haven't tried it; but I suspect if I pickled the
| class, then deleted the addrbook.py module, I would no longer be able to
| unpickle the class.  Or did I miss something?

You want to (un)pickle the instance of the class.  That is where the
usefulness is.  And, yes, you do need to keep the source around in
order to successfully unpickle the objects.

Alternatively you could practice file IO and devise your own format
for persistantly storing the data.

-D

-- 

For society, it's probably a good thing that engineers value function
over appearance.  For example, you wouldn't want engineers to build
nuclear power plants that only _look_ like they would keep all the
radiation inside.
    (Scott Adams - The Dilbert principle)



From pythontutor@venix.com  Mon Dec  3 15:53:47 2001
From: pythontutor@venix.com (Lloyd Kvam)
Date: Mon, 03 Dec 2001 10:53:47 -0500
Subject: [Tutor] class data
References: <Pine.LNX.4.33.0112031027180.17542-100000@fleet1.paxp.com>
Message-ID: <3C0BA00B.4010709@venix.com>

addrbook.py contains the python instructions to implement the addressbook.  It does NOT contain
the data that makes up the addressbook.  pickling is used to save the data that was entered
using the addrbook module.

If you give someone your addrbook.py module, you are giving them a computer program.
You are NOT giving them your addressbook.

fleet@teachout.org wrote:

> OK.  Using pickle and the associated example, I was able to save the class
> and restore it.  Either none of the data was saved or I don't know how to
> access it when the class is restored.
> 
> I don't see the utility in 'pickling' a class.  It's already saved in a
> module (addrbook.py).  I haven't tried it; but I suspect if I pickled the
> class, then deleted the addrbook.py module, I would no longer be able to
> unpickle the class.  Or did I miss something?
> 
> 				- fleet -
> 
> On Sun, 2 Dec 2001, Danny Yoo wrote:
> 
> 
>>Ah!  Take a look at the 'pickle' module:
>>
>>    http://python.org/doc/lib/module-pickle.html
>>
>>'pickle' knows how to deal with instances, and will properly allow you to
>>save data structures as a byte stream.
>>
>>It doesn't work on pathological cases (like C extension modules or files),
>>at least, not without a bit of hacking with the 'copy_reg' module.
>>
>>Try it out, and if you have problems with it, please email the list, and
>>we can ferment an example.
>>
>>
> 
> 
> _______________________________________________
> 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 alan.gauld@bt.com  Mon Dec  3 16:14:38 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 3 Dec 2001 16:14:38 -0000
Subject: [Tutor] class data
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C150@mbtlipnt02.btlabs.bt.co.uk>

> Everything went fine until -

Hmm, I wasn't really meaning that to be real code!
However since Python is executable pseudo code...

> > class Entry:
> >    def __init__(s, nm,ph,em):
> >       s.name = nm
> >       s.phone = ph
> >       s.email = em
> >    def saveme(s,flnm):
> >       f = open(flnm,'a')
> >       f.write(`s.name`,'\t',`s.phone`,'\t',s.email`)

Oops, try 
          f.write(`s.name` + '\t' + `s.phone` + '\t' + s.email`)

Alan G


From tjenkins@devis.com  Mon Dec  3 16:44:53 2001
From: tjenkins@devis.com (Tom Jenkins)
Date: 03 Dec 2001 11:44:53 -0500
Subject: [Tutor] class data
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C150@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C150@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <1007397902.2916.33.camel@asimov>

On Mon, 2001-12-03 at 11:14, alan.gauld@bt.com wrote:
> > Everything went fine until -
> 
> Hmm, I wasn't really meaning that to be real code!
> However since Python is executable pseudo code...
> 
> > > class Entry:
> > >    def __init__(s, nm,ph,em):
> > >       s.name = nm
> > >       s.phone = ph
> > >       s.email = em
> > >    def saveme(s,flnm):
> > >       f = open(flnm,'a')
> > >       f.write(`s.name`,'\t',`s.phone`,'\t',s.email`)
> 
> Oops, try 
>           f.write(`s.name` + '\t' + `s.phone` + '\t' + s.email`)
> 

I like using variable substitution; so my version would be:
f.write('%s\t%s\t%s' % (s.name, s.phone, s.email))

or

f.write('%(nm)s\t%(ph)s\t%(em)s' % ({'nm':s.name, 'ph':s.phone,
'em':s.email}))

i prefer this as its hard to see that Alan is using backticks ( ` ) for
s.name, s.phone

-- 

Tom Jenkins
Development InfoStructure
http://www.devis.com




From alan.gauld@bt.com  Mon Dec  3 16:47:06 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 3 Dec 2001 16:47:06 -0000
Subject: [Tutor] class data
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C153@mbtlipnt02.btlabs.bt.co.uk>

> > >       f.write(`s.name`,'\t',`s.phone`,'\t',s.email`)
> 
> Oops, try 
>           f.write(`s.name` + '\t' + `s.phone` + '\t' + s.email`)
Or even:
            f.write(`s.name` + '\t' + `s.phone` + '\t' + `s.email`)
                                                         ^missing

Alan G


From fleet@teachout.org  Mon Dec  3 17:21:01 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Mon, 3 Dec 2001 12:21:01 -0500 (EST)
Subject: [Tutor] class data
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C153@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.33.0112031219340.17814-100000@fleet1.paxp.com>

On Mon, 3 Dec 2001 alan.gauld@bt.com wrote:

> > > >       f.write(`s.name`,'\t',`s.phone`,'\t',s.email`)
> >
> > Oops, try
> >           f.write(`s.name` + '\t' + `s.phone` + '\t' + s.email`)
> Or even:
>             f.write(`s.name` + '\t' + `s.phone` + '\t' + `s.email`)
>                                                          ^missing

Ok.  I figured *THAT* out on my own!!! :)

				- fleet -




From dsh8290@rit.edu  Mon Dec  3 17:39:38 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 12:39:38 -0500
Subject: [Tutor] class data
In-Reply-To: <1007397902.2916.33.camel@asimov>; from tjenkins@devis.com on Mon, Dec 03, 2001 at 11:44:53AM -0500
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C150@mbtlipnt02.btlabs.bt.co.uk> <1007397902.2916.33.camel@asimov>
Message-ID: <20011203123938.B19147@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 11:44:53AM -0500, Tom Jenkins wrote:
| On Mon, 2001-12-03 at 11:14, alan.gauld@bt.com wrote:
...
| > > > class Entry:
| > > >    def __init__(s, nm,ph,em):
| > > >       s.name = nm
| > > >       s.phone = ph
| > > >       s.email = em
| > > >    def saveme(s,flnm):
| > > >       f = open(flnm,'a')
| > > >       f.write(`s.name`,'\t',`s.phone`,'\t',s.email`)
| > 
| > Oops, try 
| >           f.write(`s.name` + '\t' + `s.phone` + '\t' + s.email`)
| > 
| 
| I like using variable substitution; so my version would be:
| f.write('%s\t%s\t%s' % (s.name, s.phone, s.email))
| 
| or
| 
| f.write('%(nm)s\t%(ph)s\t%(em)s' % ({'nm':s.name, 'ph':s.phone,
| 'em':s.email}))
| 
| i prefer this as its hard to see that Alan is using backticks ( ` ) for
| s.name, s.phone

I pick whichever style is clearest for the data I have at that time.
In this case the data should already be a string, so

f.write( s.name + "\t" + s.phone + "\t" + s.email )

would work, and has the least amount of noise (in this case).

There is also the alternative of using the str() function/factory
instead of backticks.  (Oh, but I don't remember if backticks call
str() or repr(), but you can use repr() if you want to be explicit)

I like string interpolation especially if I want some (stati) text
around the data, or if I want to format numbers.  The named
interpolation tends to just add noise for simple lines (like above),
but is great if the same data is to be output multiple times, or if it
comes as a dictionary already.

-D

-- 
 
How great is the love the Father has lavished on us,
that we should be called children of God!
        1 John 3:1 



From dsh8290@rit.edu  Mon Dec  3 17:51:39 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 12:51:39 -0500
Subject: [Tutor] performance considerations
Message-ID: <20011203125139.C19147@harmony.cs.rit.edu>

I'm working on a script/program to do some processing (munging) on
text files in a directory tree.  In addition, for convenience, all
non-interesting files are copied without munging.  My script, as it
stands, is quite CPU intensive so I would like to optimize it some.

In the case of copying non-interesting files, what is (generally) the
most efficient way?  It seems there is no system-level "copy" command.
Is there a better way than read each byte of the file and write it out
to the new file?  I suppose I could just create a hard link, if I am
willing to tie it down to Unix-only.  Does anyone have recommendations
on how many bytes I should read at a time?

A portion of the script generates strings by starting with 'a' and
"adding" to it.  Ie "a", "b", ..., "z", "aa", "ab", ..., "zz", "aaa".
Would it be better to use a list of one-char-strings than to modify a
single string?  Here's the code I have now (BTW, that funny-looking
"isinstance" stuff requires 2.2) (also I am certain that this is not
where most of the time is spent anyways) :

    def increment( s ) :
        """
        Increment the string.  Recursively "carries" if needed.
        """

        assert isinstance( s , str ) , "'s' must be a string"

        # a special case, for terminating recursion
        if s == "" :
            return "a"

        # the ordinal of the next character in succession
        next_ord = ord( s[-1] ) + 1

        # check for overflow
        if ord( 'a' ) <= next_ord <= ord( 'z' ) :
            s = s[:-1] + chr( next_ord )
        else :
            s = increment( s[:-1] ) + "a"
        return s
    # end increment()


One last question for now :
I traverse the interesting files line-by-line and check them for a
regex match, then modify the line if it matches properly.  Would it be
better (faster) to read in the whole file and treat it as a single
string?  Memory is not a problem.

TIA,
-D

-- 

It took the computational power of three Commodore 64s to fly to the moon.
It takes at least a 486 to run Windows 95.
Something is wrong here.



From glingl@aon.at  Mon Dec  3 17:51:20 2001
From: glingl@aon.at (Gregor Lingl)
Date: Mon, 3 Dec 2001 18:51:20 +0100
Subject: [Tutor] Division
References: <LNBBLJKPBEHFEDALKOLCEEHBMKAA.tim.one@home.com> <001001c17bc6$8adf0fe0$1664a8c0@mega> <20011203105124.C18525@harmony.cs.rit.edu>
Message-ID: <001701c17c23$1e3a6e90$1664a8c0@mega>

Oh! (*flush!* (red))

What a mistake!
I wanted to say:

C:\python22\tools\python -Qnew idle.py
                                 ^^^^^^^^
doesn't work

(And it doesn't!)

Gregor


----- Original Message ----- 
From: "dman" <dsh8290@rit.edu>
To: <tutor@python.org>
Sent: Monday, December 03, 2001 4:51 PM
Subject: Re: [Tutor] Division


> On Mon, Dec 03, 2001 at 07:48:40AM +0100, Gregor Lingl wrote:
> | Dear Tim!
> | 
> | Thanks! This works fine.
> | 
> | But unfortunataly there remains the problem of starting
> | IDLE - which I use to use with my students - in this new mode:
> | 
> | C:\python22\tools\idle -Qnew idle.py
                             ************
> 
> Open up the file C:\python22\tools\idle and see what it is.  I would
> guess (but I don't have windows or idle installed) that it is a batch
> script or something.  You need to put the -Qnew option in there such
> that _python_, not idle, gets the option.  Right now I think you are
> giving idle the -Qnew option, and it really doesn't care.
> 
> -D
> 
> --
> 
> He who finds a wife finds what is good
>     and receives favor from the Lord.
>         Proverbs 18:22
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



From fleet@teachout.org  Mon Dec  3 17:44:59 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Mon, 3 Dec 2001 12:44:59 -0500 (EST)
Subject: [Tutor] Follow up to 'class data'
Message-ID: <Pine.LNX.4.33.0112031221060.17814-100000@fleet1.paxp.com>

I think I'm stuck in the "just don't get it" class (pun intentional).

"Everything is an object" includes, I guess classes.

So to me, the address book is an object and can be a class?

But the example seems to ignore "address book" and describes the means of
adding, modifying, deleting data as classes.  ??

I would have thought "address book" would be the class and the means of
adding, modifying, deleting data would be "methods."

Since the actual data (names, addresses, phone numbers, e-mail addresses,
etc.) will need to be stored in dictionaries, lists, text files, etc.,
what is the advantage of using classes as opposed to functions.  Or are we
just talking about 'another way to do it?'

The structure as I see it would be something like:

class AddressBook:
   def input:
   def modify:
   def delete:
   def search:
   def sort:
   def output:

Should I be looking at something like:

class AddressBook:
   class Input(AddressBook):
      def inputName:
      def inputAddress:
      def inputPhone:

etc.

				- fleet -



From fleet@teachout.org  Mon Dec  3 17:52:15 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Mon, 3 Dec 2001 12:52:15 -0500 (EST)
Subject: [Tutor] class data
In-Reply-To: <3C0BA00B.4010709@venix.com>
Message-ID: <Pine.LNX.4.33.0112031250370.17846-100000@fleet1.paxp.com>

This was my understanding of it also; but classes apparently contain their
own __dict__.  I was kind of hoping it would get pickled along with the
rest.  If it did, I have no clue how to access the data.

				- fleet -

On Mon, 3 Dec 2001, Lloyd Kvam wrote:

> addrbook.py contains the python instructions to implement the addressbook.  It does NOT contain
> the data that makes up the addressbook.  pickling is used to save the data that was entered
> using the addrbook module.
>
> If you give someone your addrbook.py module, you are giving them a computer program.
> You are NOT giving them your addressbook.



From tim.one@home.com  Mon Dec  3 18:03:41 2001
From: tim.one@home.com (Tim Peters)
Date: Mon, 3 Dec 2001 13:03:41 -0500
Subject: [Tutor] Division
In-Reply-To: <001701c17c23$1e3a6e90$1664a8c0@mega>
Message-ID: <LNBBLJKPBEHFEDALKOLCMELBMKAA.tim.one@home.com>

[Gregor Lingl]
> Oh! (*flush!* (red))
>
> What a mistake!
> I wanted to say:
>
> C:\python22\tools\python -Qnew idle.py
>                                ^^^^^^^
> doesn't work
>
> (And it doesn't!)

You're right, it doesn't work -- Guido and I are looking into why (it's a
mystery so far!).

When that's fixed, note that you should never run a Tkinter app on Windows
with python.exe:  a Tk bug can cause unpredictable system hangs on Win9x
when the app shuts down.  You'll want to use pythonw.exe and idle.pyw
instead.



From ak@silmarill.org  Mon Dec  3 18:07:13 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 03 Dec 2001 13:07:13 -0500
Subject: [Tutor] Follow up to 'class data'
In-Reply-To: <Pine.LNX.4.33.0112031221060.17814-100000@fleet1.paxp.com>
References: <Pine.LNX.4.33.0112031221060.17814-100000@fleet1.paxp.com>
Message-ID: <20011203130713.A26805@sill.silmarill.org>

On Mon, Dec 03, 2001 at 12:44:59PM -0500, fleet@teachout.org wrote:
> I think I'm stuck in the "just don't get it" class (pun intentional).
> 
> "Everything is an object" includes, I guess classes.
> 
> So to me, the address book is an object and can be a class?
> 
> But the example seems to ignore "address book" and describes the means of
> adding, modifying, deleting data as classes.  ??
> 
> I would have thought "address book" would be the class and the means of
> adding, modifying, deleting data would be "methods."
> 
> Since the actual data (names, addresses, phone numbers, e-mail addresses,
> etc.) will need to be stored in dictionaries, lists, text files, etc.,
> what is the advantage of using classes as opposed to functions.  Or are we
> just talking about 'another way to do it?'

Well, classes "hide" data so that it's harder to mess it up by mistake.
The fancy name for this is data incapsulation, I think. You could also
subclass address book. Read some thick book on OOP, if you really want
to..

I also find that it makes for more readable code if you use classes. For
instance, in my pybook (e-books reader) app, I at first had a bunch of
global vars and functions, so local_books list, and read_last() method,
and so on.. now, I have books.local list, and books.read_last() method,
so I can think in terms of having this big blob "books" that I can apply
actions to.

In addition, if you have some data you want to change in your function
and you aren't using classes, you'll either have to use it as global or
pass it in functions and return it back. Either option adds unnecessary
clutter to the program, and globals just feel wrong..

Now OO gurus will have a heart attack because I like classes for all the
wrong reasons ;-P.

> 
> The structure as I see it would be something like:
> 
> class AddressBook:
>    def input:
>    def modify:
>    def delete:
>    def search:
>    def sort:
>    def output:
> 
> Should I be looking at something like:
> 
> class AddressBook:
>    class Input(AddressBook):
>       def inputName:
>       def inputAddress:
>       def inputPhone:
> 
> etc.
> 
> 				- fleet -


> 
> 
> _______________________________________________
> 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  Mon Dec  3 18:10:41 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 03 Dec 2001 13:10:41 -0500
Subject: [Tutor] performance considerations
In-Reply-To: <20011203125139.C19147@harmony.cs.rit.edu>
References: <20011203125139.C19147@harmony.cs.rit.edu>
Message-ID: <20011203131041.B26805@sill.silmarill.org>

On Mon, Dec 03, 2001 at 12:51:39PM -0500, dman wrote:
> 
> I'm working on a script/program to do some processing (munging) on
> text files in a directory tree.  In addition, for convenience, all
> non-interesting files are copied without munging.  My script, as it
> stands, is quite CPU intensive so I would like to optimize it some.
> 
> In the case of copying non-interesting files, what is (generally) the
> most efficient way?  It seems there is no system-level "copy" command.

shutil.copy()

> Is there a better way than read each byte of the file and write it out
> to the new file?  I suppose I could just create a hard link, if I am
> willing to tie it down to Unix-only.  Does anyone have recommendations
> on how many bytes I should read at a time?
> 
> A portion of the script generates strings by starting with 'a' and
> "adding" to it.  Ie "a", "b", ..., "z", "aa", "ab", ..., "zz", "aaa".
> Would it be better to use a list of one-char-strings than to modify a
> single string?  Here's the code I have now (BTW, that funny-looking

I believe so.. profile!

> "isinstance" stuff requires 2.2) (also I am certain that this is not
> where most of the time is spent anyways) :
> 
>     def increment( s ) :
>         """
>         Increment the string.  Recursively "carries" if needed.
>         """
> 
>         assert isinstance( s , str ) , "'s' must be a string"
> 
>         # a special case, for terminating recursion
>         if s == "" :
>             return "a"
> 
>         # the ordinal of the next character in succession
>         next_ord = ord( s[-1] ) + 1
> 
>         # check for overflow
>         if ord( 'a' ) <= next_ord <= ord( 'z' ) :
>             s = s[:-1] + chr( next_ord )
>         else :
>             s = increment( s[:-1] ) + "a"
>         return s
>     # end increment()
> 
> 
> One last question for now :
> I traverse the interesting files line-by-line and check them for a
> regex match, then modify the line if it matches properly.  Would it be
> better (faster) to read in the whole file and treat it as a single
> string?  Memory is not a problem.

Yeah, probably.. profile!

> 
> TIA,
> -D
> 
> -- 
> 
> It took the computational power of three Commodore 64s to fly to the moon.
> It takes at least a 486 to run Windows 95.
> Something is wrong here.
> 
> 
> _______________________________________________
> 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 dsh8290@rit.edu  Mon Dec  3 18:13:26 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 13:13:26 -0500
Subject: [Tutor] class data
In-Reply-To: <Pine.LNX.4.33.0112031250370.17846-100000@fleet1.paxp.com>; from fleet@teachout.org on Mon, Dec 03, 2001 at 12:52:15PM -0500
References: <3C0BA00B.4010709@venix.com> <Pine.LNX.4.33.0112031250370.17846-100000@fleet1.paxp.com>
Message-ID: <20011203131326.A19344@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 12:52:15PM -0500, fleet@teachout.org wrote:
| This was my understanding of it also; but classes apparently contain their
| own __dict__.  

Classes have a dictionary that only contains the methods and class
members.  Class _instances_ have a __dict__ that contains the data
stored by the instance.

| I was kind of hoping it would get pickled along with the rest. 

It does -- it is part of the data.

| If it did, I have no clue how to access the data.

The same way you always do.  Here's an example (that skips the file
read/write step) :


import pickle

class C :
    pass

o = C()
o.foo = "bar"
o.spam = "eggs"

pickled_string = pickle.dumps( o )

# normally you would write this string to a file, or a socket, or something

del o # just to make sure the old one is gone and I can't make a typo

# normally you would read the string from a file, or a socket, or something
obj = pickle.loads( pickled_string )

print obj.foo , obj.spam


-D

-- 

(E)very (M)inor (A)ttention (C)osts (S)anity



From tim.one@home.com  Mon Dec  3 18:16:59 2001
From: tim.one@home.com (Tim Peters)
Date: Mon, 3 Dec 2001 13:16:59 -0500
Subject: [Tutor] Division
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C14A@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <LNBBLJKPBEHFEDALKOLCCELEMKAA.tim.one@home.com>

[alan.gauld@bt.com]
> Just one point is that maybe for an education in programming
> they should use the old style division behaviour - its how
> the vast majority of programming languages work and is a
> great way to see how the computer is working under the covers.

Actually, truncating integer division is largely confined to C and Fortran
and their derivatives.  The list of languages that don't truncate starts
with Algol 60 and Lisp, and includes JavaScript, Visual Basic, Perl, PHP,
Smalltalk, AWK, Prolog, Pascal, COBOL, ABC, and Python with -Qnew <wink>.



From dsh8290@rit.edu  Mon Dec  3 18:24:58 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 13:24:58 -0500
Subject: [Tutor] Division
In-Reply-To: <LNBBLJKPBEHFEDALKOLCMELBMKAA.tim.one@home.com>; from tim.one@home.com on Mon, Dec 03, 2001 at 01:03:41PM -0500
References: <001701c17c23$1e3a6e90$1664a8c0@mega> <LNBBLJKPBEHFEDALKOLCMELBMKAA.tim.one@home.com>
Message-ID: <20011203132458.B19344@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 01:03:41PM -0500, Tim Peters wrote:
| [Gregor Lingl]
| > Oh! (*flush!* (red))
| >
| > What a mistake!
| > I wanted to say:
| >
| > C:\python22\tools\python -Qnew idle.py
| >                                ^^^^^^^
| > doesn't work
| >
| > (And it doesn't!)

I installed IDLE for you (though I'm on a debian box, not windows) and
traced through how it executes stuff.

| You're right, it doesn't work -- Guido and I are looking into why (it's a
| mystery so far!).
 
It uses an instance of code.InteractiveInterpreter (built-in stuff)
which uses codeop.CommandCompiler.  The __future__ statement stuff
works, as the comment says it does.

It seems that the bug is somewhere down in the built-in compile()
function.

Anyways, put

        self.interp.runsource( "from __future__ import division" )

on line 353 of PyShell.py for a quick "fix".  It should be the last
statement of the __init__ method.

-D

-- 

Q: What is the difference betwee open-source and commercial software?
A: If you have a problem with commercial software you can call a phone
   number and they will tell you it might be solved in a future version.
   For open-source sofware there isn't a phone number to call, but you
   get the solution within a day.



From dsh8290@rit.edu  Mon Dec  3 18:31:13 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 13:31:13 -0500
Subject: [Tutor] performance considerations
In-Reply-To: <20011203131041.B26805@sill.silmarill.org>; from sill@optonline.net on Mon, Dec 03, 2001 at 01:10:41PM -0500
References: <20011203125139.C19147@harmony.cs.rit.edu> <20011203131041.B26805@sill.silmarill.org>
Message-ID: <20011203133113.C19344@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 01:10:41PM -0500, Andrei Kulakov wrote:
| On Mon, Dec 03, 2001 at 12:51:39PM -0500, dman wrote:
| > 
| > I'm working on a script/program to do some processing (munging) on
| > text files in a directory tree.  In addition, for convenience, all
| > non-interesting files are copied without munging.  My script, as it
| > stands, is quite CPU intensive so I would like to optimize it some.
| > 
| > In the case of copying non-interesting files, what is (generally) the
| > most efficient way?  It seems there is no system-level "copy" command.
| 
| shutil.copy()

Cool, thanks.

| > A portion of the script generates strings by starting with 'a' and
| > "adding" to it.  Ie "a", "b", ..., "z", "aa", "ab", ..., "zz", "aaa".
| > Would it be better to use a list of one-char-strings than to modify a
| > single string?  Here's the code I have now (BTW, that funny-looking

I forgot to mention, if a list of strings is used, each yield will
yield  "".join( the_list ), so the comparison is the multiple
modifications (creation) of strings versus join.

| I believe so.. profile!

I should.

| > One last question for now :
| > I traverse the interesting files line-by-line and check them for a
| > regex match, then modify the line if it matches properly.  Would it be
| > better (faster) to read in the whole file and treat it as a single
| > string?  Memory is not a problem.
| 
| Yeah, probably.. profile!

I want to speculate before I rewrite it :-).  Maybe Tim will tell me
something (since he is so familiar with the inner workings)?

-D

-- 

How to shoot yourself in the foot with Java:

You find that Microsoft and Sun have released imcompatible class
libraries both implementing Gun objects. You then find that although
there are plenty of feet objects implemented in the past in many other
languages, you cannot get access to one. But seeing as Java is so cool,
you dont care and go around shooting anything else you can find.
    (written by Mark Hammond)



From ak@silmarill.org  Mon Dec  3 18:37:50 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 03 Dec 2001 13:37:50 -0500
Subject: [Tutor] performance considerations
In-Reply-To: <20011203133113.C19344@harmony.cs.rit.edu>
References: <20011203125139.C19147@harmony.cs.rit.edu>
 <20011203131041.B26805@sill.silmarill.org>
 <20011203133113.C19344@harmony.cs.rit.edu>
Message-ID: <20011203133750.A27060@sill.silmarill.org>

On Mon, Dec 03, 2001 at 01:31:13PM -0500, dman wrote:
> On Mon, Dec 03, 2001 at 01:10:41PM -0500, Andrei Kulakov wrote:
> | On Mon, Dec 03, 2001 at 12:51:39PM -0500, dman wrote:
> | > 
> | > I'm working on a script/program to do some processing (munging) on
> | > text files in a directory tree.  In addition, for convenience, all
> | > non-interesting files are copied without munging.  My script, as it
> | > stands, is quite CPU intensive so I would like to optimize it some.
> | > 
> | > In the case of copying non-interesting files, what is (generally) the
> | > most efficient way?  It seems there is no system-level "copy" command.
> | 
> | shutil.copy()
> 
> Cool, thanks.
> 
> | > A portion of the script generates strings by starting with 'a' and
> | > "adding" to it.  Ie "a", "b", ..., "z", "aa", "ab", ..., "zz", "aaa".
> | > Would it be better to use a list of one-char-strings than to modify a
> | > single string?  Here's the code I have now (BTW, that funny-looking
> 
> I forgot to mention, if a list of strings is used, each yield will
> yield  "".join( the_list ), so the comparison is the multiple
> modifications (creation) of strings versus join.

Yeah, that's what I thought.. I think I remember someone saying that one
join would be much faster.

> 
> | I believe so.. profile!
> 
> I should.
> 
> | > One last question for now :
> | > I traverse the interesting files line-by-line and check them for a
> | > regex match, then modify the line if it matches properly.  Would it be
> | > better (faster) to read in the whole file and treat it as a single
> | > string?  Memory is not a problem.
> | 
> | Yeah, probably.. profile!
> 
> I want to speculate before I rewrite it :-).  Maybe Tim will tell me
> something (since he is so familiar with the inner workings)?
> 
> -D
> 
> -- 
> 
> How to shoot yourself in the foot with Java:
> 
> You find that Microsoft and Sun have released imcompatible class
> libraries both implementing Gun objects. You then find that although
> there are plenty of feet objects implemented in the past in many other
> languages, you cannot get access to one. But seeing as Java is so cool,
> you dont care and go around shooting anything else you can find.
>     (written by Mark Hammond)
> 
> 
> _______________________________________________
> 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  Mon Dec  3 18:43:54 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 03 Dec 2001 10:43:54 -0800
Subject: [Tutor] Re: Tutor digest, Vol 1 #1239 - 11 msgs
References: <E16AwSr-0005ve-00@mail.python.org>
Message-ID: <3C0BC7EA.93FAC9D@ccvcorp.com>

>
>
> Message: 3
> Date: Mon, 3 Dec 2001 09:37:52 -0500 (EST)
> From:  <fleet@teachout.org>
> Reply-To:  <fleet@teachout.org>
> To:  <alan.gauld@bt.com>
> cc: python tutor list <tutor@python.org>
> Subject: RE: [Tutor] class data
>
> Everything went fine until -
>
> >>> for e in book:
> ...    e.saveme('book.txt')
> ...
> Traceback (innermost last):
>   File "<stdin>", line 2, in ?
>   File "<stdin>", line 8, in saveme
> TypeError: read-only buffer, tuple
>
>                                 - fleet -
>
> On Mon, 3 Dec 2001 alan.gauld@bt.com wrote:
> > book = []
> > for i in range(10):
> >    book.append(Entry('al','1234','ag.co.com')

The problem is that this line is short a paren---

... book.append( Entry('al','1234','ag.co.com') ) # <-- two of each paren

Without that closing paren, the interpreter was trying to read *everything* after that as part of a
tuple... with obvious problems.  :)

(I don't know if IDLE does this, but PythonWin will automatically highlight matching parens--this
is a *very* handy little feature.)

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Mon Dec  3 20:22:28 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 03 Dec 2001 12:22:28 -0800
Subject: [Tutor] Follow up to 'class data'
References: <E16Axzc-0003NA-00@mail.python.org>
Message-ID: <3C0BDF04.7410989@ccvcorp.com>

> On Mon, 3 Dec 2001 12:44:59 -0500 (EST),
> <fleet@teachout.org> wrote:

>
> I think I'm stuck in the "just don't get it" class (pun intentional).
>
> "Everything is an object" includes, I guess classes.
>
> So to me, the address book is an object and can be a class?
>
> But the example seems to ignore "address book" and describes the means of adding, modifying,
> deleting data as classes.  ??
>
> I would have thought "address book" would be the class and the means of
> adding, modifying, deleting data would be "methods."

I think that what's confusing you here (in part), is that there is a difference between a "class
object" and a "class instance" (also known as an instance object).

A class definition is an object, just as a function is an object, and you can pass class definitions
around just like you can pass function references.  You probably will rarely (if ever) need to do
this, though.

When you go to *use* a class, you typically create one or more *instances* from that class.  Each of
those instances, has its own store of data.

As an example, I can create a Person class, and list all sorts of things that a Person can do.  I can
even, if I really want, let someone else modify the list of things that a Person can do.  But when I
want to actually *use* a Person, I don't use Person itself, I create instances of Person, such as
"John", "Terry", "Michael", etc, and then have each of those instances do something.  Each instance
may well have different attributes (probably self.name is different for each, among other things).

When you pickled your class, if you were pickling the *class object*, then you're right, that serves
little purpose beyond what having the .py file does.  You really want to pickle each of the
*instance* objects, which combine the standard actions (methods) defined in the class, with the
specific data (attributes) that belong with that particular instance.

Jeff Shannon
Technician/Programmer
Credit International




From dyoo@hkn.eecs.berkeley.edu  Mon Dec  3 20:17:34 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 3 Dec 2001 12:17:34 -0800 (PST)
Subject: [Tutor] Newbie Question:  IDLE, is there a HOWTO use...
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C148@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.21.0112031215420.16701-100000@hkn.eecs.berkeley.edu>

On Mon, 3 Dec 2001 alan.gauld@bt.com wrote:

> > So far, I have used the IDLE to edit py's but it seems that 
> > there is more to it than that.
> 
> IDLE also has debugging tools and class browsing tools.
> But the vast majority of use is just to create and run .py files.
> 
> > Is there a HOWTO for the use of IDLE?
> 
> There is a tutorial on the IDLE section of the python.org web site.
> 
> Danny was doing a tutor too I think? But I don't have his url.

Here's the URL:

    http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html



From G.Kruschina@gmx.de  Mon Dec  3 20:27:02 2001
From: G.Kruschina@gmx.de (Guenter Kruschina)
Date: Mon, 3 Dec 2001 21:27:02 +0100
Subject: [Tutor] Re: How to compare text?
In-Reply-To: <3C0B5C9C.10969.755101@localhost>
Message-ID: <3C0BEE26.5908.1B94372@localhost>

--Message-Boundary-26703
Content-type: text/plain; charset=ISO-8859-1
Content-transfer-encoding: Quoted-printable
Content-description: Mail message body

From:           	"A" <printers@sendme.cz>
To:             	tutor@python.org, activepython@listserv.ActiveState.com,
  	python-list@python.org
Subject:        	How to compare text?
Send reply to:  	printers@sendme.cz
Priority:       	normal
Date sent:      	Mon, 3 Dec 2001 11:06:04 +0100

> 
> Hello,
> How can I compare of one  parragraph of text with another
> paragraph?Each paragraph can have about 100 words.
> For example I have the first paragraph
> 
> I want to be very good at Python programming. Better than in Perl.
> 
> THe second paragraph might look loke this:
> 
> She works all day long to master Perl.
> 
> All that I need is to find out if any of word from the second is in the 
> first paragraph. For the example above I should find out word
> 
> Perl
> 
> 
> What is the best and quickest way?
> Thank you for help.
> Ladislav
> 
> 
> _______________________________________________
> ActivePython mailing list
> ActivePython@listserv.ActiveState.com
> http://listserv.ActiveState.com/mailman/listinfo/activepython
> 


Hallo Ladislav, I have written a small progam, which will work as you expe=
ct. I 
hope so. I think this is a fast way to compare two paragraphs.

wbg
G=FCnter



--Message-Boundary-26703
Content-type: text/plain; charset=US-ASCII
Content-transfer-encoding: 7BIT
Content-description: Text from file 'diff.py'



def CreateDict(par):
            
   
   #Remove some chars
   for char in ('.',';',','):
        par = par.replace(char,"")
                                
    
                                
   words = par.split(' ')                                   
   dPar = {}
    
   for word in words:
       dPar[word] = 1

   return dPar       


def Diff(par1,par2):
    
    dPar1 = CreateDict(par1) 
    dPar2 = CreateDict(par2)
     
    lCommon = [] 
    for word in dPar2.keys():
        if dPar1.has_key(word):
            lCommon.append(word)  
            
    return lCommon    
        
    


 
 
 
 
def main(): 
    lCommonWords = Diff("I want to be very good at Python programming. Better than in Perl.",
        "She works all day long to master Perl.")        
        
    print "Common Words: ", lCommonWords        
    
 
main()    
--Message-Boundary-26703--


From fleet@teachout.org  Mon Dec  3 20:51:31 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Mon, 3 Dec 2001 15:51:31 -0500 (EST)
Subject: [Tutor] (no subject)
Message-ID: <Pine.LNX.4.33.0112031523040.18409-100000@fleet1.paxp.com>


Your example below works; but when I try something like:

john = class('john doe','123-456-6789')
jane = class('jane doe','123-456-9876')

I can pickle john, or I can pickle jane; but I don't seem to be able to
pickle both.  I'm assuming to do this I need to store the data in a
dictionary (or something) and pickle the dictionary (or something).

Actually, having pondered this through three screensaver activations (or
so) it appears I would have to store the *instance* in a dictionary - not
the name or phone number; but just "john."

>>> john
<addrbook.AddrBookEntry instance at 80e62b0>

But would this be valid for different sessions of Python?

				- fleet -

dman <dsh8290@rit.edu said:

>Classes have a dictionary that only contains the methods and class
>members.  Class _instances_ have a __dict__ that contains the data
>stored by the instance.
>
>| I was kind of hoping it would get pickled along with the rest.
>
>It does -- it is part of the data.
>
>| If it did, I have no clue how to access the data.
>
>The same way you always do.  Here's an example (that skips the file
>read/write step) :
>
>
>import pickle
>
>class C :
>    pass
>
>o = C()
>o.foo = "bar"
>o.spam = "eggs"
>
>pickled_string = pickle.dumps( o )
>
># normally you would write this string to a file, or a socket, or
>something






From sburch@ordway.org  Mon Dec  3 21:30:08 2001
From: sburch@ordway.org (Burchill, Scott B.)
Date: Mon, 3 Dec 2001 15:30:08 -0600
Subject: [Tutor] Too many open files
Message-ID: <EA7067EE4084D31186E308002BC33FC10881FE@overture.ordway.org>

I have a small program which uses recursion while dealing with a flat file
database.  I am opening and closing a number of files repeatedly during this
recursion and I feel like I have done the closing needed but I am still
being faced with a "too many files open" error.

My questions:  Is there a variable I can reference which holds the number of
open files?  How can I find out what the maximum number of open files is for
my system?

I am running as follows:
Python 2.1.1 (#1, Sep  4 2001, 12:16:58)
[GCC 3.0] on sunos5

Thanks loads in advance for any help!

sbb

--
Scott B. Burchill
Ordway Center for the Performing Arts
345 Washington Street
St. Paul, MN  55102-1495

voice +1 (651) 282-3023
cell  +1 (651) 248-2713
fax   +1 (651) 224-5319
efax  +1 (508) 519-6133

http://www.ordway.org

\:)>
 /:(>



From Bruce.Lee-Shanok@cognos.com  Mon Dec  3 21:29:15 2001
From: Bruce.Lee-Shanok@cognos.com (Lee-Shanok, Bruce)
Date: Mon, 3 Dec 2001 16:29:15 -0500
Subject: [Tutor] Setting Python version for IDLE
Message-ID: <FB15E670DA55D51185350008C786514A0140EAC4@sottexch1.cognos.com>

I have multiple versions of Python sitting on my machine at the moment. I'm
wondering how to specify which one my installed version of IDLE points to by
default...

Anyone know where I should be looking?

This message may contain privileged and/or confidential information.  If you
have received this e-mail in error or are not the intended recipient, you
may not use, copy, disseminate, or distribute it; do not open any
attachments, delete it immediately from your system and notify the sender by
e-mail promptly that you have done so.  Thank You.


From glingl@aon.at  Mon Dec  3 22:28:26 2001
From: glingl@aon.at (Gregor Lingl)
Date: Mon, 3 Dec 2001 23:28:26 +0100
Subject: [Tutor] Division
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C14A@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <003d01c17c49$d3eb13e0$1664a8c0@mega>

Thanks for this argument. I did some considerations
on this topic for myself.

My experience is, that my students understand well this
overloading of /, but they tend to forget it when writing
some useful programs doing some maths. Especially when
using the input-statement one often arrives at integers 
unintentionally. So should we type-cast every input with
float or resort only to use raw_input?

On the other hand the main point here is the difference between
two kinds of division, which of course must be taught - and perhaps
can be taught more easily - also in the python -Qnew interpreter.
If those two are accomplished by two different operators or
by a single overloaded one is -  IMHO ;-)  - secondary to that.

Thanks another time for the discussion

Gregor
 

----- Original Message ----- 
From: <alan.gauld@bt.com>
To: <tim.one@home.com>; <glingl@aon.at>; <tutor@python.org>
Sent: Monday, December 03, 2001 2:23 PM
Subject: RE: [Tutor] Division


> > > As I'm starting to give a new course 'Introduction to
> > > programming' in Jan 2002. It's for young students in the
> > > age of 15/16. (Of course) I shall use Python.
> > > I'd consider it an advantage not to confuse my students
> > > in the beginning with the specialities the overlaoding of 
> > > the division-operator (although I had to do so for several times
> > > until now). But neither with the import from future
> > > statement.
> 
> Just one point is that maybe for an education in programming 
> they should use the old style division behaviour - its how 
> the vast majority of programming languages work and is a 
> great way to seehow the computer is working under the covers.
> 
> If you want to use programming as part of another topic then 
> use new division but if you want to teach programming 
> principles stick to old style - its much more univesally 
> applicable and infornative IMHO.
> 
> Alan G
> 



From rick@niof.net  Mon Dec  3 21:39:38 2001
From: rick@niof.net (Rick Pasotto)
Date: Mon, 3 Dec 2001 16:39:38 -0500
Subject: [Tutor] thread locks
Message-ID: <20011203163938.B1113@tc.niof.net>

If the first thing I do in a long running function is to acquire a
lock, can I be guaranteed that the first statement after lauching
that function as a thread can accurately check for the existence
of the lock?

include thread,time
mutex = thread.allocate_lock()
def func():
	mutex.acquire()
	# do lots of stuff
	mutex.release()

thread.start_new(func,())
while 1:
	if mutex.locked():
		time.sleep(1)
	else:
		break
# thread has finished so I can do other things

I know this seems to defeat the purpose of using a thread but this is
in a Tkinter program and if I don't do this the main window will not
get redrawn if the user covers it up, etc.

Or is there a better way to solve my problem?

-- 
To tamper with man's freedom is not only to injure him, to degrade
him; it is to change his nature, to render him, in so far as such
oppression is exercised, incapable of improvement; it is to strip
him of his resemblance to the Creator, to stifle within him the
noble breath of life with which he was endowed at his creation.
	-- Frédéric Bastiat (1801-1850)
    Rick Pasotto    rickp@telocity.com    http://www.niof.net


From wsf@fultondesigns.co.uk  Mon Dec  3 22:30:05 2001
From: wsf@fultondesigns.co.uk (William S Fulton)
Date: Mon, 3 Dec 2001 22:30:05 -0000
Subject: [Tutor] Re: [Swig] Installation problems
References: <3C0B4DBD.37617612@gmx.de>
Message-ID: <009301c17c4e$ea6fe6e0$0b00a8c0@leopard>

> I want to generate a python shadow class from an excisting c++ file by
> using SWIG and VC++ 6.0 under Windows 2000 and i think that something
> went wrong with the installation of SWIG under VC++. Can anyone give me
> an advise where i can find detailed information of the installation
> process ? It seems that there are some binding problems of SWIG with
> VC++.
Download swigwin-1.3.9 by selecting 'All Releases' at
http://www.swig.org/download.html. Read the ReadmeWindows.txt file with the
download, it tells you everything you need to know - you will also have to
download the main swig-1.3.9 package as per instructions in the readme file.

Cheers
William



From dsh8290@rit.edu  Tue Dec  4 00:33:11 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 19:33:11 -0500
Subject: [Tutor] Division
In-Reply-To: <003d01c17c49$d3eb13e0$1664a8c0@mega>; from glingl@aon.at on Mon, Dec 03, 2001 at 11:28:26PM +0100
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C14A@mbtlipnt02.btlabs.bt.co.uk> <003d01c17c49$d3eb13e0$1664a8c0@mega>
Message-ID: <20011203193311.D19633@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 11:28:26PM +0100, Gregor Lingl wrote:
| Thanks for this argument. I did some considerations
| on this topic for myself.
| 
| My experience is, that my students understand well this
| overloading of /, but they tend to forget it when writing
| some useful programs doing some maths. Especially when
| using the input-statement one often arrives at integers 
| unintentionally. So should we type-cast every input with

More of a technicality, but there is no type-casting in python.  The
sole purpose of a type cast is to inform the compiler of a statically
typed language (eg C, C++, Java) that you think/want to have something
of a different type that the compiler thinks you have.  In python what
you have are conversion functions that actually do a conversion of the
object.

| float or resort only to use raw_input?

For simple programs or where input is assumed to be valid, input() is
functional.  In any other situation, use raw_input().  Once you have
the data via raw_input() you can convert it to whatever internal types
you want (eg floats) and also perform proper error checking.  A common
example of the pitfalls of using input() is if the user entered
    open( "some_file_you_dont_want_to_delete" , "w" )

This would give you back a file object, not a number, and also have
the effect of truncating the file to size 0 if it already existed.

-D

-- 

(E)scape (M)eta (A)lt (C)ontrol (S)hift



From urnerk@qwest.net  Tue Dec  4 00:42:22 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 03 Dec 2001 16:42:22 -0800
Subject: [Tutor] Division
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C14A@mbtlipnt02.btlabs
 .bt.co.uk>
Message-ID: <4.2.0.58.20011203164100.00c49b10@pop3.norton.antivirus>

>
>If you want to use programming as part of another topic then
>use new division but if you want to teach programming
>principles stick to old style - its much more univesally
>applicable and infornative IMHO.
>
>Alan G

Not so sure about this in light of Tim's recent remark:

    Actually, truncating integer division is largely confined
    to C and Fortran and their derivatives.  The list of
    languages that don't truncate starts with Algol 60 and
    Lisp, and includes JavaScript, Visual Basic, Perl, PHP,
    Smalltalk, AWK, Prolog, Pascal, COBOL, ABC, and Python
    with -Qnew <wink>.

Seems one can justify going either way, even if "programming
principles" is the yardstick.

Kirby



From dsh8290@rit.edu  Tue Dec  4 00:52:21 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 19:52:21 -0500
Subject: [Tutor] additional persistence questions
In-Reply-To: <Pine.LNX.4.33.0112031523040.18409-100000@fleet1.paxp.com>; from fleet@teachout.org on Mon, Dec 03, 2001 at 03:51:31PM -0500
References: <Pine.LNX.4.33.0112031523040.18409-100000@fleet1.paxp.com>
Message-ID: <20011203195221.E19633@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 03:51:31PM -0500, fleet@teachout.org wrote:
| 
| 
| Your example below works; but when I try something like:
| 
| john = class('john doe','123-456-6789')
| jane = class('jane doe','123-456-9876')
| 
| I can pickle john, or I can pickle jane; but I don't seem to be able to
| pickle both.

Care to share your code?  (btw, that can't be your real code, 'class'
is a keyword ;-))

--- demo.py ---
import pickle
from cStringIO import StringIO

class ABookEntry :
    def __init__( self , name , phone ) :
        self.name = name
        self.phone = phone

    def __str__( self ) :
        return "%s %s" % ( self.name , self.phone )

john = ABookEntry( "john" , "123-4567" )
jane = ABookEntry( "jane" , "765-4321" )

print john , jane

f = StringIO() # this is a file-like object, but in memory only
pickle.dump( john , f )
pickle.dump( jane , f )

del john , jane

f.seek( 0 ) # go back to the beginning, as if it was just opened

jo = pickle.load( f )
ja = pickle.load( f )

print jo , ja
---------------

$ python demo.py 
john 123-4567 jane 765-4321
john 123-4567 jane 765-4321


Looking closer at the docs, the 'loads()' function only unpickles the
first object in the string and ignores the rest.


| I'm assuming to do this I need to store the data in a
| dictionary (or something) and pickle the dictionary (or something).
| 
| Actually, having pondered this through three screensaver activations (or
| so) it appears I would have to store the *instance* in a dictionary - not
| the name or phone number; but just "john."
| 
| >>> john
| <addrbook.AddrBookEntry instance at 80e62b0>

You don't need to create a dictionary for this, just dumping the
instances is sufficient.

| But would this be valid for different sessions of Python?

Dictionaries, lists, classes, class instances, strings, etc are all
in-memory data.  When you quit python (or turn off your computer) the
memory where those data were stored is released and used by other
processes.

What you are looking for is persistant storage of some kind.  You want
your data to persist beyond the lifetime of a given python process.
The only way to achieve this is to serialize the data to disk (or,
conceivably to memory on a different machine that will continue
running, but that is not so feasible).  To serialize the data do disk
means either creating files or using a full-blown database system that
will handle files for you.

The simplest thing for you is to create a file yourself and to use the
'pickle' module to convert the in-memory data to a string that can be
stored in the file, and (very important!) read back in later.  See the
example above for how to do this.  However, don't use the StringIO or
cStringIO modules -- they provide file-like objects that exist in
memory.  They go away when you quit python.  I used them just so I
didn't need to create files on my disk for the example.

-D

-- 

Contrary to popular belief, Unix is user friendly.
It just happens to be selective about who it makes friends with.
                                               -- Dave Parnas



From dsh8290@rit.edu  Tue Dec  4 01:07:29 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 20:07:29 -0500
Subject: [Tutor] Too many open files
In-Reply-To: <EA7067EE4084D31186E308002BC33FC10881FE@overture.ordway.org>; from sburch@ordway.org on Mon, Dec 03, 2001 at 03:30:08PM -0600
References: <EA7067EE4084D31186E308002BC33FC10881FE@overture.ordway.org>
Message-ID: <20011203200729.F19633@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 03:30:08PM -0600, Burchill, Scott B. wrote:
| I have a small program which uses recursion while dealing with a flat file
| database.  I am opening and closing a number of files repeatedly during this
| recursion and I feel like I have done the closing needed but I am still
| being faced with a "too many files open" error.

To debug this (you probably are forgetting to close some files, or
closing it too late) you could make a dict and store a reference to
all the files you open in it (as keys, the value doesn't matter).
When you close a file, remove it from the dict (you can increment a
counter if you want to report how many you closed).  Then, when you
get the exception, iterate over the keys of the dict and print out the
name (and length) to see what files you do have open.  For example :

debug_files = {}
debug_closed = 0
import random
def recurse() :
    i = random.random()
    try :
        f = open( "/tmp/" + str(i) , "w" )
    except OSError , err :
        print err
        files = debug_files.keys()
        print "Open files : %d" % len( files )
        print "Closed files : %d" % debug_closed
        for file in files :
            print file.name
            # now close it just to be nice before we exit
            file.close()
        import sys
        sys.exit( 1 )
    debug_files[ f ] = None
    # just a little magic to simulate program logic
    if i % 2 :
        f.close()
        debug_closed += 1
        del debug_files[ f ]
    recurse()
    

| My questions:  Is there a variable I can reference which holds the number of
| open files?  How can I find out what the maximum number of open
| files is for my system?

Read the kernel source?  (heh, not for Solaris)  The bash manpage
shows that 'ulimit' doesn't display this.  Here's an idea though :

>>> l = [ ]
>>> i = 0
>>> while 1 :
...   l.append( open( "/tmp/" + str(i) , "w" ) )
...   i += 1
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
IOError: [Errno 24] Too many open files: '/tmp/1021'
>>> print len( l )
1021
>>>

Looks like it is 1021 for Linux 2.4.10, x86.  Actually, I bet it is
1024 (nice round number), but python already has stdin, stdout, and
stderr open that I didn't account for.

| I am running as follows:
| Python 2.1.1 (#1, Sep  4 2001, 12:16:58)
| [GCC 3.0] on sunos5

How's gcc 3.0 holding up for you?

-D 

-- 

"GUIs normally make it simple to accomplish simple actions and
impossible to accomplish complex actions."
    --Doug Gwyn  (22/Jun/91 in comp.unix.wizards)



From dsh8290@rit.edu  Tue Dec  4 01:19:24 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 20:19:24 -0500
Subject: [Tutor] performance considerations
In-Reply-To: <20011203133750.A27060@sill.silmarill.org>; from sill@optonline.net on Mon, Dec 03, 2001 at 01:37:50PM -0500
References: <20011203125139.C19147@harmony.cs.rit.edu> <20011203131041.B26805@sill.silmarill.org> <20011203133113.C19344@harmony.cs.rit.edu> <20011203133750.A27060@sill.silmarill.org>
Message-ID: <20011203201924.G19633@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 01:37:50PM -0500, Andrei Kulakov wrote:
| On Mon, Dec 03, 2001 at 01:31:13PM -0500, dman wrote:
| > On Mon, Dec 03, 2001 at 01:10:41PM -0500, Andrei Kulakov wrote:
| > | On Mon, Dec 03, 2001 at 12:51:39PM -0500, dman wrote:
| > | > 
| > | > I'm working on a script/program to do some processing (munging) on
| > | > text files in a directory tree.  In addition, for convenience, all
| > | > non-interesting files are copied without munging.  My script, as it
| > | > stands, is quite CPU intensive so I would like to optimize it some.
| > | > 
| > | > A portion of the script generates strings by starting with 'a' and
| > | > "adding" to it.  Ie "a", "b", ..., "z", "aa", "ab", ..., "zz", "aaa".
| > | > Would it be better to use a list of one-char-strings than to modify a
| > | > single string?  Here's the code I have now (BTW, that funny-looking
| > 
| > I forgot to mention, if a list of strings is used, each yield will
| > yield  "".join( the_list ), so the comparison is the multiple
| > modifications (creation) of strings versus join.
| 
| Yeah, that's what I thought.. I think I remember someone saying that one
| join would be much faster.

I did check out the 'profile' module before I left work, and it is
really easy to profile the code!  I'll test this tomorrow.

| > | > One last question for now :
| > | > I traverse the interesting files line-by-line and check them for a
| > | > regex match, then modify the line if it matches properly.  Would it be
| > | > better (faster) to read in the whole file and treat it as a single
| > | > string?  Memory is not a problem.
| > | 
| > | Yeah, probably.. profile!
| > 
| > I want to speculate before I rewrite it :-).  Maybe Tim will tell me
| > something (since he is so familiar with the inner workings)?

About half the time was spent in the function that iterates over the
lines checking it against the regex and modifying it appropriately.
The other half was spent checking lines for adjacent duplicates and
eliminating them.

The biggest problem with my regex, was it was inherently line-based.
It looked something like :

    (.*)(interesting stuff)(.*)

then I would take "interesting stuff" and break it down to the part
I'm really interested in, change it and put it all back together.

Then I had a "duh" moment :  all I need to do is find "interesting
stuff", play with it, then use string.replace to put the new stuff in
the string.

Now I'm wondering if the overhead of string creation with replace() is
better, and if it would be faster to just iterate over all the strings
I want to replace and try replacing them whether or not they exist in
the current file.

Is there any mutable strings in python?  I imagine that could improve
performance.

In any event, the thing only takes 28s to run.  It seems much longer,
due to various settings in my environment.

-D

-- 

Failure is not an option.  It is bundled with the software.



From dsh8290@rit.edu  Tue Dec  4 01:28:28 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 3 Dec 2001 20:28:28 -0500
Subject: [Tutor] thread locks
In-Reply-To: <20011203163938.B1113@tc.niof.net>; from rick@niof.net on Mon, Dec 03, 2001 at 04:39:38PM -0500
References: <20011203163938.B1113@tc.niof.net>
Message-ID: <20011203202828.H19633@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 04:39:38PM -0500, Rick Pasotto wrote:
| If the first thing I do in a long running function is to acquire a
| lock, can I be guaranteed that the first statement after lauching
| that function as a thread can accurately check for the existence
| of the lock?

You are not guaranteed that the thread will actually run as soon as it
is started.

| include thread,time
| mutex = thread.allocate_lock()
| def func():
| 	mutex.acquire()
| 	# do lots of stuff
| 	mutex.release()
| 
| thread.start_new(func,())
| while 1:
| 	if mutex.locked():
| 		time.sleep(1)
| 	else:
| 		break
| # thread has finished so I can do other things

| Or is there a better way to solve my problem?

import threading , time
def func() :
    while 1 : pass # do something that takes a while

t = threading.Thread( target=func )
t.start()
while t.isAlive() : time.sleep( 1 )

| I know this seems to defeat the purpose of using a thread but this is
| in a Tkinter program and if I don't do this the main window will not
| get redrawn if the user covers it up, etc.

Depending on how this is used and what it affects, you could just
start the thread and let it go.  Sometimes there is no need to make
the user wait until it is done.

BTW, you are aware that Tk is not thread-safe, right?  It is only safe
to modify any widgets in the Tk main thread.  If you aren't careful
with this, you can have spurious lockups and other bad things happen.
I don't know about Tk, but Swing has a method that takes a Runnable
object and queues it at the end of the event queue so that it is run
in the Swing main thread.  The runnable object would only contain the
code to update the GUI, not the labor stuff.

-D

-- 

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



From deliberatus@my995internet.com  Tue Dec  4 05:50:46 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Tue, 04 Dec 2001 00:50:46 -0500
Subject: [Tutor] rf1
Message-ID: <3C0C6436.A55CCA68@my995internet.com>

ok, got a copy of a letter zi sent to myself. capturex it in my server,
emailed it to meself from in there, here it is below. also wrote this
script.

----rf1 # = ReadFile program #1---------
import string

f = open("letter2.TXT",r')
in1=f.readlines()
f.close()

print in1
--------------EOF---------------
ok, now for giggles, here is that letter.
------------The VERY next line is it's first.-----------------
>From deliberatus@my995internet.com Tue Dec  4 00:13:16 2001
Return-Path: <deliberatus@my995internet.com>
Received: from my995internet.com ([64.78.133.184])
        by ns.howlermonkey.net (8.11.1/8.11.0) with ESMTP id
fB45DAS59756
        for <testcode@howlermonkey.net>; Tue, 4 Dec 2001 00:13:16 -0500
(EST)
        (envelope-from deliberatus@my995internet.com)
Received: from my995internet.com [63.17.249.117] by my995internet.com
with ESMTP
  (SMTPD32-6.06) id A5533CA000F6; Mon, 03 Dec 2001 21:47:15 -0700

Message-ID: <3C0C5B40.6466E49B@my995internet.com>
Date: Tue, 04 Dec 2001 00:12:32 -0500

From: Kirk Bailey <deliberatus@my995internet.com>
Organization: Silas Dent Memorial Cabal of ERIS Esoteric and hot dog
boiling society 
 so there.
X-Mailer: Mozilla 4.74 [en] (Win98; U)
X-Accept-Language: en
MIME-Version: 1.0
To: testcode@howlermonkey.net
Subject: test
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

test-first body line
-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


last body line
---------------------previous line was the last line of the
file--------------

ok, this earned me some intresting output:

print in1


C:\Python21>python rf1
['From deliberatus@my995internet.com Tue Dec  4 00:13:16 2001\n',
'Return-Path:
<deliberatus@my995internet.com>\n', 'Received: from my995internet.com
([64.78.13
3.184])\n', '        by ns.howlermonkey.net (8.11.1/8.11.0) with ESMTP
id fB45DA
S59756\n', '        for <testcode@howlermonkey.net>; Tue, 4 Dec 2001
00:13:16 -0
500 (EST)\n', '        (envelope-from deliberatus@my995internet.com)\n',
'Receiv
ed: from my995internet.com [63.17.249.117] by my995internet.com with
ESMTP\n', '
  (SMTPD32-6.06) id A5533CA000F6; Mon, 03 Dec 2001 21:47:15 -0700\n',
'\n', 'Mes
sage-ID: <3C0C5B40.6466E49B@my995internet.com>\n', 'Date: Tue, 04 Dec
2001 00:12
:32 -0500\n', '\n', 'From: Kirk Bailey
<deliberatus@my995internet.com>\n', 'Orga
nization: Silas Dent Memorial Cabal of ERIS Esoteric and hot dog boiling
society
 \n', ' so there.\n', 'X-Mailer: Mozilla 4.74 [en] (Win98; U)\n',
'X-Accept-Lang
uage: en\n', 'MIME-Version: 1.0\n', 'To: testcode@howlermonkey.net\n',
'Subject:
 test\n', 'Content-Type: text/plain; charset=us-ascii\n',
'Content-Transfer-Enco
ding: 7bit\n', '\n', 'test-first body line\n', '-- \n',
'Respectfully,\n', '
         -Kirk D Bailey (C)2001\n', '              Addme! icq
#27840081\n', 'end
\n', '\n', '\n', 'Within the sweep of his sword, Each man is an
Ubar.\n', '\n',
'http://www.howlermonkey.net/\n', 'http://www.sacredelectron.org/\n',
'\n', '\n'
, 'last body line\n']

C:\Python21>

Looks like it formed a tupple if I grok this right.

But I wanted a dictionary! They are SO much easier to search!






-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From rick@niof.net  Tue Dec  4 04:41:02 2001
From: rick@niof.net (Rick Pasotto)
Date: Mon, 3 Dec 2001 23:41:02 -0500
Subject: [Tutor] thread locks
In-Reply-To: <20011203202828.H19633@harmony.cs.rit.edu>
References: <20011203163938.B1113@tc.niof.net> <20011203202828.H19633@harmony.cs.rit.edu>
Message-ID: <20011203234102.B19025@tc.niof.net>

On Mon, Dec 03, 2001 at 08:28:28PM -0500, dman wrote:
> On Mon, Dec 03, 2001 at 04:39:38PM -0500, Rick Pasotto wrote:
> 
> | Or is there a better way to solve my problem?
> 
> import threading , time
> def func() :
>     while 1 : pass # do something that takes a while
> 
> t = threading.Thread( target=func )
> t.start()
> while t.isAlive() : time.sleep( 1 )

This works with one addition:

while t.isAlive() :
	self.win.update()
    time.sleep( 1 )

> | I know this seems to defeat the purpose of using a thread but this is
> | in a Tkinter program and if I don't do this the main window will not
> | get redrawn if the user covers it up, etc.
> 
> Depending on how this is used and what it affects, you could just
> start the thread and let it go.  Sometimes there is no need to make
> the user wait until it is done.

Until the process is done (the info is retrieved) there is nothing for
the user to do.

> BTW, you are aware that Tk is not thread-safe, right?  It is only safe
> to modify any widgets in the Tk main thread.

Which is why I asked the question. The long running process is in a
class that has no need to know that it's being run from a gui so I don't
want to put any gui stuff in it yet I need to update the gui while it's
running. By putting it in a thread I can stay in the main program to
update the gui and then proceed when the thread finishes.

This is working fine for me. I've got a widget with an after() method
that continuously checks a global variable that is written to (within
a lock) by the thread. The thread itself doesn't make any actual gui
calls, it just appends to the global list variable.

BTW, I'm calling my program PyNewzBin - The Multi-Part Binary Usenet
File Retriever. It's purpose is to more easily deal with newsgroups
like alt.binaries.mp3.audiobooks than a regular newsreader does. It's
most useful on a broadband connection since you can use it for the long
downloads and read news with your regular newsreader at the same time.

If anyone on this list thinks such a program would be useful to them and
would like to offer suggestions for improving it, I'd be glad to send
them the program.

-- 
Each of us certainly gets from Nature, from God, the right to
defend his person, his liberty, and his property, since they are
the three elements constituting or sustaining life, elements which
are mutually complementary and which cannot be understood without
one another. For what are our faculties, if not an extension of
our personality, and what is property, if not an extension of our
faculties?
	-- Frédéric Bastiat (1801-1850)
    Rick Pasotto    rickp@telocity.com    http://www.niof.net


From dyoo@hkn.eecs.berkeley.edu  Tue Dec  4 06:25:02 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 3 Dec 2001 22:25:02 -0800 (PST)
Subject: [Tutor] rf1
In-Reply-To: <3C0C6436.A55CCA68@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112032214110.30600-100000@hkn.eecs.berkeley.edu>

On Tue, 4 Dec 2001, Kirk Bailey wrote:

> import string
> 
> f = open("letter2.TXT",r')

Be careful --- you need to make sure to balance the quotes, or else Python
will think that the string is spilling over.  Strings that spill over will
be flagged as SyntaxErrors in Python, to make sure that you're aware of
this.

open(), by the way, will open things with "r"ead permission by default, so
the following code does the same thing:

    f = open("letter2.TXT")

Less typing, and less prone to mistakes.


> in1=f.readlines()
> f.close()
>
> print in1
>
> Looks like it formed a tupple if I grok this right.

Gotta be nitpicky about this.  *grin* To clarify, the command:

> in1=f.readlines()

is giving you back a list of the lines in your file.  There's a difference
between a tuple and a list.  Tuples use round parentheses:

   (1, 2, 3)

and lists use boxy braces:

   [1, 2, 3]

They're visually similar, and pretty much serve the same role as a holder
of possibly many values.  The big difference between tuples and lists,
though, is that lists are like balloons.  They're inflatable if we use
append() on them.


> But I wanted a dictionary! Those are SO much easier to search!

True: dictionaries are easy to search.  However, we need to tell Python
how exactly you want to search them.  Can you give a small example on what
you expect the dictionary to look like?



From dyoo@hkn.eecs.berkeley.edu  Tue Dec  4 07:02:47 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 3 Dec 2001 23:02:47 -0800 (PST)
Subject: [Tutor] rf1 (fwd)
Message-ID: <Pine.LNX.4.21.0112032249120.31456-100000@hkn.eecs.berkeley.edu>

Hi Kirk,

I'm forwarding your letter to Tutor, so that the others there can give
their input on this.

It sounds like you're looking for the 'rfc822' module, which knows how to
recognize the forms of most mail messages:

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

rfc822 builds something a bit more complicated than a simple dictionary.


By the way, there's a reason why the admins here won't configure Reply-To
on Tutor... uh... I just can't remember it at the moment.  But thank
goodness for Google.  *grin*

Let's see... ah, there it is!  I do remember that Deirdre was adamantly
against it, and we had a discussion on it way way back in June:

    http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/552073

Sorry I didn't respond to your question about reply-to sooner.  But for
the reasons listed on that thread, we won't be munging up messages with
the reply-to header here.

Talk to you later!



---------- Forwarded message ----------
Date: Tue, 04 Dec 2001 01:45:20 -0500
From: Kirk Bailey <deliberatus@my995internet.com>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] rf1

Each field in a email has a name at the beginning of it, and that field
ends with the CRLF charpair.

Regretfully, every line in the body also ends with a CRLF, and the body
field does NOT start with a Body: tag. There is simply a blank line
immediately before it- that is, CRLFCRLF(stuff in the body).

I submitted a ciouple of samples of letters Icaptured in the server with
an alias which appends incoming email to an identity to a file, and that
was included.

The idea is to come up with something that wil digest an incoming letter
and be able to pop out data fields on command, such as To, From,
subject, and the all important BODY- which has no name, it just comes
after all the existing headers.


Danny Yoo wrote:
> 
> On Tue, 4 Dec 2001, Kirk Bailey wrote:
> 
> > import string
> >
> > f = open("letter2.TXT",r')
> 
> Be careful --- you need to make sure to balance the quotes, or else Python
> will think that the string is spilling over.  Strings that spill over will
> be flagged as SyntaxErrors in Python, to make sure that you're aware of
> this.
> 
> open(), by the way, will open things with "r"ead permission by default, so
> the following code does the same thing:
> 
>     f = open("letter2.TXT")
> 
> Less typing, and less prone to mistakes.
> 
> > in1=f.readlines()
> > f.close()
> >
> > print in1
> >
> > Looks like it formed a tupple if I grok this right.
> 
> Gotta be nitpicky about this.  *grin* To clarify, the command:
> 
> > in1=f.readlines()
> 
> is giving you back a list of the lines in your file.  There's a difference
> between a tuple and a list.  Tuples use round parentheses:
> 
>    (1, 2, 3)
> 
> and lists use boxy braces:
> 
>    [1, 2, 3]
> 
> They're visually similar, and pretty much serve the same role as a holder
> of possibly many values.  The big difference between tuples and lists,
> though, is that lists are like balloons.  They're inflatable if we use
> append() on them.
> 
> > But I wanted a dictionary! Those are SO much easier to search!
> 
> True: dictionaries are easy to search.  However, we need to tell Python
> how exactly you want to search them.  Can you give a small example on what
> you expect the dictionary to look like?

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/



From dyoo@hkn.eecs.berkeley.edu  Tue Dec  4 09:39:18 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 4 Dec 2001 01:39:18 -0800 (PST)
Subject: [Tutor] "One Day of IDLE Toying" web guide available
Message-ID: <Pine.LNX.4.21.0112040131130.2107-100000@hkn.eecs.berkeley.edu>

Hi everyone,

Ok, I've felt sufficiently embarassed about the little FIXME's here and
there in my IDLE tutorial, so I've removed them.  *grin* I've made minor
changes to some words, but not a major revision.  I've also added pictures
that were missing from the guide, so things should be less obscure now.

Most importantly, I've finally given the darn thing a real title: "One Day
of IDLE Toying":

    http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html


This tutorial is limited to showing one day's worth of showing the ropes
of IDLE, just enough to be able to pick up and play through one of the
introductions on the main Python.org site.  If anyone wants to link to it,
please feel free to do so.  I won't move this page anywhere.  *grin*


I'd welcome any comments on this; I've sorta ignored updating this page
for... what... 6 months now?  *grin* Anyway, apologies for my laxness, and
I hope that this is helpful for someone.



From m_mariappanX@trillium.com  Tue Dec  4 10:30:22 2001
From: m_mariappanX@trillium.com (Mariappan, MaharajanX)
Date: Tue, 4 Dec 2001 02:30:22 -0800
Subject: [Tutor] FW: Having list in dict type
Message-ID: <53A7943A5BD8D411B6930002A5073155013F60EA@bgsmsx90.iind.intel.com>


>  -----Original Message-----
> From: 	Mariappan, MaharajanX  
> Sent:	Tuesday, December 04, 2001 3:26 PM
> To:	'tutor@python.org'
> Subject:	Having list in dict type
> 
> Hi Folks!
> 
> Is it posible for dictionary type's value part to be a list like below,
> 
> { "key1", ["name", "value"]
>   "key2", ["name", "value"]
> 
> If yes, 
> 
> 1) how can I gennerate this data dynamically[ Asuume that I have all the
> sting values]
> 2) Hiw can I traverse and print all the strings from this data.
> 
> TIA,
> Maharajan
> 


From alan.gauld@bt.com  Tue Dec  4 10:40:23 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 4 Dec 2001 10:40:23 -0000
Subject: [Tutor] Follow up to 'class data'
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C155@mbtlipnt02.btlabs.bt.co.uk>

> "Everything is an object" includes, I guess classes.

This is confusing things I agree. Its true that in Python everything is an
object, including classes. But for now forget that!

In OO terms classes define templates from which we create objects
- a better term is instances, it it disambiguates from pythons 
more general idea of objects.

> So to me, the address book is an object and can be a class?

So you could create an AddressBook class which would be a 
template from which you could create multiple instances, 
each of which would be an address book. Each address book 
would have the attributes you define in your AddressBook 
class(the methods and fields) but have their own values 
stored in those fields.  Thus your father's address book may 
hold different names to yours.

> I would have thought "address book" would be the class and 
> the means of adding, modifying, deleting data would be "methods."

Could be, and the data itself could be defined as classes
- Entries for example. Thus:

> The structure as I see it would be something like:
> 
> class AddressBook:
>    def input:
>    def modify:
>    def delete:
>    def search:
>    def sort:
>    def output:

Is fine, and the entries could look like:

class Entry
    def input
    def edit
    def compare(Entry)

Now we can have an address book that contains different 
types of entry by subclassing Entry:

class Building(Entry)
    def input
    etc...

class Person(Entry)
    def input
    etc...


The AddressBoook class writes its methods to use the Entry 
methods(eg compare(Entry) would be used both in searching 
and sorting...) But we can have both types of Entry 
(Building or Person) stored and AddressBook doesn't care, 
it just sees Entries!

> class AddressBook:
>    class Input(AddressBook):
>       def inputName:
>       def inputAddress:
>       def inputPhone:

Categorically NO. Classes are not functions!
Occasionally, very occasionally, we write classes that look 
like functions but its not normal practice. Similarly its 
not usually a good idea to provide set/get methods for 
every internal attribute - a common beginners mistake.
Only expose those attributes that the outside world needs 
to see.

Classes are 'living breathing things' that  know stuff and 
how to deal with that stuff. When thinking about classes 
ask "What does Foo know? And what can Foo do with what it knows?"

This is known as Responsibility Driven Design and is fundamental 
to designing with objects. Each object has its own set of 
responsibilities, no more and no less. If you can't figure 
which existing object is responsible it probably means its time 
for a new class...

As Peter Coad says: "Objects do it to themselves"

Alan G.


From alan.gauld@bt.com  Tue Dec  4 10:47:36 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 4 Dec 2001 10:47:36 -0000
Subject: [Tutor] class data
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C156@mbtlipnt02.btlabs.bt.co.uk>

> This was my understanding of it also; but classes apparently 
> contain their own __dict__.  

Yes but mostly you don't need to know that :-)

You create instances of your classes ad thise instances 
get a copy of the dictionary internally. They then populate 
their copy with data and when you pickle the object(instance) 
it saves the internal dictionary.

When you restore from a pickle the new object(instance) 
knows what the dictionary should look like because it 
is defined in the class(template).

> If it did, I have no clue how to access the data.

You don't pickle classes you pickle instances.
You restore those instances and access the internal data
as if you had never pickled it!

foo = MyClass()
foo.bar = 42

#  pickle foo here

foo = 7    # temporarily make foo something else if you like...

# now restore foo from the pickle

print foo.bar   # viola! foo has its object properties restored 

Its as if foo had never been away. You just access the fields
as you would have done before pickling.

Alan G.


From alan.gauld@bt.com  Tue Dec  4 10:55:03 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 4 Dec 2001 10:55:03 -0000
Subject: [Tutor] Follow up to 'class data'
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C157@mbtlipnt02.btlabs.bt.co.uk>

> Well, classes "hide" data so that it's harder to mess it up 
> The fancy name for this is data incapsulation, I think. 

Actually its 'data hiding'. 
Encapsulation is the process of combining data and function into
a single blob - an object. There are many OO languages which 
implement encapsulation without data hiding - early Python 
being one!(and still does by default).

Unfortunately even many modern books have gotten these 
terms mixed up which is an unfortunate side effect of 
the industry's confusion between OOP and C++!

> Now OO gurus will have a heart attack because I like classes 
> for all the wrong reasons ;-P.

Sounds like exactly the right reasons to me!
Of course those advantages pave the way for other exciting
features like asbstract classes etc too, but they are a 
consequence of the fundamental features you describe.

Alan G


From alan.gauld@bt.com  Tue Dec  4 11:07:22 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 4 Dec 2001 11:07:22 -0000
Subject: [Tutor] Division
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C158@mbtlipnt02.btlabs.bt.co.uk>

> > they should use the old style division behaviour - its how
> > the vast majority of programming languages work and is a
> Actually, truncating integer division is largely confined to 
> C and Fortran and their derivatives.  

Guess that gives away where my programming career started then :-)

> Basic, Smalltalk, AWK, Prolog, Pascal, COBOL, 

Hmm, I've used all of these but thinking about it you're right
they have a separate integer division operator that truncates
but by default convert to float for division results.

OK, I withdraw the objection :-)

Alan G.



From ak@silmarill.org  Tue Dec  4 11:13:38 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Tue, 04 Dec 2001 06:13:38 -0500
Subject: [Tutor] Follow up to 'class data'
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C157@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C157@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20011204061338.A29787@sill.silmarill.org>

On Tue, Dec 04, 2001 at 10:55:03AM -0000, alan.gauld@bt.com wrote:
> > Well, classes "hide" data so that it's harder to mess it up 
> > The fancy name for this is data incapsulation, I think. 
> 
> Actually its 'data hiding'. 
> Encapsulation is the process of combining data and function into
> a single blob - an object. There are many OO languages which 
> implement encapsulation without data hiding - early Python 
> being one!(and still does by default).
> 
> Unfortunately even many modern books have gotten these 
> terms mixed up which is an unfortunate side effect of 
> the industry's confusion between OOP and C++!
> 
> > Now OO gurus will have a heart attack because I like classes 
> > for all the wrong reasons ;-P.
> 
> Sounds like exactly the right reasons to me!
> Of course those advantages pave the way for other exciting
> features like asbstract classes etc too, but they are a 
> consequence of the fundamental features you describe.

I mentioned data hiding because I've heard about it, but I didn't find it
helpful myself (yet). I guess the things I described - easier way to
change data without globals or passing arguments back and forth - can be
filed under data encapsulation? Umm.. now that I thought about it for a
bit, I guess I only use one of classes "niceties":

1. Encapsulation - makes it easier to make a mental picture of your
program, you can create objects and associate both actions and data with
it. Otherwise you'd have them all over the place and that's confusing.
That's all I'm using classes for.

2. Polymorphism - I totally have no idea what does it mean in practice.
I read in some java book that it allows you to handle different types of
data easily, or somesuch.

3. Data hiding - I guess it's useful in very large projects where many
people are working on the code and you want to protect your data from
the silly intern in the next cubicle?

4. Inheritance - I used it a little bit but I could do without it just
as well. It pretty much saves typing and maintainance time, right?

> 
> Alan G

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


From alan.gauld@bt.com  Tue Dec  4 17:33:28 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 4 Dec 2001 17:33:28 -0000
Subject: [Tutor] Follow up to 'class data'
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C15C@mbtlipnt02.btlabs.bt.co.uk>

> 1. Encapsulation - makes it easier to make a mental picture of your
> program, you can create objects and associate both actions 
> and data 

Absolutely correct, the foundation of OOP.

> 2. Polymorphism - I totally have no idea what does it mean in 
> practice.

You probably use it without realising.
Its where a group of different classes have the same 
interface - ie set of methods - but implement them differently.
The HTML/XML/SGML parsers in te standard library are good 
examples. You create a parser and use it. Which parser depends
on the file type. The parsers are polymorphic instances of 
the general parser interface.

Another example is the AddressBook example earlier today.
AddressBook can contain entries. The Entries can either 
be buildings or people but provide they have the same set 
of methods the AddressBook doesn't know or care, it just 
uses the basic interface. In fact we could go on to define 
a Network entry too and the AddressBook need be none the wiser
it just calls the same set of methods.

See my OOP topic on my web tutor for much more with examples:
http://www.freenetpages.co.uk/hp/alan.gauld

> 3. Data hiding - I guess it's useful in very large projects where many
> people are working on the code and you want to protect your data from
> the silly intern in the next cubicle?

Sort of, its also useful when you are prototyping and the 
internal data starts off as a hard coded list, then gets 
moved to a flat file and finally to an RDBMS. The method
calls don't change but the internals of how they work change 
drastically. The other area that it helps in is where 
there are data rules such as valid ranges or  that you 
an only set one value if you also delete another etc. 
By forcing access via a method you can enforce those 
rules(inside the method) and thus avoid bugs.

> 4. Inheritance - I used it a little bit but I could do without it just
> as well. It pretty much saves typing and maintainance time, right?

This is usually the means of providing polymorphism(see above)
but as I show on my web tutor the two are not necessarily linked
(except in strictly typed languages). Inheritance does provide some
code saving convenience features in its own right and in 
particular allows programming by specialisation - where you
add new methods and attributes to existing ones or override
existing methods to do new things (this is subtly different 
to pure polymorphism which requires identical interfaces!
Something called the Liskov(sp?) Substitution Principle)

Interestingly there are some objective data to suggest that 
inheritance can actually be detrimental to maintenance since
it is much harder to ensure that a code fix in one place won't 
cause damage some place else that inherits the changed code.

Also the lack of local visibility of the functions can make 
code comprehension more difficult. This is one area where 
python and its explicit use of self and the imported module 
names actually helps a lot.

Alan g


From ak@silmarill.org  Tue Dec  4 18:02:45 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Tue, 04 Dec 2001 13:02:45 -0500
Subject: [Tutor] Follow up to 'class data'
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C15C@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C15C@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20011204130245.A31878@sill.silmarill.org>

On Tue, Dec 04, 2001 at 05:33:28PM -0000, alan.gauld@bt.com wrote:

[snip]

> 
> Interestingly there are some objective data to suggest that 
> inheritance can actually be detrimental to maintenance since
> it is much harder to ensure that a code fix in one place won't 
> cause damage some place else that inherits the changed code.

Let's say you inherit B from class A. If you change A and it
messes up B, the way I see it, could mean 2 things: either
B isn't really a subset of A and shouldn't have been inherited
from it, or the change was too broad, and you should've instead
derived another child class C from A and changed C.. That's
theory, I don't know how it pans out in practice.. and you know
what they say about the difference between theory and practice:
in theory, there is no difference, but in practice, there is :P

Thanks a lot - your post was very helpful. I had some general
idea about this stuff but it was very disorganized and I wasn't
sure about the terminology..

> 
> Also the lack of local visibility of the functions can make 
> code comprehension more difficult. This is one area where 
> python and its explicit use of self and the imported module 
> names actually helps a lot.
> 
> Alan g

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


From rcyahnke@doit.wisc.edu  Tue Dec  4 19:04:59 2001
From: rcyahnke@doit.wisc.edu (Ross Yahnke)
Date: Tue, 4 Dec 2001 13:04:59 -0600 (CST)
Subject: [Tutor] Python - html tables - cgi question
Message-ID: <Pine.A41.4.33.0112041254490.2118406-100000@hubcap.doit.wisc.edu>

Hi All - Strictly speaking this is more of a html/cgi question but I really
want to use Python to do it!

I have a text file with tab delimited data in it. I want to present it as an
html table that's in sorted order. Each column heading I'd like to be a
clickable link so that when I click on it, the table regenerates resorted
under the column clicked on.

I can get Python cgi to display a static list with no links only sorted by a
pre-chosen column. How do I go do the next step to let the viewer decide how
the table is to be sorted?

For what it's worth I'm using Apache 1.3.14 under Linux 2.2.16 using Python
1.5.2. The python code I'm using so far is really basic so I'm up to learning
something new to get this to work as I'd like to generalize it more...

Thanks all!

- Ross




From deliberatus@my995internet.com  Tue Dec  4 20:09:57 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Tue, 04 Dec 2001 15:09:57 -0500
Subject: [Tutor] rf1 (fwd)
References: <Pine.LNX.4.21.0112032249120.31456-100000@hkn.eecs.berkeley.edu>
Message-ID: <3C0D2D95.C881E52A@my995internet.com>

Sure does look like it from a quick look, gotta grok the isness before I
can dsay more.

This list has got itself set so if one clicks reply, it goes to the
sender- no replyto field! I was clicking reply, and therefore smaling
Danny in th mail box with a large trout, instead of sticking in the
list's mailbox. Shame on me.

But I alsways set up liss with a reply-to field, so clicking reply
assuredly takes the reply to the list. Some think this is good, some
preferr not to use a reply-to field. 

Danny Yoo wrote:
> 
> Hi Kirk,
> 
> I'm forwarding your letter to Tutor, so that the others there can give
> their input on this.
> 
> It sounds like you're looking for the 'rfc822' module, which knows how to
> recognize the forms of most mail messages:
> 
>     http://www.python.org/doc/lib/module-rfc822.html
> 
> rfc822 builds something a bit more complicated than a simple dictionary.
> 
> By the way, there's a reason why the admins here won't configure Reply-To
> on Tutor... uh... I just can't remember it at the moment.  But thank
> goodness for Google.  *grin*
> 
> Let's see... ah, there it is!  I do remember that Deirdre was adamantly
> against it, and we had a discussion on it way way back in June:
> 
>     http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/552073
> 
> Sorry I didn't respond to your question about reply-to sooner.  But for
> the reasons listed on that thread, we won't be munging up messages with
> the reply-to header here.
> 
> Talk to you later!
> 
> ---------- Forwarded message ----------
> Date: Tue, 04 Dec 2001 01:45:20 -0500
> From: Kirk Bailey <deliberatus@my995internet.com>
> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] rf1
> 
> Each field in a email has a name at the beginning of it, and that field
> ends with the CRLF charpair.
> 
> Regretfully, every line in the body also ends with a CRLF, and the body
> field does NOT start with a Body: tag. There is simply a blank line
> immediately before it- that is, CRLFCRLF(stuff in the body).
> 
> I submitted a ciouple of samples of letters Icaptured in the server with
> an alias which appends incoming email to an identity to a file, and that
> was included.
> 
> The idea is to come up with something that wil digest an incoming letter
> and be able to pop out data fields on command, such as To, From,
> subject, and the all important BODY- which has no name, it just comes
> after all the existing headers.
> 
> Danny Yoo wrote:
> >
> > On Tue, 4 Dec 2001, Kirk Bailey wrote:
> >
> > > import string
> > >
> > > f = open("letter2.TXT",r')
> >
> > Be careful --- you need to make sure to balance the quotes, or else Python
> > will think that the string is spilling over.  Strings that spill over will
> > be flagged as SyntaxErrors in Python, to make sure that you're aware of
> > this.
> >
> > open(), by the way, will open things with "r"ead permission by default, so
> > the following code does the same thing:
> >
> >     f = open("letter2.TXT")
> >
> > Less typing, and less prone to mistakes.
> >
> > > in1=f.readlines()
> > > f.close()
> > >
> > > print in1
> > >
> > > Looks like it formed a tupple if I grok this right.
> >
> > Gotta be nitpicky about this.  *grin* To clarify, the command:
> >
> > > in1=f.readlines()
> >
> > is giving you back a list of the lines in your file.  There's a difference
> > between a tuple and a list.  Tuples use round parentheses:
> >
> >    (1, 2, 3)
> >
> > and lists use boxy braces:
> >
> >    [1, 2, 3]
> >
> > They're visually similar, and pretty much serve the same role as a holder
> > of possibly many values.  The big difference between tuples and lists,
> > though, is that lists are like balloons.  They're inflatable if we use
> > append() on them.
> >
> > > But I wanted a dictionary! Those are SO much easier to search!
> >
> > True: dictionaries are easy to search.  However, we need to tell Python
> > how exactly you want to search them.  Can you give a small example on what
> > you expect the dictionary to look like?
> 
> --
> Respectfully,
>              -Kirk D Bailey (C)2001
>               Addme! icq #27840081
> end
> 
> Within the sweep of his sword, Each man is an Ubar.
> 
> http://www.howlermonkey.net/
> http://www.sacredelectron.org/

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From pythontutor@venix.com  Tue Dec  4 20:34:57 2001
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 04 Dec 2001 15:34:57 -0500
Subject: [Tutor] rf1 (fwd)
References: <Pine.LNX.4.21.0112032249120.31456-100000@hkn.eecs.berkeley.edu> <3C0D2D95.C881E52A@my995internet.com>
Message-ID: <3C0D3371.9080606@venix.com>

Is reply-to-all an option in your email client???

Kirk Bailey wrote:

> Sure does look like it from a quick look, gotta grok the isness before I
> can dsay more.
> 
> This list has got itself set so if one clicks reply, it goes to the
> sender- no replyto field! I was clicking reply, and therefore smaling
> Danny in th mail box with a large trout, instead of sticking in the
> list's mailbox. Shame on me.
> 
> But I alsways set up liss with a reply-to field, so clicking reply
> assuredly takes the reply to the list. Some think this is good, some
> preferr not to use a reply-to field. 
> 
> Danny Yoo wrote:
> 
>>Hi Kirk,
>>
>>I'm forwarding your letter to Tutor, so that the others there can give
>>their input on this.
>>

...


>>By the way, there's a reason why the admins here won't configure Reply-To
>>on Tutor... uh... I just can't remember it at the moment.  But thank
>>goodness for Google.  *grin*
>>
>>Let's see... ah, there it is!  I do remember that Deirdre was adamantly
>>against it, and we had a discussion on it way way back in June:
>>
>>    http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/552073
>>
>>Sorry I didn't respond to your question about reply-to sooner.  But for
>>the reasons listed on that thread, we won't be munging up messages with
>>the reply-to header here.
>>
>>Talk to you later!
>>

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

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



From dsh8290@rit.edu  Tue Dec  4 20:49:00 2001
From: dsh8290@rit.edu (dman)
Date: Tue, 4 Dec 2001 15:49:00 -0500
Subject: [Tutor] Follow up to 'class data'
In-Reply-To: <20011204130245.A31878@sill.silmarill.org>; from sill@optonline.net on Tue, Dec 04, 2001 at 01:02:45PM -0500
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C15C@mbtlipnt02.btlabs.bt.co.uk> <20011204130245.A31878@sill.silmarill.org>
Message-ID: <20011204154900.A23384@harmony.cs.rit.edu>

On Tue, Dec 04, 2001 at 01:02:45PM -0500, Andrei Kulakov wrote:
| On Tue, Dec 04, 2001 at 05:33:28PM -0000, alan.gauld@bt.com wrote:
| 
| [snip]
| 
| > Interestingly there are some objective data to suggest that 
| > inheritance can actually be detrimental to maintenance since
| > it is much harder to ensure that a code fix in one place won't 
| > cause damage some place else that inherits the changed code.
| 
| Let's say you inherit B from class A. If you change A and it
| messes up B, the way I see it, could mean 2 things: either
| B isn't really a subset of A and shouldn't have been inherited
| from it, or the change was too broad, and you should've instead
| derived another child class C from A and changed C.. That's
| theory, I don't know how it pans out in practice.. and you know
| what they say about the difference between theory and practice:
| in theory, there is no difference, but in practice, there is :P

My profs prefer "composition" over "inheritance".  The truth of the
matter is that inheritance can be a convenient way to automatically
get a bunch of implementation or to specialize something (like, maybe
subclass 'int' so that you can add some special operation).  However
inheritance also creates tight coupling and can make maintenance
difficult if the classes and inheritance tree were not ideal from the
start.

Object composition is a technique where instead of inheriting from a
class, instead an instance of that class is stored in the object and
operations are delegated to it.

If you do enough Java programming you will see how inheritance is not
flexible enough.  Composition can be a pain to code (especially for
large sets of operations) in static languages like C++ and Java, but
with Python you can use __getattr__ to automatically delegate all
operations that aren't implemented in the current class.

-D

-- 

But As for me and my household, we will serve the Lord.
        Joshua 24:15



From dsh8290@rit.edu  Tue Dec  4 20:55:25 2001
From: dsh8290@rit.edu (dman)
Date: Tue, 4 Dec 2001 15:55:25 -0500
Subject: [Tutor] thread locks
In-Reply-To: <20011203234102.B19025@tc.niof.net>; from rick@niof.net on Mon, Dec 03, 2001 at 11:41:02PM -0500
References: <20011203163938.B1113@tc.niof.net> <20011203202828.H19633@harmony.cs.rit.edu> <20011203234102.B19025@tc.niof.net>
Message-ID: <20011204155525.B23384@harmony.cs.rit.edu>

On Mon, Dec 03, 2001 at 11:41:02PM -0500, Rick Pasotto wrote:
| On Mon, Dec 03, 2001 at 08:28:28PM -0500, dman wrote:
| > On Mon, Dec 03, 2001 at 04:39:38PM -0500, Rick Pasotto wrote:
| > 
| > | Or is there a better way to solve my problem?
| > 
| > import threading , time
| > def func() :
| >     while 1 : pass # do something that takes a while
| > 
| > t = threading.Thread( target=func )
| > t.start()
| > while t.isAlive() : time.sleep( 1 )
| 
| This works with one addition:
| 
| while t.isAlive() :
| 	self.win.update()
|     time.sleep( 1 )
| 
| > | I know this seems to defeat the purpose of using a thread but this is
| > | in a Tkinter program and if I don't do this the main window will not
| > | get redrawn if the user covers it up, etc.
| > 
| > Depending on how this is used and what it affects, you could just
| > start the thread and let it go.  Sometimes there is no need to make
| > the user wait until it is done.
| 
| Until the process is done (the info is retrieved) there is nothing for
| the user to do.

They can look at the window :-).  Ideally you would have some sort of
animation to show that the program is still working.  This is more
important on a windows system where things have a greater tendency to
stop working.

| > BTW, you are aware that Tk is not thread-safe, right?  It is only safe
| > to modify any widgets in the Tk main thread.
| 
| Which is why I asked the question. The long running process is in a
| class that has no need to know that it's being run from a gui so I don't
| want to put any gui stuff in it yet I need to update the gui while it's
| running. By putting it in a thread I can stay in the main program to
| update the gui and then proceed when the thread finishes.

So just start the thread and forget about it.  Your event handler can
return (in the even thread) and allow Tk's mainloop to continue.  The
worker thread will keep working independently of that.

| This is working fine for me. I've got a widget with an after() method
| that continuously checks a global variable that is written to (within
| a lock) by the thread. The thread itself doesn't make any actual gui
| calls, it just appends to the global list variable.

This isn't ideal -- polling and a global variable.  It might help to
look at the 'threading' module -- it has some higher level concurrency
support than the 'thread' module.  In particular, the Event class
would be of interest to you.  You create an event.  The worker thread
will set() the event when it is done preparing the data.  In the mean
time that other widget wait()'s for the event to be set.  It is a
blocking call, which means that you don't do any polling.

It would be better to redesign the system so that the data is a local
variable that is passed around as necessary, but if it functions then
don't bother redesigning until you really need to redesign the system
(like when the current design can no longer meet the (ever changing)
needs of users).

HTH,
-D

-- 

(E)ighteen (M)egs (A)nd (C)onstantly (S)wapping



From dsh8290@rit.edu  Tue Dec  4 21:02:05 2001
From: dsh8290@rit.edu (dman)
Date: Tue, 4 Dec 2001 16:02:05 -0500
Subject: [Tutor] FW: Having list in dict type
In-Reply-To: <53A7943A5BD8D411B6930002A5073155013F60EA@bgsmsx90.iind.intel.com>; from m_mariappanX@trillium.com on Tue, Dec 04, 2001 at 02:30:22AM -0800
References: <53A7943A5BD8D411B6930002A5073155013F60EA@bgsmsx90.iind.intel.com>
Message-ID: <20011204160205.C23384@harmony.cs.rit.edu>

On Tue, Dec 04, 2001 at 02:30:22AM -0800, Mariappan, MaharajanX wrote:
| Hi Folks!
| 
| Is it posible for dictionary type's value part to be a list like below,
| 
| { "key1", ["name", "value"]
|   "key2", ["name", "value"]
| 
| If yes, 

Yes.  The keys must be hashable, but the values can be anything.

| 1) how can I gennerate this data dynamically[ Asuume that I have all
| the string values]

It is not enough to know that you have the data, but _how_ you have it
is important.  If they are already in the lists, then the question is
meaningless.  If it is in a file that you need to parse, then (also
knowing the format!) we can give suggestions.  It is also necessary to
know what determines what a key is and what the related values should
be, otherwise we're just making up random data with random rules for
creating it.

| 2) Hiw can I traverse and print all the strings from this data.

# python 2.2
for key in dict :
    print key , dict[ key ]

# all versions
for keys in dict.keys() :
    print key , dict[ key]


HTH,
-D

-- 

"GUIs normally make it simple to accomplish simple actions and
impossible to accomplish complex actions."
    --Doug Gwyn  (22/Jun/91 in comp.unix.wizards)



From m_mariappanX@trillium.com  Tue Dec  4 09:55:40 2001
From: m_mariappanX@trillium.com (Mariappan, MaharajanX)
Date: Tue, 4 Dec 2001 01:55:40 -0800
Subject: [Tutor] Having list in dict type
Message-ID: <53A7943A5BD8D411B6930002A5073155013F60E8@bgsmsx90.iind.intel.com>

Hi Folks!

Is it posible for dictionary type's value part to be a list like below,

{ "key1", ["name", "value"]
  "key2", ["name", "value"]

If yes, 

1) how can I gennerate this data dynamically[ Asuume that I have all the
sting values]
2) Hiw can I traverse and print all the strings from this data.

TIA,
Maharajan



From dyoo@hkn.eecs.berkeley.edu  Tue Dec  4 21:42:36 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 4 Dec 2001 13:42:36 -0800 (PST)
Subject: [Tutor] Having list in dict type
In-Reply-To: <53A7943A5BD8D411B6930002A5073155013F60E8@bgsmsx90.iind.intel.com>
Message-ID: <Pine.LNX.4.21.0112041325330.17154-100000@hkn.eecs.berkeley.edu>

On Tue, 4 Dec 2001, Mariappan, MaharajanX wrote:

> Hi Folks!
> 
> Is it posible for dictionary type's value part to be a list like below,
> 
> { "key1", ["name", "value"]
>   "key2", ["name", "value"]

Sure: if we try this in the interpreter:

###
>>> mydict = {}
>>> mydict = { "key" : ['name', 'value'],
...            'key2' : ['name', 'value'] }
>>> mydict
{'key': ['name', 'value'], 'key2': ['name', 'value']}
###

we can see that this works well.  Python's data structures can be nested
arbitrarily deep, so we can even do something very silly like this with
lists:

###
>>> def cover(thing, depth):
...     while depth > 0:
...         thing = [thing]
...         depth = depth - 1
...     return thing
... 
>>> buried_treasure = cover('gold coin', 10)
>>> buried_treasure
[[[[[[[[[['gold coin']]]]]]]]]]
###


and this flexibility extends to dictionaries too:

###
>>> treasures_of_the_deep = { 'gold coin' : cover('gold coin', 10),
...                           'mythril' : cover('mythril', 7),
...                           'masamune' : cover('masamune', 14) }
>>> treasures_of_the_deep
{ 'mythril': [[[[[[['mythril']]]]]]],
  'masamune': [[[[[[[[[[[[[['masamune']]]]]]]]]]]]]],
  'gold coin': [[[[[[[[[['gold coin']]]]]]]]]] }
###



> 1) how can I gennerate this data dynamically[ Asuume that I have all
> the sting values]

This depends on how your data is organized.  If it looks like you're
traversing, one by one, through your string values, then using a 'for'
loop might work well.  Can you give us some sample data, and your
expectation of what the dictionary should look like?


We can always add new entries into a dictionary like this:

###
>>> treasures_of_the_deep['pearl'] = cover('pearl', 99)
###

so if we combine something like this with a loop, we should be able to
insert elements dynamically into a dictionary.



> 2) Hiw can I traverse and print all the strings from this data.

We can 'walk' down dictionaries with the items() method.  For example,
with that dictionary above:

###
>>> mydict = { "key" : ['name', 'value'],
...            'key2' : ['name', 'value'] }
>>> for key, value in mydict.items():
...     print "The key %s unlocks the value %s" % (key, value)
... 
The key key unlocks the value ['name', 'value']
The key key2 unlocks the value ['name', 'value']
###

You might want to look at the dictionary documentation here:

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

which covers what we can do with dictionaries in excruciating detail.  
It's not thrilling reading, but it might come in handy.


Hope this helps!



From apython101@yahoo.com  Tue Dec  4 22:09:33 2001
From: apython101@yahoo.com (john public)
Date: Tue, 4 Dec 2001 14:09:33 -0800 (PST)
Subject: [Tutor] membership
Message-ID: <20011204220934.47129.qmail@web21103.mail.yahoo.com>

does the membership (in) function work for lists and
strings like it does for Tuples?

 is the there a got line X function in Python for
creating loops?

 How do I unsubscribe from the daily digest? TIA

 John

__________________________________________________
Do You Yahoo!?
Buy the perfect holiday gifts at Yahoo! Shopping.
http://shopping.yahoo.com


From dyoo@hkn.eecs.berkeley.edu  Tue Dec  4 22:12:09 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 4 Dec 2001 14:12:09 -0800 (PST)
Subject: [Tutor] Python - html tables - cgi question
In-Reply-To: <Pine.A41.4.33.0112041254490.2118406-100000@hubcap.doit.wisc.edu>
Message-ID: <Pine.LNX.4.21.0112041406030.17154-100000@hkn.eecs.berkeley.edu>

On Tue, 4 Dec 2001, Ross Yahnke wrote:

> Hi All - Strictly speaking this is more of a html/cgi question but I
> really want to use Python to do it!
> 
> I have a text file with tab delimited data in it. I want to present it as an
> html table that's in sorted order. Each column heading I'd like to be a
> clickable link so that when I click on it, the table regenerates resorted
> under the column clicked on.
> 
> I can get Python cgi to display a static list with no links only sorted by a
> pre-chosen column. How do I go do the next step to let the viewer decide how
> the table is to be sorted?

Hmmm... You might be able to do this by allowing the column titles itself
to be clickable, and adding an optional "sort_by" parameter to your CGI
program.  This way, you can allow users the option to choose the sorting
order in a way that's somewhat consistant with a spreadsheet user
interface.

Grabbing parameters from a CGI involves using the 'cgi' module:

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


If you have questions, please feel free to ask them on Tutor.  We'll be
happy to help you get your program going!  Good luck!



From kalle@gnupung.net  Tue Dec  4 22:20:59 2001
From: kalle@gnupung.net (Kalle Svensson)
Date: Tue, 4 Dec 2001 23:20:59 +0100
Subject: [Tutor] membership
In-Reply-To: <20011204220934.47129.qmail@web21103.mail.yahoo.com>
References: <20011204220934.47129.qmail@web21103.mail.yahoo.com>
Message-ID: <20011204232059.A24444@proton.lysator.liu.se>

[john public]
> does the membership (in) function work for lists and
> strings like it does for Tuples?

Yes, it does:
"1" in ["1", "2"]
is true, as is
"1" in "12"
and
"1" in ("1", "2")

>  is the there a got line X function in Python for
> creating loops?

I'm not sure what you're asking about here.  The canonical loop in Python is
the for loop over a sequence:

for x in [1, "foo", 3]:
    print x

will print

1
foo
3

A while loop is also available:

x = 0
while x < 3:
    print x
    x = x + 1

will print

0
1
2

>  How do I unsubscribe from the daily digest? TIA

Go to the URI
http://mail.python.org/mailman/listinfo/tutor
and enter your email address in the form at the bottom of the page and submit.
>From the following page you can edit your membership information and
unsubscribe.

Peace,
  Kalle
-- 
[  Laziness, impatience, hubris:  Pick two!  ]
[   International: http://www.gnupung.net/   ]
[ Svenska: http://www.lysator.liu.se/~kalle/ ]


From jrm@videotron.ca  Tue Dec  4 15:34:58 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Tue, 4 Dec 2001 17:34:58 +0200
Subject: [Tutor] Do Tkinter's windows always default to a certain size ?
Message-ID: <000d01c17cd9$3b75ae00$0100c0a8@videotron.ca>

    When running a Tkinter based program I just did from IDLE, commenting
out this_window.mainloop() of course, the window appears just the size I
would expect. But when running the same program (with this_window.mainloop()
active this time) from Explorer or a DOS prompt the window always default to
the same size and it goes for IDLE itself : looks like 640x400 best guess.
Can this behavior be changed ? I can't be the only one experiencing this and
it has to be a FAQ but I didn't find it. :(

Jean M.



From apython101@yahoo.com  Tue Dec  4 23:23:16 2001
From: apython101@yahoo.com (john public)
Date: Tue, 4 Dec 2001 15:23:16 -0800 (PST)
Subject: [Tutor] (no subject)
Message-ID: <20011204232316.58414.qmail@web21102.mail.yahoo.com>

I am a beginning programmer. Here is my my first
program for tic tac toe. It works BUT, a simple loop
would shorten this code considerably.  Is there a way
to tell the program to go to the line:

 n = input("which sqaure")

once it gets to the end of the first cycle?

 Thanks!!

a,b,c,d,e,f,g,h,i =1,2,3,4,5,6,7,8,9

square = ['a','b','c','d','e','f','g','h','i']

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]

n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]
# end of first part, can we loop here?
# can we create functions and modules to shorten the
code?
n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]

n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]

n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]


 
n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]

n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]

n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]


n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]


n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]


 


__________________________________________________
Do You Yahoo!?
Buy the perfect holiday gifts at Yahoo! Shopping.
http://shopping.yahoo.com


From apython101@yahoo.com  Tue Dec  4 23:25:02 2001
From: apython101@yahoo.com (john public)
Date: Tue, 4 Dec 2001 15:25:02 -0800 (PST)
Subject: [Tutor] loops
Message-ID: <20011204232502.50455.qmail@web21106.mail.yahoo.com>

I am a beginning programmer. Here is my my first
program for tic tac toe. It works BUT, a simple loop
would shorten this code considerably.  Is there a way
to tell the program to go to the line:

 n = input("which sqaure")

once it gets to the end of the first cycle?

 Thanks!!

a,b,c,d,e,f,g,h,i =1,2,3,4,5,6,7,8,9

square = ['a','b','c','d','e','f','g','h','i']

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]

n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]
# end of first part, can we loop here?
# can we create functions and modules to shorten the
code?
n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]

n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]

n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]


 
n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]

n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]

n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]


n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]


n = input("which square?")



s = raw_input("who gets the square?")
square[n-1] = s 

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]


 


__________________________________________________
Do You Yahoo!?
Buy the perfect holiday gifts at Yahoo! Shopping.
http://shopping.yahoo.com


From apython101@yahoo.com  Wed Dec  5 00:52:49 2001
From: apython101@yahoo.com (john public)
Date: Tue, 4 Dec 2001 16:52:49 -0800 (PST)
Subject: [Tutor] membership
Message-ID: <20011205005249.34964.qmail@web21104.mail.yahoo.com>

t1 = "a little red moon"
t2 = t1
t3 = "redmond washington"

if ("r" in t2):
    print "t2"
    print t2

 this short piece of code works using the membership
function. However adding what is below:

t1 = "a little red moon"
t2 = t1
t3 = "redmond washington"

if ("r" in t2):
    print "t2"
    print t2
   
if ("re" in t2):
   print "t2"
   print  t2
if ("re" in t3):
   print "t3"
   print  t3


results in this error message:


t2
a little red moon
Traceback (most recent call last):
  File "C:\Python21\Tools\idle\amembership.py", line
10, in ?
    if ("re" in t2):
TypeError: 'in <string>' requires character as left
operand

Can someone tell me why this happens? I am a beginning
programmer. I started in C++ three weeks ago. I
switched to python two weeks ago when I realized it
was user friendly. My first program was a tic tac toe
game. I am now trying to write a program that stores
notes in lists,tuples or strings. The information is
written word. Such as "little red moon"
"redmond washington", "cute redhead I met at the bar".
I want to be able to search the lists, tuple's or
strings succesively for the letter "r", which would
bring up all three notes. Then "re" which would bring
up all three. Then "red" which would still bring up
all three. Then redm, which would bring up only the
list [redmond washington], and redh which would bring
up only the list [cute redhead I met at the bar]. Is
the membership function what I should be using to do
this? I am only a begginer and most of what is said on
this thread is way over my head. I seem to be able to
read and understand code directly better than read and
understand what is said about code. Once I can see
code I can run it. Then make substitutions and
changes. So far this seems to be the best way for me
to learn from others. I will be posting the tic tac
toe program after this. Thanks for all the help
everbawdy!

 John Public ( really my real name ;)really!




__________________________________________________
Do You Yahoo!?
Buy the perfect holiday gifts at Yahoo! Shopping.
http://shopping.yahoo.com


From virketis@fas.harvard.edu  Wed Dec  5 01:05:32 2001
From: virketis@fas.harvard.edu (Pijus Virketis)
Date: Tue, 04 Dec 2001 20:05:32 -0500
Subject: [Tutor] membership
In-Reply-To: <20011205005249.34964.qmail@web21104.mail.yahoo.com>
Message-ID: <200112050105.fB5158l30204@smtp2.fas.harvard.edu>

John,

>t2
>a little red moon
>Traceback (most recent call last):
>  File "C:\Python21\Tools\idle\amembership.py", line
>10, in ?
>    if ("re" in t2):
>TypeError: 'in <string>' requires character as left
>operand

As the error message states, the thing for which you are asking "in" to
look for in some string must be a character, or equivalently a string of
lenght one. So, you can ask: "is letter 'r' in this string?" but not "is
word 're' in this string?" Of course, Python has ways to look for words in
strings as well. Check out the string module here:
http://www.python.org/doc/current/lib/module-string.html and in particular
look at string.find() and (perhaps) string.count().

Cheers, 

-P
------------------------------------------------------------
PGP PUBLIC KEY: www.fas.harvard.edu/~virketis/links
My weblog: www.fas.harvard.edu/~virketis



From glingl@aon.at  Wed Dec  5 01:08:29 2001
From: glingl@aon.at (Gregor Lingl)
Date: Wed, 5 Dec 2001 02:08:29 +0100
Subject: [Tutor] loops
References: <20011204232502.50455.qmail@web21106.mail.yahoo.com>
Message-ID: <00cb01c17d29$59fe3e50$1664a8c0@mega>

----- Original Message ----- 
From: "john public" <apython101@yahoo.com>
To: <tutor@python.org>
Sent: Wednesday, December 05, 2001 12:25 AM
Subject: [Tutor] loops


> I am a beginning programmer. Here is my my first
> program for tic tac toe. It works BUT, a simple loop
> would shorten this code considerably.  Is there a way
> to tell the program to go to the line:
> 
>  n = input("which sqaure")
> 
> once it gets to the end of the first cycle?
> 
>  Thanks!!
> 
> a,b,c,d,e,f,g,h,i =1,2,3,4,5,6,7,8,9
> 
> square = ['a','b','c','d','e','f','g','h','i']
> 
> print square[0],square[1],square[2]
> print square[3],square[4],square[5]
> print square[6],square[7],square[8]
> 
> n = input("which square?")
> 
> 
> 
> s = raw_input("who gets the square?")
> square[n-1] = s 
> 
> print square[0],square[1],square[2]
> print square[3],square[4],square[5]
> print square[6],square[7],square[8]
> # end of first part, can we loop here?

Certainly:

a,b,c,d,e,f,g,h,i =1,2,3,4,5,6,7,8,9

square = ['a','b','c','d','e','f','g','h','i']

print square[0],square[1],square[2]
print square[3],square[4],square[5]
print square[6],square[7],square[8]

for i in range(9):
    n = input("which square?")
    s = raw_input("who gets the square?")
    square[n-1] = s 

    print square[0],square[1],square[2]
    print square[3],square[4],square[5]
    print square[6],square[7],square[8]


And the next problem would be: how to
find out, if the game is over before the
ninth draw?

Gregor

P.S.: Hav a look at http://www.python.org/doc/Newbies.html



From apython101@yahoo.com  Wed Dec  5 02:09:18 2001
From: apython101@yahoo.com (john public)
Date: Tue, 4 Dec 2001 18:09:18 -0800 (PST)
Subject: [Tutor] find
Message-ID: <20011205020918.48033.qmail@web21104.mail.yahoo.com>

--0-1855971381-1007518158=:47978
Content-Type: text/plain; charset=us-ascii




John, 

>t2 
>a little red moon 
>Traceback (most recent call last): 
> File "C:\Python21\Tools\idle\amembership.py", line 
>10, in ? 
> if ("re" in t2): 
>TypeError: 'in <string>' requires character as left 
>operand 

As the error message states, the thing for which you are asking "in" to 
look for in some string must be a character, or equivalently a string 
of 
lenght one. So, you can ask: "is letter 'r' in this string?" but not 
"is 
word 're' in this string?" Of course, Python has ways to look for words 
in 
strings as well. Check out the string module here: 
http://www.python.org/doc/current/lib/module-string.html and in 
particular 
look at string.find() and (perhaps) string.count(). 


ok so the membership function only looks for single charectors. So I was using the wrong tool for the job.

after looking at the Python library reference 4.1 I took a newbie guess and thought that:

find(s, sub[, start[,end]]) 
   Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices. 
was the right tool for the job.

I interpreted and applied as below:


t1 = "a little red moon"
t2 = "cute redhead"
t3 = "redmond washington"

if ("r" in t2):
    print "t2"
    print t2

find(t2,red[0[1]])  

and got:

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.
IDLE 0.8 -- press F1 for help
>>> 
t2
cute redhead
Traceback (most recent call last):
  File "C:\Python21\Tools\idle\amembership.py", line 10, in ?
    find(t2,red[0[1]])
NameError: name 'find' is not defined


am I barking up the right tree?

thanks 



---------------------------------
Do You Yahoo!?
Buy the perfect holiday gifts at Yahoo! Shopping.
--0-1855971381-1007518158=:47978
Content-Type: text/html; charset=us-ascii

<P><BR><BR><FONT color=darkred><EM>John, <BR><BR>&gt;t2 <BR>&gt;a little red moon <BR>&gt;Traceback (most recent call last): <BR>&gt; File "C:\Python21\Tools\idle\amembership.py", line <BR>&gt;10, in ? <BR>&gt; if ("re" in t2): <BR>&gt;TypeError: 'in &lt;string&gt;' requires character as left <BR>&gt;operand <BR><BR>As the error message states, the thing for which you are asking "in" to <BR>look for in some string must be a character, or equivalently a string <BR>of <BR>lenght one. So, you can ask: "is letter 'r' in this string?" but not <BR>"is <BR>word 're' in this string?" Of course, Python has ways to look for words <BR>in <BR>strings as well. Check out the string module here: <BR>http://www.python.org/doc/current/lib/module-string.html and in <BR>particular <BR>look at string.find() and (perhaps) string.count(). <BR><BR><BR></EM></FONT><STRONG><FONT color=black>ok so the membership function only looks for single charectors. So I was using the wrong tool for the job.</FONT></STRONG></P>
<P><STRONG>after&nbsp;looking at the Python library reference 4.1 I took a newbie guess and thought that:</STRONG></P>
<DL>
<DT><B><A name=l2h-632><TT class=function>find</TT></A></B>(<VAR>s, sub</VAR><BIG>[</BIG><VAR>, start</VAR><BIG>[</BIG><VAR>,end</VAR><BIG>]</BIG><BIG>]</BIG>) 
<DD>Return the lowest index in <VAR>s</VAR> where the substring <VAR>sub</VAR> is found such that <VAR>sub</VAR> is wholly contained in <CODE><VAR>s</VAR>[<VAR>start</VAR>:<VAR>end</VAR>]</CODE>. Return <CODE>-1</CODE> on failure. Defaults for <VAR>start</VAR> and <VAR>end</VAR> and interpretation of negative values is the same as for slices. </DD></DL>
<P><STRONG>was the right tool for the job.</STRONG></P>
<P><STRONG>I interpreted and applied as below:</STRONG></P>
<P><BR>t1 = "a little red moon"<BR>t2 = "cute redhead"<BR>t3 = "redmond washington"</P>
<P>if ("r" in t2):<BR>&nbsp;&nbsp;&nbsp; print "t2"<BR>&nbsp;&nbsp;&nbsp; print t2</P>
<P>find(t2,red[0[1]])&nbsp; </P>
<P><STRONG>and got:</STRONG></P>
<P>Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32<BR>Type "copyright", "credits" or "license" for more information.<BR>IDLE 0.8 -- press F1 for help<BR>&gt;&gt;&gt; <BR>t2<BR>cute redhead<BR>Traceback (most recent call last):<BR>&nbsp; File "C:\Python21\Tools\idle\amembership.py", line 10, in ?<BR>&nbsp;&nbsp;&nbsp; find(t2,red[0[1]])<BR>NameError: name 'find' is not defined<BR></P>
<P><STRONG>am I barking up the right tree?</STRONG></P>
<P>thanks </P><p><br><hr size=1><b>Do You Yahoo!?</b><br>
Buy the perfect holiday gifts at <a
href="http://rd.yahoo.com/O=1/I=brandr-mailfooter/*http://shopping.yahoo.com">Yahoo! Shopping</a>.
--0-1855971381-1007518158=:47978--


From virketis@fas.harvard.edu  Wed Dec  5 02:43:27 2001
From: virketis@fas.harvard.edu (Pijus Virketis)
Date: Tue, 04 Dec 2001 21:43:27 -0500
Subject: [Tutor] find
In-Reply-To: <20011205020918.48033.qmail@web21104.mail.yahoo.com>
Message-ID: <200112050243.fB52h6r05965@smtp1.fas.harvard.edu>

--=====================_172160196==_.ALT
Content-Type: text/plain; charset="us-ascii"


>
> cute redhead
> Traceback (most recent call last):
>   File "C:\Python21\Tools\idle\amembership.py", line 10, in ?
>     find(t2,red[0[1]])
> NameError: name 'find' is not defined
>
> am I barking up the right tree?


Well, if I were you, I'd be barking up that very same tree as well, John. :)
However, your barking would be much more fruitful, if you imported the string
module before using find(). So, at the beginning of your code, add the
following:

import string

Then, you can say something like this:

string.find("tree", "re")               #checks if "re" is in "tree"

Do not forget the module name and the dot before find()! You need it, because
find() is in the string module namespace, so if you were omit string.*, Python
would look in the global namespace for "find" and it (probably) would not be
there. Hence the error message: "name 'find' is not defined." This comes in
particularly handy when you DO actually define some "find" object of your own,
and then import the string module. Python keeps your find and the
string.find()
completely separate. The term for it is namespace separation. There's
definitely more to it, but I think this should get you started.

Cheers, 

-P
------------------------------------------------------------
PGP PUBLIC KEY: www.fas.harvard.edu/~virketis/links
My weblog: www.fas.harvard.edu/~virketis

--=====================_172160196==_.ALT
Content-Type: text/html; charset="us-ascii"

<html>
<blockquote type=cite cite>cute redhead<br>
Traceback (most recent call last):<br>
&nbsp; File &quot;C:\Python21\Tools\idle\amembership.py&quot;, line 10,
in ?<br>
&nbsp;&nbsp;&nbsp; find(t2,red[0[1]])<br>
NameError: name 'find' is not defined<br>
<br>
<b>am I barking up the right tree?</b></blockquote><br>
Well, if I were you, I'd be barking up that very same tree as well, John.
:) However, your barking would be much more fruitful, if you imported the
string module before using find(). So, at the beginning of your code, add
the following:<br>
<br>
import string<br>
<br>
Then, you can say something like this:<br>
<br>
string.find(&quot;tree&quot;,
&quot;re&quot;)<x-tab>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</x-tab><x-tab>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</x-tab>#checks
if &quot;re&quot; is in &quot;tree&quot;<br>
<br>
Do not forget the module name and the dot before find()! You need it,
because find() is in the string module namespace, so if you were omit
string.*, Python would look in the global namespace for &quot;find&quot;
and it (probably) would not be there. Hence the error message: &quot;name
'find' is not defined.&quot; This comes in particularly handy when you DO
actually define some &quot;find&quot; object of your own, and then import
the string module. Python keeps your find and the string.find()
completely separate. The term for it is namespace separation. There's
definitely more to it, but I think this should get you started.<br>
<br>
Cheers, <br>
<br>
-P<br>
<div>------------------------------------------------------------</div>
<div>PGP PUBLIC KEY:
<a href="http://www.fas.harvard.edu/~virketis/links" EUDORA=AUTOURL>www.fas.harvard.edu/~virketis/links</a></div>
<div>My weblog:
<a href="http://www.fas.harvard.edu/~virketis" EUDORA=AUTOURL>www.fas.harvard.edu/~virketis</a></div>
</html>

--=====================_172160196==_.ALT--



From dsh8290@rit.edu  Wed Dec  5 03:14:58 2001
From: dsh8290@rit.edu (dman)
Date: Tue, 4 Dec 2001 22:14:58 -0500
Subject: [Tutor] find
In-Reply-To: <20011205020918.48033.qmail@web21104.mail.yahoo.com>; from apython101@yahoo.com on Tue, Dec 04, 2001 at 06:09:18PM -0800
References: <20011205020918.48033.qmail@web21104.mail.yahoo.com>
Message-ID: <20011204221458.A28531@harmony.cs.rit.edu>

On Tue, Dec 04, 2001 at 06:09:18PM -0800, john public wrote:
...
| find(t2,red[0[1]])  

import string
string.find( t2 , red[0][1] )

would be what you meant.

As of python 2.0 (or was it 2.1? I think 2.0) you can use the method
directly on the string object :

t2.find( red[0][1] )

HTH,
-D

-- 

If any of you lacks wisdom, he should ask God, who gives generously to
all without finding fault, and it will be given to him.  But when he
asks he must believe and not doubt, because he who doubts is like a wave
of the sea, blown and tossed by the wind.
        James 1:5-6



From jrm@videotron.ca  Tue Dec  4 22:03:31 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Wed, 5 Dec 2001 00:03:31 +0200
Subject: [Tutor] Ok, I understand you...
Message-ID: <001b01c17d0f$83342a60$0100c0a8@videotron.ca>

    My question must have seemed like a foreing language to you :
"when running the same program (with this_window.mainloop()
active this time) from Explorer or a DOS prompt the window always default to
the same size and it goes for IDLE itself : looks like 640x400 " since that
beahvior is not present on my notebook equipped with Windows '98
too. Boy, am I going to enjoy that one ! (beurk!)

Thanks for your bandwidth anyway ;)

Jean M.




From dyoo@hkn.eecs.berkeley.edu  Wed Dec  5 05:28:49 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 4 Dec 2001 21:28:49 -0800 (PST)
Subject: [Tutor] find
In-Reply-To: <20011204221458.A28531@harmony.cs.rit.edu>
Message-ID: <Pine.LNX.4.21.0112042122040.28199-100000@hkn.eecs.berkeley.edu>

Oh, one other thing about string.find(): it will return the position of
where it finds a match, but if there isn't a match, it'll return '-1':

###
>>> string.find("james and the giant peach", "james")
0
>>> string.find("james and the giant peach", "peach")
20
>>> string.find("hat", "rabbit")
-1
###

so be careful when you use string.find() in an 'if' condition.



Here's an example of a common bug:

##
>>> if string.find("rosebud", "rosebud"):    ## This should have been
...     print "What happen?"                 ## if string.find("rosebud",
... else:                                    ##       "rosebud") == -1:
...     print "Someone set us up."
... 
Someone set us up.
###


Hope this helps!



From jrm@videotron.ca  Tue Dec  4 22:44:31 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Wed, 5 Dec 2001 00:44:31 +0200
Subject: [Tutor] Finally :
Message-ID: <000b01c17d15$3cf41960$0100c0a8@videotron.ca>

    Sure it's not keeping you from sleeping but, just in case you'd fall in
the same trap : my new video card (ATI 8500) is using a manager called
Hydravision, mostly for dual display. I got rid of it and everything is
normal again.

Goodnight ! :)

Jean M.




From cow@esweeet.com  Wed Dec  5 06:30:21 2001
From: cow@esweeet.com (Cow)
Date: Tue, 4 Dec 2001 22:30:21 -0800 (PST)
Subject: [Tutor] Converting Python Script into Executable Files...
Message-ID: <20011205063022.1725B36F9@sitemail.everyone.net>

I am new to Python and i was wondering if you can convert your Python script into an executable file (*.exe) instead of leaving it as a .py file?
Also, in order to run a Python script, is it nessesary that your computer has all of those Python files (like if i wanted to send my friend one of my programs, but he didn't have the files, could he still run my program?)?


Thanks
-Ryan

_____________________________________________________________
Free eSweeet Mail - http://www.esweeet.com


From ak@silmarill.org  Wed Dec  5 06:38:07 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Wed, 05 Dec 2001 01:38:07 -0500
Subject: [Tutor] Converting Python Script into Executable Files...
In-Reply-To: <20011205063022.1725B36F9@sitemail.everyone.net>
References: <20011205063022.1725B36F9@sitemail.everyone.net>
Message-ID: <20011205013807.A1806@sill.silmarill.org>

On Tue, Dec 04, 2001 at 10:30:21PM -0800, Cow wrote:
> I am new to Python and i was wondering if you can convert your Python script into an executable file (*.exe) instead of leaving it as a .py file?
> Also, in order to run a Python script, is it nessesary that your computer has all of those Python files (like if i wanted to send my friend one of my programs, but he didn't have the files, could he still run my program?)?
> 
> 
> Thanks
> -Ryan

There's a number of programs that do that, the most popular iirc is
py2exe. The resulting .exe is quite big though 'cause it has to package
python interpreter with it, so you may want to tell your friend to
just install python.

> 
> _____________________________________________________________
> Free eSweeet Mail - http://www.esweeet.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 toodles@yifan.net  Wed Dec  5 06:44:07 2001
From: toodles@yifan.net (Andrew Wilkins)
Date: Wed, 5 Dec 2001 14:44:07 +0800
Subject: [Tutor] Converting Python Script into Executable Files...
References: <20011205063022.1725B36F9@sitemail.everyone.net>
Message-ID: <004701c17d58$3e928bb0$0300a8c0@sun>

> I am new to Python and i was wondering if you can convert your Python
script into an executable file (*.exe) instead of leaving it as a .py file?
> Also, in order to run a Python script, is it nessesary that your computer
has all of those Python files (like if i wanted to send my friend one of my
programs, but he didn't have the files, could he still run my program?)?

Check Gordon McMillan's package.
http://www.mcmillan-inc.com/install1.html

Andrew W.

>
>
> Thanks
> -Ryan
>
> _____________________________________________________________
> Free eSweeet Mail - http://www.esweeet.com
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From cow@esweeet.com  Wed Dec  5 08:24:27 2001
From: cow@esweeet.com (Cow)
Date: Wed, 5 Dec 2001 00:24:27 -0800 (PST)
Subject: [Tutor] Py2exe Help
Message-ID: <20011205082427.CC45A3ECC@sitemail.everyone.net>

I just downloaded Py2exe and have been playing with it for a long time now, but it doesn't seem to be working for me.  I have read the explaination on how to use it over and over, but i still keep on getting errors.  Can someone here please explain to me how to use it in their own words, because i don't understand the ones that were provided to me in the Py2exe file?

Thanks
-Ryan

_____________________________________________________________
Free eSweeet Mail - http://www.esweeet.com


From phelimkelly@hotmail.com  Wed Dec  5 09:54:17 2001
From: phelimkelly@hotmail.com (Phelim Kelly)
Date: Wed, 05 Dec 2001 09:54:17 +0000
Subject: [Tutor] Blank line added when reading in from file????
Message-ID: <F255xX6HGvPQSY0RAZv0001301c@hotmail.com>

<html><div style='background-color:'><DIV>Hello,</DIV>
<DIV>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; I have a small probelm, hope you can help. I'm reading text from an external file into a python program as follows:</DIV>
<DIV>&nbsp;</DIV>
<DIV>filename&nbsp; = raw_input("Enter the filename to read from: ");</DIV>
<DIV>p=0<BR>in_file = open(filename,"r")<BR>while p &lt; 4:<BR>&nbsp;&nbsp; text = in_file.readline()<BR>&nbsp;&nbsp; list[p]=text&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #list is an array which stores the content of each line read in.<BR>&nbsp;&nbsp; p = p + 1<BR>in_file.close()<BR><BR></DIV>
<DIV>The problem I have is that the text that is stored in variable 'text' isn't simply the contents of one line of the file, another blank line is appended onto the end, which causes problems for the rest of the program, so instead of this,</DIV>
<DIV>&nbsp;</DIV>
<DIV>---------------------</DIV>
<DIV>line read in from file</DIV>
<DIV>--------------------</DIV>
<DIV>&nbsp;</DIV>
<DIV>I get this,</DIV>
<DIV>&nbsp;</DIV>
<DIV>-------------------</DIV>
<DIV>line read in from file</DIV>
<DIV>&nbsp;</DIV>
<DIV>-------------------</DIV>
<DIV>&nbsp;</DIV>
<DIV>Can anyone tell me the command used to get rid of the extra blank line added on?</DIV>
<DIV>Thanks in advance,</DIV>
<DIV>Phelim.</DIV></div><br clear=all><hr>Get your FREE download of MSN Explorer at <a href='http://go.msn.com/bql/hmtag_itl_EN.asp'>http://explorer.msn.com</a><br></html>


From ak@silmarill.org  Wed Dec  5 10:04:48 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Wed, 05 Dec 2001 05:04:48 -0500
Subject: [Tutor] Blank line added when reading in from file????
In-Reply-To: <F255xX6HGvPQSY0RAZv0001301c@hotmail.com>
References: <F255xX6HGvPQSY0RAZv0001301c@hotmail.com>
Message-ID: <20011205050448.A2647@sill.silmarill.org>

On Wed, Dec 05, 2001 at 09:54:17AM +0000, Phelim Kelly wrote:

Hello,

Many e-mail programs can't edit HTML directly. If you want to get
maximum response, send plain text messages.

 - Andrei

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


From phelimkelly@hotmail.com  Wed Dec  5 10:10:46 2001
From: phelimkelly@hotmail.com (Phelim Kelly)
Date: Wed, 05 Dec 2001 10:10:46 +0000
Subject: [Tutor] Blank line added when reading in from file????
Message-ID: <F1473iVdGJ5OGQOuE3c00014119@hotmail.com>

<html><div style='background-color:'><DIV>
<P>Thanks for your response Andrei,</P>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; I'm not sure I understand your response! I'm not using HTML files, I'm working on a UNIX machine. The file I'm reading from is a plain text file.</P>
<P>&nbsp;</P>
<P>Hello, </P></DIV>
<DIV></DIV>
<DIV></DIV>Many e-mail programs can't edit HTML directly. If you want to get 
<DIV></DIV>maximum response, send plain text messages. 
<DIV></DIV>
<DIV></DIV>- Andrei 
<DIV></DIV>
<DIV></DIV>-- 
<DIV></DIV>Cymbaline: intelligent learning mp3 player - python, linux, console. 
<DIV></DIV>get it at: cy.silmarill.org 
<DIV></DIV>
<DIV></DIV>_______________________________________________ 
<DIV></DIV>Tutor maillist - Tutor@python.org 
<DIV></DIV>http://mail.python.org/mailman/listinfo/tutor 
<DIV></DIV></div><br clear=all><hr>Get your FREE download of MSN Explorer at <a href='http://go.msn.com/bql/hmtag_itl_EN.asp'>http://explorer.msn.com</a><br></html>


From dyoo@hkn.eecs.berkeley.edu  Wed Dec  5 10:09:35 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 5 Dec 2001 02:09:35 -0800 (PST)
Subject: [Tutor] Py2exe Help
In-Reply-To: <20011205082427.CC45A3ECC@sitemail.everyone.net>
Message-ID: <Pine.LNX.4.21.0112050207100.1598-100000@hkn.eecs.berkeley.edu>

On Wed, 5 Dec 2001, Cow wrote:

> I just downloaded Py2exe and have been playing with it for a long time
> now, but it doesn't seem to be working for me.  I have read the
> explaination on how to use it over and over, but i still keep on
> getting errors.  Can someone here please explain to me how to use it
> in their own words, because i don't understand the ones that were
> provided to me in the Py2exe file?

There are a few people here who have some experience with py2exe here.
What kind of error messages are you getting?  If you can give us the
literal error messages that you're getting, that may give one of us here
enough clues to figure out what's happening.

Also, what kind of programs have you tried py2exe on?  Does it work at all
on simple programs?

I hope that your problem can get fixed quickly.  Good luck!



From alan.gauld@bt.com  Wed Dec  5 11:45:21 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 5 Dec 2001 11:45:21 -0000
Subject: [Tutor] Follow up to 'class data'
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C167@mbtlipnt02.btlabs.bt.co.uk>

> > it is much harder to ensure that a code fix in one place won't 
> > cause damage some place else that inherits the changed code.
> 
> Let's say you inherit B from class A. If you change A and it
> messes up B, the way I see it, could mean 2 things: 

Way too high level.
The problems tend to be in tiny details like:
method X does something and as a side effect sets a member 
field to some value, say -1, to indicate a NULL result. 
The maintainer discovers a flaw where -1 should be a valid result
so in his/her 'fix' sets the field to the "right value", say None.

However unbeknownst to the maintainer some other project
uses his class and relies on the field being set to -1 and
is not aflicted by the original bug that caused the maintainer 
to check the method. Now the 'fixed' version goes live and the 
second project develops its own bug.

Configuration management can solve some of these issues but if 
the second project needs the fixed version as well then we are 
stuffed! The problem is the classic one of global variables. 
Classes effectively use global variables when they modify 
class member data. Although they are protected within the 
class namespace they are still globals so far as the class 
methods are concerned. When you get a lot of different clssses 
inheriting common functions it becomes difficult to keep 
track of the impact of these side effects.

Imagine a class hierarchy 7 levels deep using multiple inheritance.
Then imagine someone chaging a single method say 1 layer off the top
and trying to see what the impact is in all the layers below....
In a network management project some years ago we had just such a 
scenario. Each network element (there were over 50 of these leaf 
node classes) inherited 35 parent classes. If you had to change 
a single method of one of those 35 base classes you had to check 
out all 50 of the leaf nodes to make sure you hadn't screwed 
anything up!

Alan g


From alan.gauld@bt.com  Wed Dec  5 11:51:28 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 5 Dec 2001 11:51:28 -0000
Subject: [Tutor] Follow up to 'class data'
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C168@mbtlipnt02.btlabs.bt.co.uk>

> | > Interestingly there are some objective data to suggest that 
> | > inheritance can actually be detrimental to maintenance since
> 
> My profs prefer "composition" over "inheritance".  

Thats becoming the accepted stance.
Interestingly its the stance the Smalltalk community have 
allways taken and is the reason they have resisted moves 
to put multiple inheritance into Smalltalk...
Of course it helps that Smalltalk is, like Python, very 
dynamic and supports introspection(like __getattr__).

Inheritance is often over used and abused (see my earlier reply)
but it is essential for polymorphism in some languages 
- that's the pity!

Alan g


From alan.gauld@bt.com  Wed Dec  5 11:58:30 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 5 Dec 2001 11:58:30 -0000
Subject: [Tutor] membership
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C169@mbtlipnt02.btlabs.bt.co.uk>

> does the membership (in) function work for lists and
> strings like it does for Tuples?

Yes, it works for all sequences including lists and strings
Very useful for input validation:

if response in "yY": doSomething()
elif response in "Nn": doAnother()
else: print 'Must respond Y/N"


>  is the there a got line X function in Python for
> creating loops?

I assume you mean GOTO line X?
The answer is NO. Most modern languages denigrate the 
use of GOTO, loops in Python are implemented using

for <item> in <sequence>:

OR 

while <condition>:

These can be modified using the break and continue statements.
By combining these there is no need for a GOTO and the code 
remains maintainable for longer!

>  How do I unsubscribe from the daily digest? TIA

Go to the tutor web page on python.org and chamge your 
settings

Alan g


From alan.gauld@bt.com  Wed Dec  5 12:06:04 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 5 Dec 2001 12:06:04 -0000
Subject: [Tutor] loops
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C16B@mbtlipnt02.btlabs.bt.co.uk>

> program for tic tac toe. It works BUT, a simple loop
> would shorten this code considerably.  Is there a way
> to tell the program to go to the line:
> 
>  n = input("which sqaure")

Yes. 
You sound like someone who has programmed in BASIC at sometime?
If so you might find my online tutor which compares Python 
and BASIC useful:

http://www.freenetpages.co.uk/hp/alan.gauld/

It has specific topics on loops etc.

Alan G


From alan.gauld@bt.com  Wed Dec  5 12:08:27 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 5 Dec 2001 12:08:27 -0000
Subject: [Tutor] membership
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C16C@mbtlipnt02.btlabs.bt.co.uk>

>  this short piece of code works using the membership
> function. However adding what is below:
> 
> t1 = "a little red moon"
> t2 = t1
> t3 = "redmond washington"
> 
> if ("r" in t2):
>     print "t2"
>     print t2
>    
> if ("re" in t2):

The membership operator only works for single items.
You need the string functions for this: string.search()
in this case.

Alan G


From alan.gauld@bt.com  Wed Dec  5 12:12:47 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 5 Dec 2001 12:12:47 -0000
Subject: [Tutor] membership
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C16D@mbtlipnt02.btlabs.bt.co.uk>

> look at string.find() and (perhaps) string.count().

Oops yes. I'm getting my re and string modules mixed up.

re.search() and string.find()

Am I alone in thinking it would be nice to make the string/re 
find/search and replace/sub operations consistent?

sorry,

Alan G.


From KellyPhe@logica.com  Wed Dec  5 12:29:55 2001
From: KellyPhe@logica.com (Kelly, Phelim)
Date: Wed, 5 Dec 2001 12:29:55 -0000
Subject: [Tutor] Blank line added after reading a line from a file
Message-ID: <C9054F12A3EED311B0160090274D912105C1A82B@shannon.ie.logica.com>

(I'll try this again!)

Hello, 
I have a small probelm, hope you can help. I'm reading text from an external
file into a python program as follows: 

---------------------
filename = raw_input("Enter the filename to read from: "); 
p=0
in_file = open(filename,"r")
while p < 4:
   text = in_file.readline()
   list[p]=text #list is an array which stores the content of each line read

                #in.
   p = p + 1
in_file.close()
---------------------------

The problem I have is that the text that is stored in variable 'text' isn't
simply the contents of one line of the file, another blank line is appended
onto the end, which causes problems for the rest of the program, so instead
of this, 
--------------------- 
line read in from file 
-------------------- 

I get this, 

------------------- 
line read in from file 

------------------- 
Can anyone tell me the command used to get rid of the extra blank line added
on? 
Thanks in advance, 
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 ak@silmarill.org  Wed Dec  5 12:40:15 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Wed, 05 Dec 2001 07:40:15 -0500
Subject: [Tutor] Blank line added after reading a line from a file
In-Reply-To: <C9054F12A3EED311B0160090274D912105C1A82B@shannon.ie.logica.com>
References: <C9054F12A3EED311B0160090274D912105C1A82B@shannon.ie.logica.com>
Message-ID: <20011205074015.A3598@sill.silmarill.org>

On Wed, Dec 05, 2001 at 12:29:55PM +0000, Kelly, Phelim wrote:
> (I'll try this again!)
> 
> Hello, 
> I have a small probelm, hope you can help. I'm reading text from an external
> file into a python program as follows: 
> 
> ---------------------
> filename = raw_input("Enter the filename to read from: "); 
> p=0
> in_file = open(filename,"r")
> while p < 4:
>    text = in_file.readline()
>    list[p]=text #list is an array which stores the content of each line read
> 
>                 #in.
>    p = p + 1
> in_file.close()

This would be easier done as:

in_file = open(filename)
text = inf_file.readlines()
lines_1_4 = text[:4]

That is, assuming file will comfortably fit in memory, which is the case
with most text files.

> ---------------------------
> 
> The problem I have is that the text that is stored in variable 'text' isn't
> simply the contents of one line of the file, another blank line is appended
> onto the end, which causes problems for the rest of the program, so instead
> of this, 
> --------------------- 
> line read in from file 
> -------------------- 
> 
> I get this, 
> 
> ------------------- 
> line read in from file 
> 
> ------------------- 
> Can anyone tell me the command used to get rid of the extra blank line added
> on? 

I think this has to do with how you print them out... how do you do
that?

> Thanks in advance, 
> 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.
> 
> _______________________________________________
> 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 apython101@yahoo.com  Wed Dec  5 13:51:43 2001
From: apython101@yahoo.com (john public)
Date: Wed, 5 Dec 2001 05:51:43 -0800 (PST)
Subject: [Tutor] string.search
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C16C@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20011205135143.91375.qmail@web21101.mail.yahoo.com>

--0-1935904150-1007560303=:87024
Content-Type: text/plain; charset=us-ascii


 I think string.search() is what I am looking for but without an actual example I can't figure it out. I started programming three weeks ago. I have lived with many programmers in the past and I am realizing I learned some BASIC by osmosis. Once I find the right tool for the job, is there some online documentation that has a real example for everything. I checked Guido's tutorial and the Python reference library but could only find examples in the abstract. 
such as string.search(string,[,pos[,endpos]]) 
in the case below I interpreted this to be
t1.search(t1[,0[,3]]) however I noticed that Python is not being informed as to what piece of the list it is searching. I tried running it a few times anyway but got error messages. Unfortunately the until I can become morfe familiar with the format of Python the Python Reference manual will be of little help since it does not give real examples.
  alan.gauld@bt.com wrote: 
> this short piece of code works using the membership
> function. However adding what is below:
> 
> t1 = "a little red moon"
> t2 = t1
> t3 = "redmond washington"
> 
> if ("r" in t2):
> print "t2"
> print t2
> 
> if ("re" in t2):

The membership operator only works for single items.
You need the string functions for this: string.search()
in this case.

Alan G

 



---------------------------------
Do You Yahoo!?
Buy the perfect holiday gifts at Yahoo! Shopping.
--0-1935904150-1007560303=:87024
Content-Type: text/html; charset=us-ascii

<P> I think string.search() is what I am looking for but without an actual example I can't figure it out. I started programming three weeks ago. I have lived with many programmers in the past and I am realizing I learned some BASIC by osmosis. Once I find the right tool for the job, is there some online documentation that has a real example for everything. I checked Guido's tutorial and the Python reference library but could only find examples in the abstract. 
<P>such as string.search(string,[,pos[,endpos]]) 
<P>in the case below I interpreted this to be
<P>t1.search(t1[,0[,3]]) however I noticed that&nbsp;Python is not being informed as to what piece of the list it is searching. I tried running it a few times anyway but got error messages. Unfortunately&nbsp;the&nbsp;until I can become morfe familiar with the format of Python the Python Reference manual will be of little help since it does not give real examples.
<P>&nbsp; <B><I>alan.gauld@bt.com</I></B> wrote: 
<BLOCKQUOTE style="BORDER-LEFT: #1010ff 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px">
<P>&gt; this short piece of code works using the membership<BR>&gt; function. However adding what is below:<BR>&gt; <BR>&gt; t1 = "a little red moon"<BR>&gt; t2 = t1<BR>&gt; t3 = "redmond washington"<BR>&gt; <BR>&gt; if ("r" in t2):<BR>&gt; print "t2"<BR>&gt; print t2<BR>&gt; <BR>&gt; if ("re" in t2):<BR><BR>The membership operator only works for single items.<BR>You need the string functions for this: string.search()<BR>in this case.<BR><BR>Alan G</P>
<P>&nbsp;</P></BLOCKQUOTE><p><br><hr size=1><b>Do You Yahoo!?</b><br>
Buy the perfect holiday gifts at <a
href="http://rd.yahoo.com/O=1/I=brandr-mailfooter/*http://shopping.yahoo.com">Yahoo! Shopping</a>.
--0-1935904150-1007560303=:87024--


From alan.gauld@bt.com  Wed Dec  5 14:39:09 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 5 Dec 2001 14:39:09 -0000
Subject: [Tutor] Blank line added when reading in from file????
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C16E@mbtlipnt02.btlabs.bt.co.uk>

------_=_NextPart_001_01C17D9A.991EE960
Content-type: text/plain; charset="iso-8859-1"

while p < 4:
   text = in_file.readline()
 
You could just have used:
 
list = in_file.readlines()
 
But list is a bad variable name since its also 
a Python function...it converts things to lists.
 

The problem I have is that the text that is stored in variable 'text' isn't
simply the contents of one line of the file, another blank line is appended
onto the end, which causes problems for the rest of the program, so instead
of this,

I suspect using string.strip() will fix this:
 
lines = in_file.readlines()
for index in range(length(lines)):
   lines[index] = lines[index].strip()
 
BTW The comments elsewhere about HTML refer to the format of your 
email which seems to be in HTML which some folks on the 
tutor list can't read properly (at least their mail client 
can't!).
 
Alan G

------_=_NextPart_001_01C17D9A.991EE960
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>while p &lt; 4:<BR>&nbsp;&nbsp; text = in_file.readline()<BR><SPAN 
class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>You could just have used:</FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>list = in_file.readlines()</FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>But list is a bad variable name since its also </FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>a Python function...it converts things to lists.</FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<BLOCKQUOTE 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid">
  <DIV>
  <DIV>The problem I have is that the text that is stored in variable 'text' 
  isn't simply the contents of one line of the file, another blank line is 
  appended onto the end, which causes problems for the rest of the program, so 
  instead of this,</DIV></DIV></BLOCKQUOTE>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>I suspect using string.strip() will fix this:</FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>lines = in_file.readlines()</FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>for&nbsp;index in range(length(lines)):</FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;&nbsp; lines[index] = lines[index].strip()</FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>BTW The comments elsewhere about HTML refer to the format of your 
</FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>email which seems to be in HTML which some folks on the 
</FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>tutor list can't read properly (at least their mail client 
</FONT></SPAN></DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>can't!).</FONT></SPAN></DIV>
<DIV><FONT face="Courier New" color=#0000ff size=2></FONT>&nbsp;</DIV>
<DIV><SPAN class=610523714-05122001><FONT face="Courier New" color=#0000ff 
size=2>Alan G</FONT></SPAN></DIV></BODY></HTML>

------_=_NextPart_001_01C17D9A.991EE960--


From alan.gauld@bt.com  Wed Dec  5 14:52:10 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 5 Dec 2001 14:52:10 -0000
Subject: [Tutor] RE: string.search
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C16F@mbtlipnt02.btlabs.bt.co.uk>

string.search(string,[,pos[,endpos]]) 

t1.search(t1[,0[,3]]) 

The square brackets indicate optional items, thus all you 
need is:

t2.search(t1)

Which searches for t1 within t2. It returns the location 
of t1 within t2 or -1 if not there.

You can limit the range of the search using the optional items so 
you could do:

t2.search(t1,3)   # search from the 4 character of t2 to the end 

OR

t2.search(t1,3,7)   # search from the 4th character to the 8th.

BTW I haven't checked that this is absolutely correct so read 
the docs again...I'm too old fashioned and still use the string 
module functions rather than the new string methods.
The principle of what I'm saying is correct tho...

Alan G.


From ak@silmarill.org  Wed Dec  5 15:07:16 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Wed, 05 Dec 2001 10:07:16 -0500
Subject: [Tutor] string.search
In-Reply-To: <20011205135143.91375.qmail@web21101.mail.yahoo.com>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C16C@mbtlipnt02.btlabs.bt.co.uk>
 <20011205135143.91375.qmail@web21101.mail.yahoo.com>
Message-ID: <20011205100716.A3993@sill.silmarill.org>

On Wed, Dec 05, 2001 at 05:51:43AM -0800, john public wrote:
> 
>  I think string.search() is what I am looking for but without an actual example I can't figure it out. I started programming three weeks ago. I have lived with many programmers in the past and I am realizing I learned some BASIC by osmosis. Once I find the right tool for the job, is there some online documentation that has a real example for everything. I checked Guido's tutorial and the Python reference library but could only find examples in the abstract. 
> such as string.search(string,[,pos[,endpos]]) 

In this case brackets mean that 2nd and 3rd arguments are optional.
Actual usage looks like this:

string.search(my_str, 2, 3)

 - Andrei

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


From Aedin@chah.ucc.ie  Wed Dec  5 16:16:28 2001
From: Aedin@chah.ucc.ie (Aedin Culhane)
Date: Wed, 5 Dec 2001 16:16:28 +0000 (GMT)
Subject: [Tutor] Re: Tutor digest, Vol 1 #1246 - 19 msgs
In-Reply-To: <E16BbMR-0007Up-00@mail.python.org>
Message-ID: <Pine.OSF.3.96.1011205160049.1696A-100000@chah.ucc.ie>

Dear Phelim,
I'm also a newbie, so got very excited when I thought I could actually
help with your query.. so I had to respond.. exciting times for me.

Have you tried to string.rstrip() to remove trailing space from the
string you are reading in?  

When reading files, I find it easier to read all of the file:
 
file = open(inputfile, 'r')
data = file.readlines()
list =[]
for line in data:
   list.append(line.split())  # add each line in file to list.

Hope this helps
Aedin

--------------------------------
Aedin Culhane
Bioinformatics Group, University College Cork, Cork, Ireland



> --__--__--
> 
> Message: 19
> Date: Wed, 05 Dec 2001 07:40:15 -0500
> From: Andrei Kulakov <sill@optonline.net>
> Subject: Re: [Tutor] Blank line added after reading a line from a file
> To: "'tutor@python.org'" <tutor@python.org>
> Reply-to: ak@silmarill.org
> 
> On Wed, Dec 05, 2001 at 12:29:55PM +0000, Kelly, Phelim wrote:
> > (I'll try this again!)
> > 
> > Hello, 
> > I have a small probelm, hope you can help. I'm reading text from an external
> > file into a python program as follows: 
> > 
> > ---------------------
> > filename = raw_input("Enter the filename to read from: "); 
> > p=0
> > in_file = open(filename,"r")
> > while p < 4:
> >    text = in_file.readline()
> >    list[p]=text #list is an array which stores the content of each line read
> > 
> >                 #in.
> >    p = p + 1
> > in_file.close()
> 
> This would be easier done as:
> 
> in_file = open(filename)
> text = inf_file.readlines()
> lines_1_4 = text[:4]
> 
> That is, assuming file will comfortably fit in memory, which is the case
> with most text files.
> 
> > ---------------------------
> > 
> > The problem I have is that the text that is stored in variable 'text' isn't
> > simply the contents of one line of the file, another blank line is appended
> > onto the end, which causes problems for the rest of the program, so instead
> > of this, 
> > --------------------- 
> > line read in from file 
> > -------------------- 
> > 
> > I get this, 
> > 
> > ------------------- 
> > line read in from file 
> > 
> > ------------------- 
> > Can anyone tell me the command used to get rid of the extra blank line added
> > on? 
> 
> I think this has to do with how you print them out... how do you do
> that?
> 
> > Thanks in advance, 
> > Phelim.



From SBeaudette@banknorth.com  Wed Dec  5 17:31:39 2001
From: SBeaudette@banknorth.com (Beaudette, Sheree)
Date: Wed, 5 Dec 2001 12:31:39 -0500
Subject: [Tutor] Writing to a file on another server
Message-ID: <F3F0BF66F72ED31191FB0004ACB8C5260241501F@ME1OPSEXCH01>

I'm attempting to write to a file but the following code doesn't seem to
work.  I'm not sure where the file is going if anywhere.  I'm working from
my machine and developing on a remote server which is where I'm running the
application that would create this file (the .py file is also located on
this remote server).  I'd like the file to write to another server ideally.
Is this possible?

The following is my code...  I tried using os.chdir but it didn't seem to
work.  I can't get it to write anywhere it seems

By default without specifying a path where should the file go?

def
write_data(itot,jtot,banknos,bankcontrol1,officersbank,officersno,officersdi
v, officersdept):
    import os
    #os.chdir('/temp)'
    i=0
    j=0
    while i <= itot:
        fh=open(bk.txt,"w")
        fh.write('1 3         COL 1 = FORM,  COL 3 = SPOOL CODE\n')
        while j <= jtot:
            fh.write(officersbank[j] + ' ' + officersno[j] + ' ' +
officersdiv[j] + ' ' + officersdept[j] + '\n')
            j=j+1
        i=i+1
    fh.close()
    return 1

Any help would be much appreciated.  I've been working on it for days and am
getting frustrated!!



From ak@silmarill.org  Wed Dec  5 18:22:06 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Wed, 05 Dec 2001 13:22:06 -0500
Subject: [Tutor] Writing to a file on another server
In-Reply-To: <F3F0BF66F72ED31191FB0004ACB8C5260241501F@ME1OPSEXCH01>
References: <F3F0BF66F72ED31191FB0004ACB8C5260241501F@ME1OPSEXCH01>
Message-ID: <20011205132206.A4569@sill.silmarill.org>

On Wed, Dec 05, 2001 at 12:31:39PM -0500, Beaudette, Sheree wrote:
> I'm attempting to write to a file but the following code doesn't seem to
> work.  I'm not sure where the file is going if anywhere.  I'm working from
> my machine and developing on a remote server which is where I'm running the
> application that would create this file (the .py file is also located on
> this remote server).  I'd like the file to write to another server ideally.
> Is this possible?
> 
> The following is my code...  I tried using os.chdir but it didn't seem to
> work.  I can't get it to write anywhere it seems
> 
> By default without specifying a path where should the file go?
> 
> def
> write_data(itot,jtot,banknos,bankcontrol1,officersbank,officersno,officersdi
> v, officersdept):
>     import os
>     #os.chdir('/temp)'
>     i=0
>     j=0
>     while i <= itot:
>         fh=open(bk.txt,"w")

fh = open("bk.txt", "w")    # note quotes surrounding the file name

>         fh.write('1 3         COL 1 = FORM,  COL 3 = SPOOL CODE\n')
>         while j <= jtot:
>             fh.write(officersbank[j] + ' ' + officersno[j] + ' ' +
> officersdiv[j] + ' ' + officersdept[j] + '\n')
>             j=j+1
>         i=i+1
>     fh.close()
>     return 1
> 
> Any help would be much appreciated.  I've been working on it for days and am
> getting frustrated!!
> 
> 
> _______________________________________________
> 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 Dec  5 18:34:11 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed, 05 Dec 2001 10:34:11 -0800
Subject: [Tutor] Blank line added after reading a line from a file
References: <E16BbMR-0007Uf-00@mail.python.org>
Message-ID: <3C0E68A3.A1CBD2AE@ccvcorp.com>

> On Wed, 5 Dec 2001 12:29:55 -0000,
> "Kelly, Phelim" <KellyPhe@logica.com> wrote:

>
> The problem I have is that the text that is stored in variable 'text' isn't
> simply the contents of one line of the file, another blank line is appended
> onto the end, which causes problems for the rest of the program, so instead
> of this,
> ---------------------
> line read in from file
> --------------------
>
> I get this,
>
> -------------------
> line read in from file
>
> -------------------

The issue here is that, when readline() or readlines() reads in your file, it includes the newline character at the end of each line, in the returned string.  Then, presuming that you use the print statement to display your file, print automatically adds a newline at the end of its output.  Thus, it's not that blank lines are appended to what's read in, it's that they're added in when you print things out.  :)

The solution, as others have mentioned, is to use string.strip() on each line, either as you read it in or as you print it.  This will remove any extra whitespace at the start or end of the string.  You could also use string.rstrip() to remove whitespace only at the very end of the string, or use slice notation to chop off only the final character if you think that other whitespace may important to retain.  So, for example:

>>> # note that python uses '\n' to indicate newlines,
>>> # and reproduces them as '\012'
>>> mystring = "\n blah blah blah \n"
>>> # strip all surrounding whitespace
>>> mystring.strip()
'blah blah blah'
>>> # strip only from the right side
>>> mystring.rstrip()
'\012 blah blah blah'
>>> # use slice notation to get all but the last char
>>> mystring[:-1]
'\012 blah blah blah '
>>>

Hope that clarifies things a bit.  :)

Jeff Shannon
Technician/Programmer
Credit International




From ak@silmarill.org  Wed Dec  5 18:41:40 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Wed, 05 Dec 2001 13:41:40 -0500
Subject: [Tutor] Blank line added after reading a line from a file
In-Reply-To: <3C0E68A3.A1CBD2AE@ccvcorp.com>
References: <E16BbMR-0007Uf-00@mail.python.org> <3C0E68A3.A1CBD2AE@ccvcorp.com>
Message-ID: <20011205134140.A4648@sill.silmarill.org>

On Wed, Dec 05, 2001 at 10:34:11AM -0800, Jeff Shannon wrote:
> > On Wed, 5 Dec 2001 12:29:55 -0000,
> > "Kelly, Phelim" <KellyPhe@logica.com> wrote:
> 
> >
> > The problem I have is that the text that is stored in variable 'text' isn't
> > simply the contents of one line of the file, another blank line is appended
> > onto the end, which causes problems for the rest of the program, so instead
> > of this,
> > ---------------------
> > line read in from file
> > --------------------
> >
> > I get this,
> >
> > -------------------
> > line read in from file
> >
> > -------------------
> 
> The issue here is that, when readline() or readlines() reads in your file, it includes the newline character at the end of each line, in the returned string.  Then, presuming that you use the print statement to display your file, print automatically adds a newline at the end of its output.  Thus, it's not that blank lines are appended to what's read in, it's that they're added in when you print things out.  :)
> 
> The solution, as others have mentioned, is to use string.strip() on each line, either as you read it in or as you print it.  This will remove any extra whitespace at the start or end of the string.  You could also use string.rstrip() to remove whitespace only at the very end of the string, or use slice notation to chop off only the final character if you think that other whitespace may important to retain.  So, for example:

Another possible solution is to use readlines() because it simply makes
a list of lines, without adding "\n", and yet another solution is to add
a comma after the print statement, which prevents it from printing a
newline, like this:

print line,

I think readlines() is the cleanest way to deal with this problem..


> 
> >>> # note that python uses '\n' to indicate newlines,
> >>> # and reproduces them as '\012'
> >>> mystring = "\n blah blah blah \n"
> >>> # strip all surrounding whitespace
> >>> mystring.strip()
> 'blah blah blah'
> >>> # strip only from the right side
> >>> mystring.rstrip()
> '\012 blah blah blah'
> >>> # use slice notation to get all but the last char
> >>> mystring[:-1]
> '\012 blah blah blah '
> >>>
> 
> Hope that clarifies things a bit.  :)
> 
> Jeff Shannon
> Technician/Programmer
> Credit International
> 
> 
> 
> _______________________________________________
> 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  Wed Dec  5 18:51:31 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 5 Dec 2001 10:51:31 -0800 (PST)
Subject: [Tutor] string.search    [Documentation conventions]
In-Reply-To: <20011205135143.91375.qmail@web21101.mail.yahoo.com>
Message-ID: <Pine.LNX.4.21.0112051037260.9617-100000@hkn.eecs.berkeley.edu>

On Wed, 5 Dec 2001, john public wrote:

> weeks ago. I have lived with many programmers in the past and I am
> realizing I learned some BASIC by osmosis. Once I find the right tool
> for the job, is there some online documentation that has a real
> example for everything. I checked Guido's tutorial and the Python
> reference library but could only find examples in the abstract.
>
> such as string.search(string,[,pos[,endpos]]) 

Ah!  I understand now.  It's a UNIX convention that when we describe
functions list this, we just braces to tell the user what parts are
optional.  One problem with a convention, though, is that it's not obvious
unless one hears about it.  *grin*

In an example like this, the braces are there to show that pos and endpos
are optional parameters --- you don't need to put braces in yourself.  
Let's take a look at the description of the string.find() function:

"""
find(s, sub[, start[,end]])

Return the lowest index in s where the substring sub is found such that
sub is wholly contained in s[start:end]. Return -1 on failure. Defaults
for start and end and interpretation of negative values is the same as for
slices.
"""

In this case, we don't have to feed in the last two parameters until we
want to.

###
>>> yourname = "john public"
>>> string.find(yourname, "public")
5
>>> string.find(yourname, "john")
0
>>> string.find(yourname, "john", 0)    ## Let's tell it to search from 0
0
>>> string.find(yourname, "john", 1)    ## Another search starting from 1.
-1
>>> string.find(yourname, "public", 0, -1)
-1
>>> string.find(yourname, "publi", 0, -1)
5
###


The last few examples show how we can fill in 'start' and 'end' so that
string.find() limits itself to the grounds we tell it.  In the last case,
we've told it: "You can start searching from the 0th position of yourname,
but only up to (and not including!) the very last -1th position."


Hope this helps!



From dyoo@hkn.eecs.berkeley.edu  Wed Dec  5 18:58:58 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 5 Dec 2001 10:58:58 -0800 (PST)
Subject: [Tutor] Blank line added after reading a line from a file
In-Reply-To: <20011205134140.A4648@sill.silmarill.org>
Message-ID: <Pine.LNX.4.21.0112051054350.9617-100000@hkn.eecs.berkeley.edu>

On Wed, 5 Dec 2001, Andrei Kulakov wrote:
> a list of lines, without adding "\n", and yet another solution is to add
> a comma after the print statement, which prevents it from printing a
> newline, like this:
> 
> print line,


Putting in the comma suppresses print from adding a newline of its own,
but doesn't stop printing newlines if the line itself contains them:

###
>>> def test():
...     print "hello\n"
...     print "hello again\n",
...     print "one more time"
... 
>>> test()
hello

hello again
one more time
###



From dsh8290@rit.edu  Wed Dec  5 19:11:11 2001
From: dsh8290@rit.edu (dman)
Date: Wed, 5 Dec 2001 14:11:11 -0500
Subject: [Tutor] Writing to a file on another server
In-Reply-To: <F3F0BF66F72ED31191FB0004ACB8C5260241501F@ME1OPSEXCH01>; from SBeaudette@banknorth.com on Wed, Dec 05, 2001 at 12:31:39PM -0500
References: <F3F0BF66F72ED31191FB0004ACB8C5260241501F@ME1OPSEXCH01>
Message-ID: <20011205141111.A432@harmony.cs.rit.edu>

On Wed, Dec 05, 2001 at 12:31:39PM -0500, Beaudette, Sheree wrote:
| I'm attempting to write to a file but the following code doesn't seem to
| work.  I'm not sure where the file is going if anywhere.  I'm working from
| my machine and developing on a remote server which is where I'm running the
| application that would create this file (the .py file is also located on
| this remote server).  I'd like the file to write to another server ideally.
| Is this possible?

You can write to a file on a remote server, but it depends on your
network and system configuration how you should do it.  Some options
are :

(your program doesn't know about the network)
    NFS mount
    Samba share

(your program needs to know about the network)
    ftp
    scp
    http (needs a CGI script on the server to accept the POST and
          actually write the file)

    custom client-server setup
    distributed objects (ie CORBA, XML-RPC, DCOM, etc ; this is a form
            of a custom setup)


HTH,
-D

-- 

If your life is a hard drive,
Christ can be your backup.



From wolf_binary@hotmail.com  Wed Dec  5 20:12:32 2001
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Wed, 05 Dec 2001 14:12:32 -0600
Subject: [Tutor] compiling python source files
Message-ID: <F145Tj81KKaJrfzLXTi000211af@hotmail.com>

Dear Python folks,

I would like to understand or be pointed in the right direction to 
information on how the py2exe installer works.  For instance what are these 
used for and how do you make them? (ex:python15.dll, zlib.pyd, and 
exceptions.pyc)
Can't you make a simple window and then compile it so you have an example?  
What about making .com extension files?  What does that entail?  Would 
someone please give me some links to start with.

-thanks,
Cameron Stoner

_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp



From fleet@teachout.org  Thu Dec  6 02:48:18 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Wed, 5 Dec 2001 21:48:18 -0500 (EST)
Subject: [Tutor] Follow up to 'class data'
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C155@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.33.0112052110460.4765-100000@fleet1.paxp.com>

Sorry for delay in replying - out of town.

On Tue, 4 Dec 2001 alan.gauld@bt.com wrote:

> In OO terms classes define templates from which we create objects
> - a better term is instances, it it disambiguates from pythons
> more general idea of objects.
>
> > So to me, the address book is an object and can be a class?
>
> So you could create an AddressBook class which would be a
> template from which you could create multiple instances,
> each of which would be an address book. Each address book
> would have the attributes you define in your AddressBook
> class(the methods and fields) but have their own values
> stored in those fields.  Thus your father's address book may
> hold different names to yours.

Let's say I write a compiled Basic program called AddressBook.exe that
produces a pipe-delimited flat file with names and addresses in it.
Anybody that runs it gets exactly the same address book output; but with
their own data.  One could run several "instances" of it on the same
computer - ie, "business addresses", "personal addresses", "club
addresses", etc.  Where does this differ from a class?

> > I would have thought "address book" would be the class and
> > the means of adding, modifying, deleting data would be "methods."
>
> Could be, and the data itself could be defined as classes
> - Entries for example. Thus:
>
> > The structure as I see it would be something like:
> >
> > class AddressBook:
> >    def input:
> >    def modify:
> >    def delete:
> >    def search:
> >    def sort:
> >    def output:
>
> Is fine, and the entries could look like:
>
> class Entry
>     def input
>     def edit
>     def compare(Entry)
>
> Now we can have an address book that contains different
> types of entry by subclassing Entry:
>
> class Building(Entry)
>     def input
>     etc...
>
> class Person(Entry)
>     def input
>     etc...

You just lost me.  What would be the point?

"Input" would need to handle "name," "address," "email," etc.; but unless
I restrict it, AddressBook.name could just as easily be "Empire State
Building" or "pothole at fifth and main" as it could be John Doe.

> The AddressBoook class writes its methods to use the Entry
> methods(eg compare(Entry) would be used both in searching
> and sorting...) But we can have both types of Entry
> (Building or Person) stored and AddressBook doesn't care,
> it just sees Entries!
>
> > class AddressBook:
> >    class Input(AddressBook):
> >       def inputName:
> >       def inputAddress:
> >       def inputPhone:
>
> Categorically NO. Classes are not functions!

What is the difference between class Input(AddressBook) and class
Entry(AddressBook)?  To me "data input" == "data entry"

> Occasionally, very occasionally, we write classes that look
> like functions but its not normal practice. Similarly its
> not usually a good idea to provide set/get methods for
> every internal attribute - a common beginners mistake.
> Only expose those attributes that the outside world needs
> to see.

I don't think I understand this either.  Do you mean I shouldn't provide
attributes for length, width, thickness, color of cover, etc?  Certainly
one would need to make Name, Address, Phone, etc. "exposed."

> Classes are 'living breathing things' that  know stuff and
> how to deal with that stuff. When thinking about classes
> ask "What does Foo know? And what can Foo do with what it knows?"

This smacks of anthropomorphism.  (And this statement may have a great
deal to do with my lack of "getting it.")

> As Peter Coad says: "Objects do it to themselves"

I found, much to my amazement, OOA and OOP by Peter Coad in my local
library.  OOA will be returned with all but the first 50 pages or so
unread.  Completely incomprehensible to me.  I'm struggling with OOP; but
I haven't quit yet.

				- fleet -



From i812@iname.com  Thu Dec  6 03:35:47 2001
From: i812@iname.com (Rob McGee)
Date: Wed, 5 Dec 2001 21:35:47 -0600
Subject: [Tutor] __cmp__() method examples?
Message-ID: <20011205213547.I27400@hal>

I haven't found many examples of how to do a Class.__cmp__() method. I
have a class whose instances have a certain alphabetic value which
should always be unique. I figured I would only be comparing these class
instances to other instances of the same class, so I chose to compare
based on that alphabetic value.

Maybe an example will clarify:

{code}
import random

class Project:
  def __init__(self, name):
    self.name = name
    self.value = random.randrange(1, 100)
  def __str__(self):
    return self.name
  def __cmp__(self, other):
    if self.name < other.name:  # compare name value (should be unique)
      return -1
    elif self.name > other.name:
      return 1
    else: return 0              # should mean it's the same instance

# now generate class instances -- this is always done automatically
from string import uppercase
for letter in uppercase:
  execStr = letter + ' = Project("' + letter + '")'
  # example -- 'A = Project("A")', 'Z = Project("Z")
  exec(execStr)

{/code}

(Sorry about the exec's, but I really don't know another way to do what
I want. I want these instances in the global namespace, and I need to
know exactly what each one is named. At least I think I do. Suggestions
about other ways to approach this would be welcomed, too. :) Like with
no exec's, or with the instances in something other than globals(), how
would I be able to retrieve and alter their properties?)

The user interacts with these class instances through code like this:

{code}
def getProjectName():
  text = raw_input('Project name: ')
  text = text.upper()
  return text

def objectEntry(text):
  """converts text to an object name"""
  try:
    object = eval(text)
    return object
  except: return

def ifInstance(object, className=Project):
  """returns object if it's an instance of className"""
  try:
    if object.__class__ == className:
      return object
  except: return

def myStupidMenu():
  keepGoing = 1
  while keepGoing:
    prompt = 'stupid menu ("g/x"): '
    choice = raw_input(prompt)
    choice = choice.upper()
    if choice == "G":
      text = getProjectName()
      if text:
        object = objectEntry(text)
        if object:
          instance = ifInstance(object)
          print instance, '=', instance.value
    elif choice == "X":
      keepGoing = 0
    else:
      print "\tyou're as stupid as this menu!"

myStupidMenu()
{/code}

I'm getting errors which indicate that the class instances are being
compared with other objects (AttributeError: object has no "name"
attribute.) I don't know if the sample code here will generate those
errors -- probably not -- but what I'm hoping for is just a little
guidance on how to properly implement a __cmp__() method.

What I think I'll try -- the idea came to me while writing this :) -- is
to put code in Project.__cmp__() like the ifInstance() above. If "other"
isn't an instance of self.__class__, don't try to get other.name.

Oh, I should also mention that I got into an infinite loop with another
class.__cmp__() method. That class was more complicated, and I had
several if/elif loops to compare other attributes. The fourth and final
such loop simply compared "self" and "other". I believe that was where
the loop occurred, and it was in sorting a list of instances of that
class (I don't think there were any non-instance members of the list.)

By removing the self/other raw comparison I eliminated the infinite
loop. But that experience gives me the idea that I'm missing something
about how to do a Class.__cmp__().

Thanks again all,

    Rob - /dev/rob0


From i812@iname.com  Thu Dec  6 04:50:05 2001
From: i812@iname.com (Rob McGee)
Date: Wed, 5 Dec 2001 22:50:05 -0600
Subject: [Tutor] __cmp__() method examples?
In-Reply-To: <20011205213547.I27400@hal>; from i812@iname.com on Wed, Dec 05, 2001 at 09:35:47PM -0600
References: <20011205213547.I27400@hal>
Message-ID: <20011205225005.J27400@hal>

I forgot to mention before that I'm still using Python 2.0, so the rich
comparison methods (introduced in 2.1) won't work. 

    Rob - /dev/rob0


From urnerk@qwest.net  Thu Dec  6 05:08:52 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Wed, 05 Dec 2001 21:08:52 -0800
Subject: [Tutor] Follow up to 'class data'
In-Reply-To: <Pine.LNX.4.33.0112052110460.4765-100000@fleet1.paxp.com>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C155@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <4.2.0.58.20011205210745.02301100@pop3.norton.antivirus>

>
> > Classes are 'living breathing things' that  know stuff and
> > how to deal with that stuff. When thinking about classes
> > ask "What does Foo know? And what can Foo do with what it knows?"
>
>This smacks of anthropomorphism.  (And this statement may have a great
>deal to do with my lack of "getting it.")

Anthromophorphism is useful.  If you empathize with your
objects, you'll write better code.  Disney wouldn't have
gotten anywhere with Mickey Mouse or all those other
cartoons were it not for anthropomorphism.  :-D

Kirby



From urnerk@qwest.net  Thu Dec  6 05:39:29 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Wed, 05 Dec 2001 21:39:29 -0800
Subject: [Tutor] __cmp__() method examples?
In-Reply-To: <20011205213547.I27400@hal>
Message-ID: <4.2.0.58.20011205211011.022fe1a0@pop3.norton.antivirus>

At 09:35 PM 12/5/2001 -0600, Rob McGee wrote:
>I haven't found many examples of how to do a Class.__cmp__() method. I
>have a class whose instances have a certain alphabetic value which
>should always be unique. I figured I would only be comparing these class
>instances to other instances of the same class, so I chose to compare
>based on that alphabetic value.
>
>Maybe an example will clarify:
>
>{code}
>import random
>
>class Project:
>   def __init__(self, name):
>     self.name = name
>     self.value = random.randrange(1, 100)
>   def __str__(self):
>     return self.name
>   def __cmp__(self, other):
>     if self.name < other.name:  # compare name value (should be unique)
>       return -1
>     elif self.name > other.name:
>       return 1
>     else: return 0              # should mean it's the same instance
>
># now generate class instances -- this is always done automatically
>from string import uppercase
>for letter in uppercase:
>   execStr = letter + ' = Project("' + letter + '")'
>   # example -- 'A = Project("A")', 'Z = Project("Z")
>   exec(execStr)
>
>{/code}
>
>(Sorry about the exec's, but I really don't know another way to do what
>I want. I want these instances in the global namespace, and I need to
>know exactly what each one is named. At least I think I do. Suggestions
>about other ways to approach this would be welcomed, too. :)

Hey, s'ok, really.  It's just that some people who want to help
might find this exec piece hard to fathom, so you cut down on
the number willing to look over your shoulder.  Or at least so
I hypothesize.  My suggestion earlier was, even if YOU need to
automatically assign, for the purposes of debugging here on
the list, you could just as well show (as you did in the
Example):

    >>>  A = Project("A")
    >>>  Z = Project("Z")

Of course I have approximately zero understanding of what
you're doing in your off-camera code, but another way to
instantiate a lot of objects and keep them handy is to use
a list, e.g.

    myobjects = []
    for i in range(10):
        myobjects.append(Project())

this would create 10 Project objects in a list called
myobjects, addressable by indexing.

Another approach, if you want to refer to objects by name,
is to use a dictionary, e.g.:

    myobjects = {}
    for name in ['A','B','C','D','E']:
       myobjects[name] = Project()

I don't even bother to give Projects a unique identifier for
internal storage, because I only access 'em through my list
or dictionary, and I know they're different if the index
and/or dictionary key is different.

>Like with
>no exec's, or with the instances in something other than
>globals(), how would I be able to retrieve and alter their
>properties?)

myobjects['A'].property = "new value"

or:

      for each in myobjects:
           myobjects[each].method(arg1,arg2)

E.g.

   >>> myobjects = {}
   >>> myobjects['A']= Project('Kirby')
   >>> myobjects['A'].name
   'Kirby'
   >>> myobjects['A'].name = 'Sally'
   >>> myobjects['A'].name
   'Sally'

This might not look like a big improvement, but on the
bright side, you have all your objects in an "egg carton"
(the myobjects dictionary) and if you want to iterate
through 'em all at any point, this makes it easy.

Just some options you might not have considered.  May not
be applicable.

>The user interacts with these class instances through code like this:
>
>{code}
>def getProjectName():
>   text = raw_input('Project name: ')
>   text = text.upper()
>   return text
>
>def objectEntry(text):
>   """converts text to an object name"""
>   try:
>     object = eval(text)
>     return object
>   except: return

def getobj():
    global myobjects
    objname = raw_input('Project name: ')
    if objname in myobjects.keys():
        return myobjects['objname']
    else:
        return None

>I'm getting errors which indicate that the class instances are being
>compared with other objects (AttributeError: object has no "name"
>attribute.) I don't know if the sample code here will generate those
>errors -- probably not -- but what I'm hoping for is just a little
>guidance on how to properly implement a __cmp__() method.

Yeah, unfortunately, the code you posted has no problems.  I
cut and pasted your class, imported random, and tested it:

  >>> import random
  >>> A = Project('A')
  >>> B = Project('B')
  >>> A==B  # note we're using ==, not =, which would *assign*
            # B to A, thereby screwing us up
  0
  >>> C = Project('A')  # give same name to other object
  >>> C==A
  1

Note that we're returning 1 because that's what we defined
__cmp__ to do.  We say "return 1 if the names are the same".
This does NOT mean that C and A are really the same
instance, i.e. are the same chunk of bytes in memory.
Of course they *aren't*:

   >>> id(A)
   11557216
   >>> id(C)
   11500800

>What I think I'll try -- the idea came to me while writing this :) -- is
>to put code in Project.__cmp__() like the ifInstance() above. If "other"
>isn't an instance of self.__class__, don't try to get other.name.


Yeah, you could do things like that, but you need to get a
better handle on why it's not working in the first place.
Bug fixes of the type "I don't know why this was breaking
but here's a fix", are convenient, but as the patchwork
grows, the code turns opaque, even to the only programmer
with a hope of keeping a grip on it.


>Oh, I should also mention that I got into an infinite loop with another
>class.__cmp__() method. That class was more complicated, and I had
>several if/elif loops to compare other attributes. The fourth and final
>such loop simply compared "self" and "other". I believe that was where
>the loop occurred, and it was in sorting a list of instances of that
>class (I don't think there were any non-instance members of the list.)

Try thinking of using some other data structure, like a list
or dictionary, as per above, to keep objects separate, each
with a unique pointer.  You usually shouldn't have to do
elaborate testing to figure out whether an object is the same
as some other object.

>By removing the self/other raw comparison I eliminated the infinite
>loop. But that experience gives me the idea that I'm missing something
>about how to do a Class.__cmp__().
>
>Thanks again all,
>
>     Rob - /dev/rob0

Note that in recent Pythons you don't have to go through __cmp__
to test for equality, if that's really all you're interested
in (not saying it is).  I.e., you could go:

    class Project:
       def __init__(self, name):
          self.name = name
          self.value = random.randrange(1, 100)
       def __repr__(self):
          return self.name
       def __eq__(self, other):
          if self.name == other.name:
             return 1
          else:  return 0

  >>> A = Project('A')
  >>> J = Project('J')
  >>> A==J
  0
  >>> R = Project('J')
  >>> A==R
  0
  >>> J==R
  1

Kirby




From ak@silmarill.org  Thu Dec  6 05:40:47 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Thu, 06 Dec 2001 00:40:47 -0500
Subject: [Tutor] Blank line added after reading a line from a file
In-Reply-To: <Pine.LNX.4.21.0112051054350.9617-100000@hkn.eecs.berkeley.edu>
References: <20011205134140.A4648@sill.silmarill.org>
 <Pine.LNX.4.21.0112051054350.9617-100000@hkn.eecs.berkeley.edu>
Message-ID: <20011206004047.A6025@sill.silmarill.org>

On Wed, Dec 05, 2001 at 10:58:58AM -0800, Danny Yoo wrote:
> On Wed, 5 Dec 2001, Andrei Kulakov wrote:
> > a list of lines, without adding "\n", and yet another solution is to add
> > a comma after the print statement, which prevents it from printing a
> > newline, like this:
> > 
> > print line,
> 
> 
> Putting in the comma suppresses print from adding a newline of its own,
> but doesn't stop printing newlines if the line itself contains them:

Yes, but the dude's problem was that it'd print *two* new lines. He just
wanted one. That's where comma would help :P.

> 
> ###
> >>> def test():
> ...     print "hello\n"
> ...     print "hello again\n",
> ...     print "one more time"
> ... 
> >>> test()
> hello
> 
> hello again
> one more time
> ###
> 
> 
> _______________________________________________
> 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 rroslan@hotmail.com  Thu Dec  6 06:11:59 2001
From: rroslan@hotmail.com (roslan ramli)
Date: Thu, 06 Dec 2001 14:11:59 +0800
Subject: [Tutor] Pmw
Message-ID: <LAW2-F123unPzmGqoN000006d83@hotmail.com>

<html><div style='background-color:'><DIV>I bought the book Python and Tkinter Programming and it seems that it cannot run on active state python. I downloaded the installation from python.org and have to install the Pmw. What I did was just copy the Pmw into python installation dir. I tried to run the program from the book cal2.py and I get the return message from the interpreter "Pmw has no attribute ScrolledText".</DIV>
<DIV>&nbsp;</DIV>
<DIV>I suspect the book is using a different version Pmw. I am using Pmw 0.8.5 .</DIV>
<DIV>&nbsp;</DIV>
<DIV>I hope someone could help me here.If it is an earlier version , where do I get it.</DIV>
<DIV>&nbsp;</DIV>
<DIV>Thanks.</DIV></div><br clear=all><hr>Get your FREE download of MSN Explorer at <a href='http://go.msn.com/bql/hmtag_itl_EN.asp'>http://explorer.msn.com</a><br></html>


From tim.one@home.com  Thu Dec  6 06:25:24 2001
From: tim.one@home.com (Tim Peters)
Date: Thu, 6 Dec 2001 01:25:24 -0500
Subject: [Tutor] Division
In-Reply-To: <LNBBLJKPBEHFEDALKOLCMELBMKAA.tim.one@home.com>
Message-ID: <LNBBLJKPBEHFEDALKOLCMEGCMLAA.tim.one@home.com>

About -Qnew, it turns out Guido ran into a snag when implementing it, so it
didn't work like PEP 238 said it would work.  Instead it worked the way the
NEWS file said:

   Using -Qnew is questionable; it turns on new division by default, but
   only in the __main__ module.  You can usefully combine -Qwarn
   or -Qwarnall and -Qnew: this gives the __main__ module new division,
   and warns about classic division everywhere else.

As you discovered (thanks for reminding us!), that was questionable indeed.
I've repaired this now:  -Qnew will work as documented by the PEP in 2.2c1
(release candidate 1, due out late next week).

After doing

    pythonw -Qnew tools\idle\idle.pyw

from your 2.2c1 directory, this is what you'll get:

Python 2.2c1 (#26, Dec  6 2001, 00:20:15) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> 1/2
0.5
>>>

Please note the other warnings about -Qnew in the PEP, in particular that it
turns *all* instances of "/" into true division, including those in
3rd-party modules that may not yet be expecting true division.  If you use
true division before it's the default, you're a pioneer, and should expect
bears to try to eat you <wink>.



From flash1210@hotmail.com  Thu Dec  6 07:09:58 2001
From: flash1210@hotmail.com (Frank Holmes)
Date: Wed, 05 Dec 2001 23:09:58 -0800
Subject: [Tutor] defining functions.. why return?
Message-ID: <F111w2UggLHWbw1q8am0000b2d6@hotmail.com>

   I am working my way thru "SAMS teach yourself Python in 24 hrs by Van 
Laningham (funny, it seems to be taking me a lot more than 24 hrs...) and I 
have a question  concerning defining functions.
   In his example (chapter 7 "functions and modules) Mr. Van Lanningham 
shows the following example for defining a function:

1.  def julian_leap (y):
2.  if (y%4)==0:
3.     return 1
4.  return 0

   Concerning the "return" statements, he says the interpreter keeps track 
of the place where the function was called and the return statement just 
means "goto the place in the code that you started from".
   I don't understand... The example gives 2 "return" statements... where 
are they "goto  ing"?
   I used the example function in a form:

for x in years: [1900, 1040, 1968, 1955]
    if julian_leap (x):
          print"1"
    else:
          print "2"

   it seemed to work regardless of whether I used both returns, or either, 
or none at all. So why the "return 1 and return 0 statements?

                                             thanx

_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp



From ak@silmarill.org  Thu Dec  6 07:28:50 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Thu, 06 Dec 2001 02:28:50 -0500
Subject: [Tutor] defining functions.. why return?
In-Reply-To: <F111w2UggLHWbw1q8am0000b2d6@hotmail.com>
References: <F111w2UggLHWbw1q8am0000b2d6@hotmail.com>
Message-ID: <20011206022850.A6363@sill.silmarill.org>

On Wed, Dec 05, 2001 at 11:09:58PM -0800, Frank Holmes wrote:
>   I am working my way thru "SAMS teach yourself Python in 24 hrs by Van 
> Laningham (funny, it seems to be taking me a lot more than 24 hrs...) and I 
> have a question  concerning defining functions.
>   In his example (chapter 7 "functions and modules) Mr. Van Lanningham 
> shows the following example for defining a function:
> 
> 1.  def julian_leap (y):
> 2.  if (y%4)==0:
> 3.     return 1
> 4.  return 0
> 
>   Concerning the "return" statements, he says the interpreter keeps track 
> of the place where the function was called and the return statement just 
> means "goto the place in the code that you started from".

Well, let's say you have this code:

def julian_leap(y):
    [...]
    return

print "blah"
julian_leap(year)
print "dragh"

What happens here is that first it prints 'blah', then it runs the
function, then it reaches 'return' inside function, and then it returns
to the same place between the two print statements, and then it goes to
the next line and print 'dragh'.


>   I don't understand... The example gives 2 "return" statements... where 
> are they "goto  ing"?

When you have two returns, only one of them will run, the first one..:

def func():
    return 1
    return 2

It will always return 1, and never 2, because as soon as it reaches
first 'return', the function "returns", to pun, to wherever it started
from. Normally, if you have 2 returns, at least the first of them is in
some sort of conditional, because if it wasn't, it would make the rest
of the function pointless (it'd never run).


>   I used the example function in a form:
> 
> for x in years: [1900, 1040, 1968, 1955]
>    if julian_leap (x):
>          print"1"
>    else:
>          print "2"
> 
>   it seemed to work regardless of whether I used both returns, or either, 
> or none at all. So why the "return 1 and return 0 statements?

THe thing is, if a function doesn't execute a return statement, it
returns 0 when it finishes.

def func():
    if 0: return 1  # never runs

This function will return 0. In the book you're reading, the function
returns 0 explicitly for clarity. If you drop it, it'll make no
difference.
> 
>                                             thanx
> 
> _________________________________________________________________
> Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp
> 
> 
> _______________________________________________
> 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 urnerk@qwest.net  Thu Dec  6 07:48:49 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Wed, 05 Dec 2001 23:48:49 -0800
Subject: [Tutor] defining functions.. why return?
In-Reply-To: <20011206022850.A6363@sill.silmarill.org>
References: <F111w2UggLHWbw1q8am0000b2d6@hotmail.com>
 <F111w2UggLHWbw1q8am0000b2d6@hotmail.com>
Message-ID: <4.2.0.58.20011205234239.0175a4e0@pop3.norton.antivirus>

>
>THe thing is, if a function doesn't execute a return statement, it
>returns 0 when it finishes.

Not technically correct.  Unless you explicitly return a
value, a function returns None, not 0.

>def func():
>     if 0: return 1  # never runs

   >>> a = func()
   >>> a
   >>> type(a)
   <type 'NoneType'>
   >>> None == func()
   1

>This function will return 0. In the book you're reading,
>the function returns 0 explicitly for clarity. If you drop
>it, it'll make no difference.

Since None evaluates the same as 0 in an if statement,
it's true that dropping 'return 0' in the example given
will work the same.  However, this is not because the
function without a 'return 0' behaves identically.

Some other calling code might look for a return of 0,
and None wouldn't qualify.

   >>> None == 0
   0

Kirby



From ak@silmarill.org  Thu Dec  6 07:57:10 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Thu, 06 Dec 2001 02:57:10 -0500
Subject: [Tutor] defining functions.. why return?
In-Reply-To: <4.2.0.58.20011205234239.0175a4e0@pop3.norton.antivirus>
References: <F111w2UggLHWbw1q8am0000b2d6@hotmail.com>
 <F111w2UggLHWbw1q8am0000b2d6@hotmail.com>
 <4.2.0.58.20011205234239.0175a4e0@pop3.norton.antivirus>
Message-ID: <20011206025710.A6529@sill.silmarill.org>

On Wed, Dec 05, 2001 at 11:48:49PM -0800, Kirby Urner wrote:
> 
> >
> >THe thing is, if a function doesn't execute a return statement, it
> >returns 0 when it finishes.
> 
> Not technically correct.  Unless you explicitly return a
> value, a function returns None, not 0.

Oh, I didn't know that.. thanks.

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


From dyoo@hkn.eecs.berkeley.edu  Thu Dec  6 08:25:48 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 6 Dec 2001 00:25:48 -0800 (PST)
Subject: [Tutor] Py2exe Help (fwd)
Message-ID: <Pine.LNX.4.21.0112060023430.27461-100000@hkn.eecs.berkeley.edu>

Hi Cow,

I should have written that I personally don't have experience with
py2exe... *grin*

It's usually better to use your emailer's "Reply to All" option, so that
the other people on the list too can respond.  I'll forward your message
to the rest of the list for you.  Good luck to you.


---------- Forwarded message ----------
Date: Wed, 5 Dec 2001 16:34:13 -0800 (PST)
From: Cow <cow@esweeet.com>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] Py2exe Help

First off, i have a file called 'a.py', the file i want to compile into a .exe file.  Next, i make a file called 'cow.py'.  'cow.py' is to be the setup file.  I put the following code into it (cow.py):

from distutils.core import setup
import py2exe

setup(name="a", scripts=["a.py"],)

#------END OF CODE---------

to run my setup file that will compile 'a.py', i put the following files into the C:\Python22 folder:

a.py (the file i want to compile into a .exe file)
cow.py (the setup file i programmed)
py2exe


i go into dos, type 'CD Python22' to get to the folder with all of the files in it and type the following command to run cow.py:

python cow.py py2exe

it should work and next convert 'a.py' into an executable file, but instead i get the following error:

C:\PYTHON22>python cow.py py2exe
usage: cow.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: cow.py --help [cmd1 cmd2 ...]
   or: cow.py --help-commands
   or: cow.py cmd --help

error: invalid command 'py2exe' (no module named 'distutils.command.py2exe')

does anyone know what i can do to get my setup program working?

Thanks a lot
-Ryan


--- Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:
>On Wed, 5 Dec 2001, Cow wrote:
>
>> I just downloaded Py2exe and have been playing with it for a long time
>> now, but it doesn't seem to be working for me.  I have read the
>> explaination on how to use it over and over, but i still keep on
>> getting errors.  Can someone here please explain to me how to use it
>> in their own words, because i don't understand the ones that were
>> provided to me in the Py2exe file?
>
>There are a few people here who have some experience with py2exe here.
>What kind of error messages are you getting?  If you can give us the
>literal error messages that you're getting, that may give one of us here
>enough clues to figure out what's happening.
>
>Also, what kind of programs have you tried py2exe on?  Does it work at all
>on simple programs?
>
>I hope that your problem can get fixed quickly.  Good luck!
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

_____________________________________________________________
Free eSweeet Mail - http://www.esweeet.com



From bl_mark@hotmail.com  Thu Dec  6 04:39:02 2001
From: bl_mark@hotmail.com (Barbara Mark)
Date: Wed, 05 Dec 2001 22:39:02 -0600
Subject: [Tutor] Newbie - Format question
Message-ID: <F41WNCR0ZeQCpwDnux50001de66@hotmail.com>

Would someone help with question?  I’m trying to understand nested loops. I 
think I need a comma somewhere but I have tried all locations.  See my codes 
far below for the two most applicable.
I want to code the following output for any small n:

******************* *
1
2 4
3 6 9
.
.
n   2*n   …


******************* *
My pseudocode might be:
For any n,
start at 1
multiple by 1                          =   1        Loop 2
add 1 to that number, equals result a  =   2     This is loop 1

result a multipled by 1                =   2        Loop 2
result a multipled by 2                =   4        Loop 2
add 1 to result a, equals result b     =   3      This is loop 1

result b multipled by 1                =  3         Loop 2
result b multipled by 2                =  6         Loop 2
result b multipled by 3                =  9         Loop 2
add 1 to result b, equals result c     =  4      This is loop 1

In summary, I want to start with 1,
then add 1 each time around (1 + i = j),      =  2, then 3, then 4
then multiple 1 through j times for each:
1
2 4
3 6 9
********************* *
My coding gives gives the correct answer except there is a carrier return 
after each (see farther below).
But I want it to look like this:
1
2  4
3  6  9

I’ve tried commas in different locations, but I can’t get the desired 
result.  Would you help?  Thanks in advance.  - Barbara

Code is as follows:

>>>import sys
>>>i = 1
>>>while (i <= 3):
j = 1
while (j <= i):
  i * j
  j = j + 1
i = i + 1

1
2
4
3
6
9
****************** *
OR

>>>i = 1
>>>while (i <= 3):
j = 1
while (j <= i):
  print i * j,
  j = j + 1
i = i + 1


1 2 4 3 6 9
>>>

But I can’t get inbetween. i,e.
1
2 4
3 6 9




_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp



From dyoo@hkn.eecs.berkeley.edu  Thu Dec  6 08:52:04 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 6 Dec 2001 00:52:04 -0800 (PST)
Subject: [Tutor] defining functions.. why return?
In-Reply-To: <F111w2UggLHWbw1q8am0000b2d6@hotmail.com>
Message-ID: <Pine.LNX.4.21.0112060029220.27461-100000@hkn.eecs.berkeley.edu>

On Wed, 5 Dec 2001, Frank Holmes wrote:

>    I am working my way thru "SAMS teach yourself Python in 24 hrs by Van 
> Laningham (funny, it seems to be taking me a lot more than 24 hrs...) and I 

Hmmm... You might actually find this page interesting: it's Peter Norvig's
essay about the books that claim to "Teach Yourself Foo in 24 Hours".

    http://norvig.com/21-days.html

Personally, I think it might take a bit longer than 24 hours to really
feel comfortable with Python.  But don't feel rushed about the whole
thing; there's no pop quizzes here or anything... *grin*



> have a question  concerning defining functions.
>    In his example (chapter 7 "functions and modules) Mr. Van Lanningham 
> shows the following example for defining a function:
> 
> 1.  def julian_leap (y):
> 2.  if (y%4)==0:
> 3.     return 1
> 4.  return 0
> 
>    Concerning the "return" statements, he says the interpreter keeps
> track of the place where the function was called and the return
> statement just means "goto the place in the code that you started
> from".

One analogy that might give the flavor of this "return" stuff: let's say
you're on the phone with a friend, and someone else calls you.  If you
have a nice phone, you can put your friend on hold, and answer the call.  
When you're done, you can switch and return back to your patiently waiting
friend.


In one sense, we can simulate this in Python:

###
>>> def chatWithFriend():
...    print "Anyway, I was about to knock on Knuth's door, when..."
...    print "Hold on, I'm getting a call."
...    putFriendOnHoldAndAnswer()
...    print "Hmmm... wrong number.  Anyway, where were we?"
...    return
... 
>>> def putFriendOnHoldAndAnswer():
...    print "hello?  hello?"
...    return
... 
>>> chatWithFriend()
Anyway, I was about to knock on Knuth's door, when...
Hold on, I'm getting a call.
hello?  hello?
Hmmm... wrong number.  Anyway, where were we?
###


"return" has to do with the idea that when we call
putFriendOnHoldAndAnswer() within chatWithFriend(), we want to make sure
we get back to resume the conversation.  In this case, after
putFriendOnHoldAndAnswer() is done, we're "return"ing back to where we
left off.



Functions are really nice because of this returning behavior: we can build
small functions that use other functions to do all the heavy lifting.  
Here's an example of using functions:

###
>>> def square(x):             
...     return x * x
... 
>>> def sqrt(x):
...     return x**0.5
... 
>>> def hypotenuse(side_a, side_b):
...     return sqrt(square(side_a) + square(side_b))
... 
>>> hypotenuse(3, 4)
5.0
###

The thing to see is that hypotenuse() is asking square() to give it the
squares of side_a and side_b.  square() is doing all these calculations,
and "returning" those values back to hypotenuse().  If we call square()
directly:

###
>>> square(42)
1764
###

that's ok, since it's returning its value back to us, the
interpreter.  And we can also call sqrt(), independent of anything else:

###
>>> sqrt(42)
6.4807406984078604
###

but what's really neat is what happens when we write functions that use
other functions: that's where "return" really comes into play.



From toodles@yifan.net  Thu Dec  6 09:36:11 2001
From: toodles@yifan.net (Andy W)
Date: Thu, 6 Dec 2001 17:36:11 +0800
Subject: [Tutor] Newbie - Format question
References: <F41WNCR0ZeQCpwDnux50001de66@hotmail.com>
Message-ID: <000d01c17e39$72f02160$0300a8c0@sun>

> >>>i = 1
> >>>while (i <= 3):
> j = 1
> while (j <= i):
>   print i * j,
>   j = j + 1
> i = i + 1
>
>
> 1 2 4 3 6 9
> >>>
>
> But I can't get inbetween. i,e.
> 1
> 2 4
> 3 6 9

Hi Barbara,

Try this:

i=1
while i<=3:
   j=1
   while j<=i:
      print i*j,
      j=j+1 #What version of Python are you using? If you're using 2.0 or
later you can use j+=1 to have the same effect.
   print '' #This line is required to print a newline. Because you have the
comma at the end of "print i*j," it just keeps going...
   i=i+1

HTH,
Andy



From KellyPhe@logica.com  Thu Dec  6 09:52:14 2001
From: KellyPhe@logica.com (Kelly, Phelim)
Date: Thu, 6 Dec 2001 09:52:14 -0000
Subject: [Tutor] Blank line added after reading a line from a file
Message-ID: <C9054F12A3EED311B0160090274D912105C1A839@shannon.ie.logica.com>

Jeff, Andrei,
            I got that problem fixed using one of the lines you gave me. The
line of text was read in with an extra blank line, it wasn't just the print
command that added it on. I got rid of the blank line using line 4 below:

--------------------------
in_file = open(filename,"r")
while p < 4:
   text = in_file.readline()
   text = text[:-1]         #deletes extra line
   list[p]=text
   p = p + 1
in_file.close()
---------------------------

Thanks very much for your help!

-----Original Message-----
From: Andrei Kulakov [mailto:sill@optonline.net]
Sent: 05 December 2001 18:42
To: tutor@python.org
Subject: Re: [Tutor] Blank line added after reading a line from a file


On Wed, Dec 05, 2001 at 10:34:11AM -0800, Jeff Shannon wrote:
> > On Wed, 5 Dec 2001 12:29:55 -0000,
> > "Kelly, Phelim" <KellyPhe@logica.com> wrote:
> 
> >
> > The problem I have is that the text that is stored in variable 'text'
isn't
> > simply the contents of one line of the file, another blank line is
appended
> > onto the end, which causes problems for the rest of the program, so
instead
> > of this,
> > ---------------------
> > line read in from file
> > --------------------
> >
> > I get this,
> >
> > -------------------
> > line read in from file
> >
> > -------------------
> 
> The issue here is that, when readline() or readlines() reads in your file,
it includes the newline character at the end of each line, in the returned
string.  Then, presuming that you use the print statement to display your
file, print automatically adds a newline at the end of its output.  Thus,
it's not that blank lines are appended to what's read in, it's that they're
added in when you print things out.  :)
> 
> The solution, as others have mentioned, is to use string.strip() on each
line, either as you read it in or as you print it.  This will remove any
extra whitespace at the start or end of the string.  You could also use
string.rstrip() to remove whitespace only at the very end of the string, or
use slice notation to chop off only the final character if you think that
other whitespace may important to retain.  So, for example:

Another possible solution is to use readlines() because it simply makes
a list of lines, without adding "\n", and yet another solution is to add
a comma after the print statement, which prevents it from printing a
newline, like this:

print line,

I think readlines() is the cleanest way to deal with this problem..


> 
> >>> # note that python uses '\n' to indicate newlines,
> >>> # and reproduces them as '\012'
> >>> mystring = "\n blah blah blah \n"
> >>> # strip all surrounding whitespace
> >>> mystring.strip()
> 'blah blah blah'
> >>> # strip only from the right side
> >>> mystring.rstrip()
> '\012 blah blah blah'
> >>> # use slice notation to get all but the last char
> >>> mystring[:-1]
> '\012 blah blah blah '
> >>>
> 
> Hope that clarifies things a bit.  :)
> 
> Jeff Shannon
> Technician/Programmer
> Credit International
> 
> 
> 
> _______________________________________________
> 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

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

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 sheree@psouth.net  Thu Dec  6 11:11:25 2001
From: sheree@psouth.net (Sheree Beaudette)
Date: Thu, 6 Dec 2001 06:11:25 -0500
Subject: [Tutor] Writing to a file on another server
Message-ID: <000301c17e46$bfb4eb40$01de723f@u1v62>

> Subject:	Writing to a file on another server
> 
> I'm attempting to write to a file but the following code doesn't seem
to
> work.  I'm not sure where the file is going if anywhere.  I'm working
from
> my machine and developing on a remote server which is where I'm
running
> the application that would create this file (the .py file is also
located
> on this remote server).  I'd like the file to write to another server
> ideally.  Is this possible?
> 
> The following is my code...  I tried using os.chdir but it didn't seem
to
> work.  I can't get it to write anywhere it seems
> 
> By default without specifying a path where should the file go?
> 
> def
>
write_data(itot,jtot,banknos,bankcontrol1,officersbank,officersno,office
rs
> div, officersdept):
>     import os
>     #os.chdir('/temp)'
>     i=0
>     j=0
>     while i <= itot:
>         fh=open(bk.txt,"w")
>         fh.write('1 3         COL 1 = FORM,  COL 3 = SPOOL CODE\n')
>         while j <= jtot:
>             fh.write(officersbank[j] + ' ' + officersno[j] + ' ' +
> officersdiv[j] + ' ' + officersdept[j] + '\n')
>             j=j+1
>         i=i+1
>     fh.close()
>     return 1
> 
> Any help would be much appreciated.  I've been working on it for days
and
> am getting frustrated!!
> 
I am working on a Windows NT machine.  The remote server is also Windows
NT.  The server I want to write to is a Novell server.



From alan.gauld@bt.com  Thu Dec  6 11:37:37 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 6 Dec 2001 11:37:37 -0000
Subject: [Tutor] Follow up to 'class data'
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C173@mbtlipnt02.btlabs.bt.co.uk>

> > In OO terms classes define templates from which we create objects
> > - a better term is instances, it it disambiguates from pythons
> > more general idea of objects.

> Let's say I write a compiled Basic program called AddressBook.exe that
> produces a pipe-delimited flat file with names and addresses in it.
> Anybody that runs it gets exactly the same address book 
> output; but with
> their own data.  One could run several "instances" of it on the same
> computer - ie, "business addresses", "personal addresses", "club
> addresses", etc.  Where does this differ from a class?

At that level not at all. The program is acting as a cookie cutter
for different instances of address book.

> > class Entry

> > Now we can have an address book that contains different
> > types of entry by subclassing Entry:
> >
> > class Building(Entry)
> >
> > class Person(Entry)
> 
> You just lost me.  What would be the point?

Because you would likely do the same operations on all sorts 
of Entries but do them slightly differently depending on the 
Entry type. A building has a single name but a person has 
first and last for example...
Sorting would likely be by address say for a building but 
by last name for a person so the compare method of each would 
be different.

> I restrict it, AddressBook.name could just as easily be "Empire State
> Building" or "pothole at fifth and main" as it could be John Doe.

Could be, but thats a data oriented view. When you come to 
use those entries you would find the soirting, searching etc 
very limited in effectiveness if you treat them all the same.

> > > class AddressBook:
> > >    class Input(AddressBook):
> >
> > Categorically NO. Classes are not functions!
> 
> What is the difference between class Input(AddressBook) and class
> Entry(AddressBook)?  To me "data input" == "data entry"

Maybe I misunderstood the intent. I thought the Input class
was intended to capture all the different ways to read input.
The Entry class by comparison holds an actual addressbook item
- including how it reads its own input etc.

> I don't think I understand this either.  Do you mean I 
> shouldn't provide attributes for length, width, thickness, 
> color of cover, etc? 

No, provide the attributes by all means, but don't necessarily 
provide methods to:

getLength/setLength, getWidth/setWidth.
(This is rarely seen in Python because attributes are 'public' 
by default. But in languages like C_++/Java it is common for 
beginners to proivide a bunch of attributes and then a bunch 
of get/set methods to access them - this completely destroys 
the OOP way of working!)

> one would need to make Name, Address, Phone, etc. "exposed."

Absolutely. So for these get/set would be OK.
But let's imagine Address is represented by several 
fields: HouseNo, Street, Town etc

We only need to print Address not the separate Fields
(at Address Book level) so we only need a getAddress method 
not individual ones for each field. That method would output 
all the fields in one go. Of course a better solution is to 
make Adddress an object in its own right.... but even then 
we may not need get/set for each field.

> > Classes are 'living breathing things' that  know stuff and
> This smacks of anthropomorphism.  

Absolutely correct and that's how you can approach OOP.
The objects are 'alive', they communicate with each other 
via messages. 

> > As Peter Coad says: "Objects do it to themselves"
> 
> I found, much to my amazement, OOA and OOP by Peter Coad in my local
> library.  OOA will be returned with all but the first 50 pages or so
> unread.  

Please read the rest too. Coad's OOA is a great intro to OO and one 
of the books that really made the light come on for me when I first 
read it - 10 years ago, eek!

> Completely incomprehensible to me.  I'm struggling with OOP; 

The OOP book is very good but requires that you understand 
the OOA stuff first to be honest. Timothy Budd does the same 
kind of thing as Coad's OOP book but IMHO does it better...

Stick with it, it does make sense eventually.

Alan g.


From tjenkins@devis.com  Thu Dec  6 13:41:35 2001
From: tjenkins@devis.com (Tom Jenkins)
Date: 06 Dec 2001 08:41:35 -0500
Subject: [Tutor] Py2exe Help (fwd)
In-Reply-To: <Pine.LNX.4.21.0112060023430.27461-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.21.0112060023430.27461-100000@hkn.eecs.berkeley.edu>
Message-ID: <1007646096.3855.26.camel@asimov>

Hi Cow,

[snip]

> ---------- Forwarded message ----------
> Date: Wed, 5 Dec 2001 16:34:13 -0800 (PST)
> From: Cow <cow@esweeet.com>
> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] Py2exe Help
> 
> First off, i have a file called 'a.py', the file i want to compile into a .exe file.  Next, i make a file called 'cow.py'.  'cow.py' is to be the setup file.  I put the following code into it (cow.py):
> 
[snip]

> i go into dos, type 'CD Python22' to get to the folder with all of the files in it and type the following command to run cow.py:
> 
> python cow.py py2exe
> 
> it should work and next convert 'a.py' into an executable file, but instead i get the following error:
> 
> C:\PYTHON22>python cow.py py2exe
> usage: cow.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
>    or: cow.py --help [cmd1 cmd2 ...]
>    or: cow.py --help-commands
>    or: cow.py cmd --help
> 
> error: invalid command 'py2exe' (no module named 'distutils.command.py2exe')
> 
> does anyone know what i can do to get my setup program working?
> 
> Thanks a lot
> -Ryan
> 

I believe you have the parameters reversed.  Try:
python py2exe cow.py

this tells python to run py2exe.py and pass cow.py to py2exe as a
parameter.
 
-- 

Tom Jenkins
Development InfoStructure
http://www.devis.com




From alan.gauld@bt.com  Thu Dec  6 13:56:05 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 6 Dec 2001 13:56:05 -0000
Subject: [Tutor] Writing to a file on another server
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C175@mbtlipnt02.btlabs.bt.co.uk>

>     #os.chdir('/temp)'

The last quote is outside the parens....

>         fh=open(bk.txt,"w")

bk.txt is the name of the file and a string so should be in quotes.

Alan g


From alan.gauld@bt.com  Thu Dec  6 13:59:51 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 6 Dec 2001 13:59:51 -0000
Subject: [Tutor] compiling python source files
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C176@mbtlipnt02.btlabs.bt.co.uk>

> What about making .com extension files?  

These are obsolete now. They were basically executable files 
that fitted inside a single memory segment of 64Kb on a 8086 
processor! As such they cpould iudse a simpler, faster memory 
model than .exes

Unless you are using a very old PC you have no need of .com 
files. You can of course change the name of a .exe to a .com
if it makes you feel better! :-)

Alan g.


From alan.gauld@bt.com  Thu Dec  6 14:19:21 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 6 Dec 2001 14:19:21 -0000
Subject: [Tutor] __cmp__() method examples?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C177@mbtlipnt02.btlabs.bt.co.uk>

> from string import uppercase
> for letter in uppercase:
>   execStr = letter + ' = Project("' + letter + '")'
>   # example -- 'A = Project("A")', 'Z = Project("Z")
>   exec(execStr)
> 
> (Sorry about the exec's, but I really don't know another way 

How about:

letters = {}
letters[letter] = Project(letter)

That's what the exec is doing for you under the hood 
- adding a new variable A,B,C etc to the global 
namespace dictionary. 

Now you can access your objects as:

print letter["A"]

etc.

> I want. I want these instances in the global namespace, and I need to
> know exactly what each one is named. 

Any good reason why you'd want them global?

Alan G


From fleet@teachout.org  Thu Dec  6 14:25:12 2001
From: fleet@teachout.org (fleet@teachout.org)
Date: Thu, 6 Dec 2001 09:25:12 -0500 (EST)
Subject: [Tutor] Follow up to 'class data'
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C173@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.33.0112060916510.5996-100000@fleet1.paxp.com>

On Thu, 6 Dec 2001 alan.gauld@bt.com wrote:

> At that level not at all. The program is acting as a cookie cutter
> for different instances of address book.

Perhaps I asked the wrong question.  If all I want is to use Python for a
scripting language and some simple programs, is OOP perhaps overkill?

I think I'm going to drop this discussion; as I feel myself becoming
argumentative.  It's frustrating and I still don't "get it."

I'll try to finish Coads OOP and may even take another crack at his OOA.
Thanks very much for the conversation.  I'll probably be back.

Regards,
				- fleet -





From alan.gauld@bt.com  Thu Dec  6 14:31:43 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 6 Dec 2001 14:31:43 -0000
Subject: [Tutor] defining functions.. why return?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C178@mbtlipnt02.btlabs.bt.co.uk>

> shows the following example for defining a function:
> 
> 1.  def julian_leap (y):
> 2.  if (y%4)==0:
> 3.     return 1
> 4.  return 0

First lines 2-4 should be indented 

def julian_leap (y):
  if (y%4)==0:
     return 1
  return 0

>    Concerning the "return" statements, he says the 
> interpreter keeps track of the place where the 
> function was called and the return statement just 
> means "goto the place in the code that you 
> started from".

Thats correct although in this case it also substitutes 
the returned value for the function, thus:

test = julian_leap(1999)
print test

jumping into the function and the "return 0" line has the 
effect of returning to the first line with the function 
call replaced by the retuned value(0) so test gets set
to 0. Then when we print test we get 0 out.

>    I don't understand... The example gives 2 "return" 
> statements... 

But only 1 will ever be executed. If the first one(inside the if statement)
gets executred the program will never reach the second one. If the 'if' test
fails the program drops through to the second return statement.

Thus the function either returns 1(which python considers 'true') 
or 0(which python thinks means 'false).

> are they "goto  ing"?

Back to the line that the function was called from.
test = julian_leap(1999) 
in the case above.

> for x in years: [1900, 1040, 1968, 1955]

This is wrong syntax, the colon must come at the end 
and you don't need the 'years' bit, see below

>     if julian_leap (x):
>           print"1"
>     else:
>           print "2"

Try changing it to:

for x in [1900, 1040, 1968, 1955]:
     print julian_leap (x)

You should get a set of 1 or 0 results printed

Alan G.


From alan.gauld@bt.com  Thu Dec  6 14:36:12 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 6 Dec 2001 14:36:12 -0000
Subject: [Tutor] Newbie - Format question
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C179@mbtlipnt02.btlabs.bt.co.uk>

> >>>i = 1
> >>>while (i <= 3):
> j = 1
> while (j <= i):
>   print i * j,
>   j = j + 1
  print        # force a new line after each inner loop
> i = i + 1

should fix it.

Alan g


From alan.gauld@bt.com  Thu Dec  6 14:41:05 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 6 Dec 2001 14:41:05 -0000
Subject: [Tutor] Follow up to 'class data'
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C17A@mbtlipnt02.btlabs.bt.co.uk>

> Perhaps I asked the wrong question.  If all I want is to use 
> Python for a scripting language and some simple programs, 
> is OOP perhaps overkill?

Definitely.
Until you want to reuse some code you already wrote later 
- in that case having it inside objects makes life much easier.
But for short programs OOP is indeed oiverkill, its bewnefits 
are when things start to get bigger and need more control.

> I think I'm going to drop this discussion; as I feel myself becoming
> argumentative.  It's frustrating and I still don't "get it."

I read once that it takes experienced, professional 
programmers from 6 months to 2 years to transition 
from procedural to OO thinking. Don't worry about not 
getting it, its not essential for most things.

Probably, as you use other people's objects(in the python
library say) it'll come clearer and eventually you'll 
feel natural with it.

Alan G.


From kromag@nsacom.net  Thu Dec  6 15:37:14 2001
From: kromag@nsacom.net (kromag@nsacom.net)
Date: Thu, 6 Dec 2001 09:37:14 -0600 (CST)
Subject: [Tutor] Unicode ala Mode
Message-ID: <200112061537.fB6FbES15824@pop.nsacom.net>

I have a request and a question about unicodedata.

First, can anyone supply me with some examples of python scripts using 
unicode? I am interested in displaying various asian characters (kanji, etc.).

Second, I am confused as to whether the curses module can display unicode 
characters properly in a terminal that supports said characters?

Thanks!

d


From urnerk@qwest.net  Thu Dec  6 15:56:55 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Thu, 06 Dec 2001 07:56:55 -0800
Subject: [Tutor] Newbie - Format question
In-Reply-To: <F41WNCR0ZeQCpwDnux50001de66@hotmail.com>
Message-ID: <4.2.0.58.20011206074719.01d94f00@pop3.norton.antivirus>

>
>But I can't get inbetween. i,e.
>1
>2 4
>3 6 9

Hi Barbara --

A couple more solutions, just for fun:

  >>> def sequences(max):
         for b in range(1,max+1):
             for a in range(1,b+1):
                 print a*b,
             print


  >>> sequences(5)
  1
  2 4
  3 6 9
  4 8 12 16
  5 10 15 20 25

  >>> def sequences(max):
          for b in range(1,max+1):
             print ' '.join([str(a*b) for a in range(1,b+1)])

  >>> sequences(5)
  1
  2 4
  3 6 9
  4 8 12 16
  5 10 15 20 25

Kirby



From dsh8290@rit.edu  Thu Dec  6 16:11:08 2001
From: dsh8290@rit.edu (dman)
Date: Thu, 6 Dec 2001 11:11:08 -0500
Subject: [Tutor] Writing to a file on another server
In-Reply-To: <000301c17e46$bfb4eb40$01de723f@u1v62>; from sheree@psouth.net on Thu, Dec 06, 2001 at 06:11:25AM -0500
References: <000301c17e46$bfb4eb40$01de723f@u1v62>
Message-ID: <20011206111108.A17327@illinois.cs.rit.edu>

On Thu, Dec 06, 2001 at 06:11:25AM -0500, Sheree Beaudette wrote:

| I am working on a Windows NT machine.  The remote server is also Windows
| NT.  The server I want to write to is a Novell server.

How does your system access the server?  How do your other apps access
it (eg, notepad)?

My guess is that it is a samba share, and you either access it by
mapping it to a drive letter 
    z:\path\to\file.txt
or with a complete samba path
    \\servername\path\to\file.txt

In either case (but use the right path),

f = open( "\\servername\path\to\file.txt" , "w" )
f.write( "hello world!" )
f.close()

will do what you want.  This is the neat thing about having the system
mount remote filesystems as treat them as local -- none of the
applications have to know or care!

-D

-- 

He who finds a wife finds what is good
    and receives favor from the Lord.
        Proverbs 18:22



From urnerk@qwest.net  Thu Dec  6 16:14:15 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Thu, 06 Dec 2001 08:14:15 -0800
Subject: [Tutor] How to introduce OO?
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C17A@mbtlipnt02.btlabs
 .bt.co.uk>
Message-ID: <4.2.0.58.20011206075915.01e16930@pop3.norton.antivirus>


> > Perhaps I asked the wrong question.  If all I want is to use
> > Python for a scripting language and some simple programs,
> > is OOP perhaps overkill?

At 02:41 PM 12/6/2001 +0000, alan.gauld@bt.com replied:

>Definitely.

I like to introduce Python's OO with operator overriding,
as here's something you can do with objects that you
simply cannot do procedurally.

Suppose I want numbers that, when multiplied together,
return a*b mod n, i.e. the remainder of the product a*b,
after being divided by some modulus n.

   class Modno:

         def __init__(self,val,mod):
            self.value = val
            self.mod = mod

         def __mul__(self,other):
            product = (self.value * other.value) % self.mod
            return Modno(product,self.mod)

        def __repr__(self):
            return str(self.value)


  >>> from play import Modno

  >>> a = Modno(4,5)
  >>> b = Modno(3,5)
  >>> a*b
  2
  >>> c=a*b       # a*b returns a Modno, usable right away
  >>> c*c*c*c     # using c, a Modno, returned by a*b
  1

Of course you can write a modmul procedure that takes
ordinary integers a,b and returns the product mod some
global n.  But you don't get to use * (multiplication
symbol) as a binary operator.

I then enhance the above class with __add__ which works
the same way:  returns (a + b) mod n.  Then add a __pow__
so you can exponentiate c (c**4 instead of c*c*c*c).
Then add __div__...  lotsa fun.

More code to ensure val<mod, only integers, a,b have
same mod before multiplying etc. etc. is optional.

None of this is entirely trivial in the sense of "without
application".  Learning some modular arithmetic is a
good intro to elementary group and number theory, and
an entre into cryptography.  I pursue these topics, with
Python, here: http://www.inetarena.com/~pdx4d/ocn/crypto0.html

Kirby



From fpeavy@pop.net  Thu Dec  6 16:28:55 2001
From: fpeavy@pop.net (Frank Peavy)
Date: Thu, 06 Dec 2001 08:28:55 -0800
Subject: [Tutor] sitecustomize.py - How & When to Use?
Message-ID: <5.1.0.14.0.20011206082540.00a6d440@mail45566.popserver.pop.net>

I have numerous questions related to setting up the Python environment(like 
PATHs), so I will break them up into different messages with different 
SUBJECTs.

Does anyone use the sitecustomize.py script to setup their PATHs?
I understand that this script runs every time you run PYTHON(on Mac, PC, Unix).
If so, how are you using?



From fpeavy@pop.net  Thu Dec  6 16:30:53 2001
From: fpeavy@pop.net (Frank Peavy)
Date: Thu, 06 Dec 2001 08:30:53 -0800
Subject: [Tutor] set environment variables..? Related to PATHS
Message-ID: <5.1.0.14.0.20011206082857.00a72dd0@mail45566.popserver.pop.net>

How does one set environment variables?
What and how are these variables used?



From fpeavy@pop.net  Thu Dec  6 16:33:40 2001
From: fpeavy@pop.net (Frank Peavy)
Date: Thu, 06 Dec 2001 08:33:40 -0800
Subject: [Tutor] PYTHONPATH - PATHS, again
Message-ID: <5.1.0.14.0.20011206083059.00a71670@mail45566.popserver.pop.net>

I have seen reference to PYTHONPATH in various websites, specifically 
having to do with module set up. What is PYTHONPATH? How is it used?

Incidentally, I relate this to the PATH statement in the AUTOEXEC.BAT in 
the DOS/Windows environment, but I am not sure if they are the same.



From israel@lith.com  Thu Dec  6 16:45:47 2001
From: israel@lith.com (Israel Evans)
Date: Thu, 6 Dec 2001 08:45:47 -0800
Subject: [Tutor] PYTHONPATH - PATHS, again
Message-ID: <AF020C5FC551DD43A4958A679EA16A15017B3E85@abbott.lith.com>

I have found that PYTHONPATH is very much like PATH, but it is not the same
thing.  It is normal and correct to have both.  PYTHONPATH seems to be to
python what PATH is to the rest of the system only tailored to be specific
to Python.

You can set PYTHONPATH the same way PATH is set in the AUTOEXEC.BAT, or if
you are using winNT/2k/xp you can go to Start Menu/ Settings/ Control Panel/
System/Advanced /Environment Variables/  and once there you can set up a new
System Variable called PYTHONPATH.  Make sure it follows the format of the
other variables but include all of the locations you want to run Python
from.

Hope that Helps and is All correct.  


~Israel~

-----Original Message-----
From: Frank Peavy [mailto:fpeavy@pop.net] 
Sent: Thursday, December 06, 2001 8:34 AM
To: tutor-python.org
Subject: [Tutor] PYTHONPATH - PATHS, again

I have seen reference to PYTHONPATH in various websites, specifically 
having to do with module set up. What is PYTHONPATH? How is it used?

Incidentally, I relate this to the PATH statement in the AUTOEXEC.BAT in 
the DOS/Windows environment, but I am not sure if they are the same.


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


From fpeavy@pop.net  Thu Dec  6 16:38:23 2001
From: fpeavy@pop.net (Frank Peavy)
Date: Thu, 06 Dec 2001 08:38:23 -0800
Subject: [Tutor] sys.path..... - PATH, one more time...
Message-ID: <5.1.0.14.0.20011206083401.00a71500@mail45566.popserver.pop.net>

I have seen reference to sys.path and have looked at the Library Reference 
but I am unsure how it works.

If I have the statement:

sys.path.append(variableName)

does this append variableName to my PATH?
If my path for my py scripts is:

C:\Python 2.1\pys

Does this statement result in:

C:\Python 2.1\pys\variableName

?? Please advise. Thanks.



From ak@silmarill.org  Thu Dec  6 17:05:49 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Thu, 06 Dec 2001 12:05:49 -0500
Subject: [Tutor] sys.path..... - PATH, one more time...
In-Reply-To: <5.1.0.14.0.20011206083401.00a71500@mail45566.popserver.pop.net>
References: <5.1.0.14.0.20011206083401.00a71500@mail45566.popserver.pop.net>
Message-ID: <20011206120549.A9151@sill.silmarill.org>

On Thu, Dec 06, 2001 at 08:38:23AM -0800, Frank Peavy wrote:
> I have seen reference to sys.path and have looked at the Library Reference 
> but I am unsure how it works.
> 
> If I have the statement:
> 
> sys.path.append(variableName)
> 
> does this append variableName to my PATH?
> If my path for my py scripts is:
> 
> C:\Python 2.1\pys
> 
> Does this statement result in:
> 
> C:\Python 2.1\pys\variableName
> 
> ?? Please advise. Thanks.

No, more like:

my_path = "C:\\Python 2.1\\pys"
sys.path.append(my_path)

It may be that you need backslash right before the space, too, but I'm
not sure. I don't have a windows system here. Try both ways.

> 
> 
> _______________________________________________
> 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 alan.gauld@bt.com  Thu Dec  6 17:25:31 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 6 Dec 2001 17:25:31 -0000
Subject: [Tutor] PYTHONPATH - PATHS, again
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C17E@mbtlipnt02.btlabs.bt.co.uk>

> I have seen reference to PYTHONPATH in various websites, specifically 
> having to do with module set up. What is PYTHONPATH? How is it used?

It is a pointer to tell python where to find the modules that
are imported by programs. It is similar to the program PATH used 
by the OS to find the executable files to run.

Thus when python comes out of the box it sets its home directory 
and knows to look there for builtin modules. But if you 
download extension modules or write your own it doesn't know 
where to look for them. Thus it looks at the directories 
listed in PYTHONPATH.

It is st as an environment variable(see my other post)

> Incidentally, I relate this to the PATH statement in the 
> AUTOEXEC.BAT in the DOS/Windows environment, 

Same format but different name. It does a very similar job.
FWIW here's mine from AUTROEXEC.BAT:

set PYTHONPATH=D:\PROJECTS\PYTHON;D:\LIBS\PYTHON

Thus I keep any modules I've finished in LIBS\PYTHON and 
new work under construction will be in Projects\Python.

Alan G.


From alan.gauld@bt.com  Thu Dec  6 17:28:02 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 6 Dec 2001 17:28:02 -0000
Subject: [Tutor] PYTHONPATH - PATHS, again
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C17F@mbtlipnt02.btlabs.bt.co.uk>

> other variables but include all of the locations you want to 
> run Python from.

Its not so much where you want to run Pyuthon from its 
where you want python to look for modules.

So when in a program you say

import mySuperModule

the file mySuperModule.py should live in one of the 
directories listed in PYTHONPATH.

Alan g.


From alan.gauld@bt.com  Thu Dec  6 17:31:18 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 6 Dec 2001 17:31:18 -0000
Subject: [Tutor] sys.path..... - PATH, one more time...
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C180@mbtlipnt02.btlabs.bt.co.uk>

> I have seen reference to sys.path and have looked at the 
> Library Reference but I am unsure how it works.

As I understand it Python appends the contents of PYTHONPATH 
to the sys.path.

I think it first inserts the standard values already loaded
from the registry, then adds the PYTHONPATH ones.

But I could be wrong about that bit. You can add values 
to sys.path at run time and it has the same effect as if you'd 
added them to PYTHONPATH. The advantage is that PYTHONPATH only 
gets set when you run AUTOEXEC.BAT. Setting sys.path takes 
immediate effect.

Alan g.


From KellyPhe@logica.com  Thu Dec  6 17:46:07 2001
From: KellyPhe@logica.com (Kelly, Phelim)
Date: Thu, 6 Dec 2001 17:46:07 -0000
Subject: [Tutor] passing in string from command line
Message-ID: <C9054F12A3EED311B0160090274D912105C1A84D@shannon.ie.logica.com>

Another Basic enough question I hope you can help with!

I'm reading in values from the command line that I want to assign to
variables within the code, i.e

>>python file.py number word

I know how to pass the typed number into a variable, i.e,

--------------------
try:
   variable1 =int(sys.argv[1])
except:
   print "Sorry, but you did not enter a number"
   sys.exit()
-------------------

What's the equivalent to "variable1 =int(sys.argv[1])" for assigning the
entered word to a variable, something like this??????........
"variable2 =string(sys.argv[2])"

Thanks in advance.

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 jeff@ccvcorp.com  Thu Dec  6 17:57:34 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu, 06 Dec 2001 09:57:34 -0800
Subject: [Tutor] Blank line added after reading a line from a file
References: <E16C18z-00032f-00@mail.python.org>
Message-ID: <3C0FB18E.ADD2D31D@ccvcorp.com>

> On Thu, 6 Dec 2001 09:52:14 -0000,
> "Kelly, Phelim" <KellyPhe@logica.com> wrote:
>
>
> Jeff, Andrei,
>             I got that problem fixed using one of the lines you gave me. The
> line of text was read in with an extra blank line, it wasn't just the print
> command that added it on. I got rid of the blank line using line 4 below:

Well, really, the line was not read in with an *extra* blank line.  The line was read in, including the newline character (and trust me, that newline character *does* exist in the file on disk).  It's just that, when you read a line of the file into a string, you expect that the end of the string is the end of the line, so the (somewhat redundant) existance of a character there identifying this as the end of a
line, can be a bit confusing.  If you were to look directly at the file on disk, it would look something like this (using the convention of '\n' to indicate newline characters):

----------------------textfile.txt-------------
This is a line of text.\nThis is a second line.\nThis textfile contains\na number of different lines,\nin fact.\n
------------------end of textfile.txt----------

Now, when you normally view the file, the newlines are translated, i.e.,

$ cat textfile.txt
This is a line of text.
This is a second line.
This textfile contains
a number of different lines,
in fact.

But when you read the file into python using readline() or readlines(), it does *not* translate the newline characters, it just breaks the file into chunks at their locations, so that you get:

>>> fp = open('textfile.txt')
>>> text = fp.readlines()
>>> fp.close()
>>> for line in text:
...  repr(line)
...
"'This is a line of text.\\012'"
"'This is a second line.\\012'"
"'This textfile contains\\012'"
"'a number of different lines,\\012'"
"'in fact.\\012'"
>>>

(The extra quotes are added by repr(). )  This shows that the newline characters are still there, just as they were in the original file, it's just that the file has now been chunked up.  We can verify that it's the same as the original file, too:

>>> fp = open('textfile.txt')
>>> text = fp.read()
>>> fp.close()
>>> repr(text)
"'This is a line of text.\\012This is a second line.\\012This textfile contains\\012a number of different lines,\\012in fact.\\012'"
>>>

You can see that the first example has all of the same characters as the second, it's just been partitioned into several pieces.  The problem comes when you try to do anything with those individual lines.  Most functions (or statements such as print) expect that what they're given, is a complete line, and will act appropriately.  They get thrown, however, by the existence of that trailing newline character that
readlines() left in for the sake of completeness.

And as a further note, I'm pretty sure that readline[s]() leaves the newline in place, in order to maintain symmetry with the writelines() function, which writes a list of strings to a file, but does not add newlines on its own (it's up to you to add newlines anywhere you want them).

Of course, all of this is just background, since you've found a way to solve your problem, but it's good to know the background so you know *why* your problem is fixed (and why it was a problem to begin with)...  :)

Jeff Shannon
Technician/Programmer
Credit International




From ak@silmarill.org  Thu Dec  6 17:54:42 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Thu, 06 Dec 2001 12:54:42 -0500
Subject: [Tutor] passing in string from command line
In-Reply-To: <C9054F12A3EED311B0160090274D912105C1A84D@shannon.ie.logica.com>
References: <C9054F12A3EED311B0160090274D912105C1A84D@shannon.ie.logica.com>
Message-ID: <20011206125442.A9419@sill.silmarill.org>

On Thu, Dec 06, 2001 at 05:46:07PM +0000, Kelly, Phelim wrote:
> Another Basic enough question I hope you can help with!
> 
> I'm reading in values from the command line that I want to assign to
> variables within the code, i.e
> 
> >>python file.py number word
> 
> I know how to pass the typed number into a variable, i.e,
> 
> --------------------
> try:
>    variable1 =int(sys.argv[1])
> except:
>    print "Sorry, but you did not enter a number"
>    sys.exit()
> -------------------
> 
> What's the equivalent to "variable1 =int(sys.argv[1])" for assigning the
> entered word to a variable, something like this??????........
> "variable2 =string(sys.argv[2])"
> 
> Thanks in advance.
> 
> Phelim.

All the stuff in sys.argv is already in the form of strings, so you
don't need to do anything.. just var = sys.argv[2]. By the way, if you
ever have a value that's an int and you want to convert it to string,
the function is str: var = str(int_var)

> 
> 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.
> 
> _______________________________________________
> 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 jrm@videotron.ca  Thu Dec  6 11:46:16 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Thu, 6 Dec 2001 13:46:16 +0200
Subject: [Tutor] I want the world to know !
Message-ID: <000501c17e4b$9cf47d00$0100c0a8@videotron.ca>

    I just finished "Learning to program" at
http://www.freenetpages.co.uk/hp/alan.gauld/ by the very same A. Gauld who
hangs out on this list. But you probably know him better than I. Of all the
introductory material that I am using, it's the first that I was able to
assimilate without feeling overwhelmed before the end. Now I can go back to
those that I put aside and actually understand them somewhat better.
    Disclaimer : I don't know the guy and I'm not sucking up just because
he's holding my cat hostage (j/k).

    Jean M.




From SWidney@ci.las-vegas.nv.us  Thu Dec  6 21:00:30 2001
From: SWidney@ci.las-vegas.nv.us (Scott Widney)
Date: Thu, 6 Dec 2001 13:00:30 -0800
Subject: [Tutor] defining functions.. why return?
Message-ID: <D4EB5574F4A7D2119C9E00A0C9EA408D059F586B@SOVEREIGN>


> -----Original Message-----
> From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu]
> Sent: Thursday, December 06, 2001 12:52 AM
> To: Frank Holmes
> Cc: tutor@python.org
> Subject: Re: [Tutor] defining functions.. why return?
> 
> 
> On Wed, 5 Dec 2001, Frank Holmes wrote:
> 
> >    I am working my way thru "SAMS teach yourself Python in 
> 24 hrs by Van 
> > Laningham (funny, it seems to be taking me a lot more than 
> 24 hrs...) and I 
> 
> Hmmm... You might actually find this page interesting: it's 
> Peter Norvig's
> essay about the books that claim to "Teach Yourself Foo in 24 Hours".
> 
>     http://norvig.com/21-days.html
> 
> Personally, I think it might take a bit longer than 24 hours to really
> feel comfortable with Python.  But don't feel rushed about the whole
> thing; there's no pop quizzes here or anything... *grin*

What I've noticed is that these books generally contain 24 chapters, each of
which can be consumed in an hour. It's the digestion time between chapters
that isn't specified....

=^)
Scott


From urnerk@qwest.net  Thu Dec  6 21:03:23 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Thu, 06 Dec 2001 13:03:23 -0800
Subject: [Tutor] sys.path..... - PATH, one more time...
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C180@mbtlipnt02.btlabs
 .bt.co.uk>
Message-ID: <4.2.0.58.20011206125955.00c4a100@pop3.norton.antivirus>

Note that by convention, [pythondirectory]/lib/site-packages
is now considered a default place to put your stuff, or
to install packages as subdirectories.  This is for
Windows as well as 'nix (Mac OS is a 'nix in the next era).

There's also the .pth extension in Windows.  You can list
directories there which you want 'import xxx' to search/find.

Kirby



From dsh8290@rit.edu  Thu Dec  6 22:31:53 2001
From: dsh8290@rit.edu (dman)
Date: Thu, 6 Dec 2001 17:31:53 -0500
Subject: [Tutor] Follow up to 'class data'
In-Reply-To: <Pine.LNX.4.33.0112060916510.5996-100000@fleet1.paxp.com>; from fleet@teachout.org on Thu, Dec 06, 2001 at 09:25:12AM -0500
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C173@mbtlipnt02.btlabs.bt.co.uk> <Pine.LNX.4.33.0112060916510.5996-100000@fleet1.paxp.com>
Message-ID: <20011206173153.A3760@harmony.cs.rit.edu>

On Thu, Dec 06, 2001 at 09:25:12AM -0500, fleet@teachout.org wrote:
 
| Perhaps I asked the wrong question.  If all I want is to use Python for a
| scripting language and some simple programs, is OOP perhaps overkill?

Given that python is as flexible as it is, it is common for a program
to start out small (I think of it as a "script") that uses functions
and maybe even global variables, and fits nicely in a single file.
Usually this gets the job done right now, but it is not as flexible,
customizable, or reusable as possible.  As you continue to use the
program you come up with new features you want to add and ways you
want to customize it (ie giving a path as an argument rather than
hard-coding it).  As the script expands it turns into an "application"
(there is a fine line between the two, though, and it is largely
relative) and can benefit from OOP.  Python make the conversion from
using a procedural style to OOP rather easy (compared to some other
languages).

My view is : make the program as simple as possible, but no simpler.
Don't use OOP if your program would be trivial without it.  If you
need to expand it later, you can make the transition then.  (but by
all means, go ahead and learn OOP principles so you can apply them
when appropriate)

-D 

-- 

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



From dsh8290@rit.edu  Thu Dec  6 22:38:59 2001
From: dsh8290@rit.edu (dman)
Date: Thu, 6 Dec 2001 17:38:59 -0500
Subject: [Tutor] Follow up to 'class data'
In-Reply-To: <Pine.LNX.4.33.0112052110460.4765-100000@fleet1.paxp.com>; from fleet@teachout.org on Wed, Dec 05, 2001 at 09:48:18PM -0500
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C155@mbtlipnt02.btlabs.bt.co.uk> <Pine.LNX.4.33.0112052110460.4765-100000@fleet1.paxp.com>
Message-ID: <20011206173858.B3760@harmony.cs.rit.edu>

On Wed, Dec 05, 2001 at 09:48:18PM -0500, fleet@teachout.org wrote:
 
| Let's say I write a compiled Basic program called AddressBook.exe that
| produces a pipe-delimited flat file with names and addresses in it.
| Anybody that runs it gets exactly the same address book output; but with
| their own data.  One could run several "instances" of it on the same
| computer - ie, "business addresses", "personal addresses", "club
| addresses", etc.  Where does this differ from a class?

I would say that the difference is "AddressBook.exe" is an entire
program (in binary format).  A class is simply a structural entity to
ease programming, and a single program can (often is if the langauge
supports it) composed of more than one class.

Regardless of whether or not you used classes the program would need
to know how to read from a file and understand that the interesting
data is separated by "|" and newlines, and what the interesting data
is supposed to mean.

Each program must also explicitly write the in-memory data to a file.
Classes don't automagically do that.  

If you think about it, everything in the computer is nothing more than
a series of bits.  Whether the program is written in Python, C++,
Java, COBOL, or BASIC it all ends up mapping onto the same set of
machine instructions.  The only difference is the way you, the
programmer, express those instructions to the computer.  At runtime,
classes don't exist (well, since python is interpreted you could say
they do, but in C++ or Objective C they don't).  At runtime all there
is is a bunch of bits.

| > Occasionally, very occasionally, we write classes that look
| > like functions but its not normal practice. Similarly its
| > not usually a good idea to provide set/get methods for
| > every internal attribute - a common beginners mistake.
| > Only expose those attributes that the outside world needs
| > to see.
| 
| I don't think I understand this either.  Do you mean I shouldn't provide
| attributes for length, width, thickness, color of cover, etc?  Certainly
| one would need to make Name, Address, Phone, etc. "exposed."

Suppose, for example, you wanted to store your address book in a SQL
database instead of a file.  You might have a "primary key" that
consists of a number unique to each entry.  This id should not have
get/set methods because it is an implementation detail of the entry
and it should not be used or modified by clients.  This is where
encapsulation becomes relevant.  You can switch around the persistant
data store (files like you describe above or a SQL database) and
clients don't know nor care about it, it just works.

I hope this make things clearer for you.

-D

-- 

If your life is a hard drive,
Christ can be your backup.



From dsh8290@rit.edu  Thu Dec  6 22:52:16 2001
From: dsh8290@rit.edu (dman)
Date: Thu, 6 Dec 2001 17:52:16 -0500
Subject: [Tutor] __cmp__() method examples?
In-Reply-To: <20011205213547.I27400@hal>; from i812@iname.com on Wed, Dec 05, 2001 at 09:35:47PM -0600
References: <20011205213547.I27400@hal>
Message-ID: <20011206175215.C3760@harmony.cs.rit.edu>

On Wed, Dec 05, 2001 at 09:35:47PM -0600, Rob McGee wrote:
| {code}
| import random
| 
| class Project:
|   def __init__(self, name):
|     self.name = name
|     self.value = random.randrange(1, 100)
|   def __str__(self):
|     return self.name
|   def __cmp__(self, other):
|     if self.name < other.name:  # compare name value (should be unique)
|       return -1
|     elif self.name > other.name:
|       return 1
|     else: return 0              # should mean it's the same instance
| 
| # now generate class instances -- this is always done automatically
| from string import uppercase
| for letter in uppercase:
|   execStr = letter + ' = Project("' + letter + '")'
|   # example -- 'A = Project("A")', 'Z = Project("Z")
|   exec(execStr)
| 
| {/code}
| 
| (Sorry about the exec's, but I really don't know another way to do what
| I want. I want these instances in the global namespace, and I need to
| know exactly what each one is named. At least I think I do. Suggestions
| about other ways to approach this would be welcomed, too. :) Like with
| no exec's, or with the instances in something other than globals(), how
| would I be able to retrieve and alter their properties?)

Just put the objects in a container (ie list or dictionary) as others
have mentioned.  You do know exactly what it is named because it has a
'name' attribute.  When you think you need to exec to get extra local
variables, instead pretend exec doesn't exist (say, you're writing C
code) and use a container instead.

For example :

import string 
projects = []
for letter in string.uppercase:
   projects.append( Project( letter ) )


Now to show that you do know exactly what they are named :

for project in projects :
    print "this project is named " + project.name , project


This could be done with a dictionary if, for example, the class
already exists without a name, but you want to name it.
 

import string 
projects = {}
for letter in string.uppercase:
   projects[ letter ] = Project()

You still know exactly what each one is named :

for projectname in projects.keys() :
    print "this project is named " + projectname , projects[ projectname ]



| I'm getting errors which indicate that the class instances are being
| compared with other objects 

This is normal.  Objects can be compared to any other object at any
time.  The client code may know nothing about what your object is, but
it wants to know if it is equal to another one.

| what I'm hoping for is just a little guidance on how to properly
| implement a __cmp__() method.

IIRC __cmp__ isn't allowed to raise exceptions ...

| What I think I'll try -- the idea came to me while writing this :) -- is
| to put code in Project.__cmp__() like the ifInstance() above. If "other"
| isn't an instance of self.__class__, don't try to get other.name.

that's spelled  isinstance( instance_object , class_object ), and I
recommend against this.  What if someone else wants to use your
library, and they create a specialized project class that extends your
Project class via composition instead of inheritance?  In that case
the objects could never be equal.

Since you can't use the rich comparisions, here's what I would do :

def __cmp__( self , other ) :
    try :
        # the comparision is defined as the comparison of the strings
        return cmp( self.name , other.name )
    except :
        # must be a different kind of object,
        # make it less than us
        return -1


This method will succeed for all objects and give a total ordering,
though obviously the -1 in the except clause is arbitrary (just don't
make them equal ;-)).

| Oh, I should also mention that I got into an infinite loop with another
| class.__cmp__() method. That class was more complicated, and I had
| several if/elif loops to compare other attributes. The fourth and final
| such loop simply compared "self" and "other". I believe that was where
| the loop occurred, and it was in sorting a list of instances of that
| class (I don't think there were any non-instance members of the list.)
| 
| By removing the self/other raw comparison I eliminated the infinite
| loop. But that experience gives me the idea that I'm missing something
| about how to do a Class.__cmp__().

Well, the __cmp__  method is supposed to decide whether or not the two
things are equal (and less than or greater than).  If you try and
compare the two objects directly using an operator, well, that
operator is defined by the __cmp__ method which tries to compare the
objects which is defined by __cmp__ (I'll stop here, but I think you
see what was happening).

-D

-- 

"Don't use C;  In my opinion,  C is a library programming language
 not an app programming language."  - Owen Taylor (GTK+ developer)



From jrm@videotron.ca  Thu Dec  6 19:46:39 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Thu, 6 Dec 2001 21:46:39 +0200
Subject: [Tutor] simplifications : are they good ?
Message-ID: <000501c17e8e$b9168080$0100c0a8@videotron.ca>

    Of course I'm a beginner, but when I see something like :

Label(fen1, text = 'Premier champ :').grid(sticky =E)
Label(fen1, text = 'Second :').grid(sticky =E)
Label(fen1, text = 'Troisième :').grid(sticky =E)
entr1 = Entry(fen1).grid(row =0, column =1)
entr2 = Entry(fen1).grid(row =1, column =1)
entr3 = Entry(fen1).grid(row =2, column =1)

    instead of the full form I'm sceptic. Is the omission of a viariable
affectation going to speedup the program ? Same question for grouping
creation and method on the same line ? Same for the omission of certain row
and column numbers ?

    I must admit that I'm by nature irritated by all forms of jargon or
anything that artificially hinders simplicity and clarity ; on the other
hand, if the gain in speed is real then it could be justified.

JM




From dyoo@hkn.eecs.berkeley.edu  Fri Dec  7 03:03:20 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 6 Dec 2001 19:03:20 -0800 (PST)
Subject: [Tutor] simplifications : are they good ?
In-Reply-To: <000501c17e8e$b9168080$0100c0a8@videotron.ca>
Message-ID: <Pine.LNX.4.21.0112061851150.19315-100000@hkn.eecs.berkeley.edu>

On Thu, 6 Dec 2001, Jean Montambeault wrote:

>     Of course I'm a beginner, but when I see something like :
>=20
> Label(fen1, text =3D 'Premier champ :').grid(sticky =3DE)
> Label(fen1, text =3D 'Second :').grid(sticky =3DE)
> Label(fen1, text =3D 'Troisi=E8me :').grid(sticky =3DE)
> entr1 =3D Entry(fen1).grid(row =3D0, column =3D1)
> entr2 =3D Entry(fen1).grid(row =3D1, column =3D1)
> entr3 =3D Entry(fen1).grid(row =3D2, column =3D1)
>=20
>     instead of the full form I'm sceptic. Is the omission of a viariable
> affectation going to speedup the program ? Same question for grouping

Hi Jean,

Good question!  I don't believe it's a matter of speedup, but instead of
convenience.  Sometimes it's just easier to say:

###
>>> 3 * 4
12
###

instead of:

###
>>> x =3D 3
>>> y =3D 4
>>> x * y
12
###



In the same vein, the author of:

> Label(fen1, text =3D 'Premier champ :').grid(sticky =3DE)
> Label(fen1, text =3D 'Second :').grid(sticky =3DE)
> Label(fen1, text =3D 'Troisi=E8me :').grid(sticky =3DE)

probably felt that giving a name to each Label was unnecessarily
convoluted, when the author wasn't planning to do anything more with the
Label.  This is often the case of Labels, because the user doesn't really
interact with labels after they're placed in a GUI.

The author could have written:

##
l1 =3D Label(fen1, text=3D'Premier champ :')
l2 =3D Label(fen1, text=3D'Second :')
l3 =3D Label(fen1, text =3D 'Troisi=E8me :')
l1.grid(sticky =3D E)
l2.grid(sticky =3D E)
l3.grid(sticky =3D E)
###

but as far as Python is concerned, there's negligible difference in the
efficiency of this process.


Hope this helps!



From dsh8290@rit.edu  Fri Dec  7 03:15:28 2001
From: dsh8290@rit.edu (dman)
Date: Thu, 6 Dec 2001 22:15:28 -0500
Subject: [Tutor] simplifications : are they good ?
In-Reply-To: <000501c17e8e$b9168080$0100c0a8@videotron.ca>; from jrm@videotron.ca on Thu, Dec 06, 2001 at 09:46:39PM +0200
References: <000501c17e8e$b9168080$0100c0a8@videotron.ca>
Message-ID: <20011206221528.B4259@harmony.cs.rit.edu>

On Thu, Dec 06, 2001 at 09:46:39PM +0200, Jean Montambeault wrote:
 
|     I must admit that I'm by nature irritated by all forms of jargon or
| anything that artificially hinders simplicity and clarity ; on the other
| hand, if the gain in speed is real then it could be justified.

Speed is never enough justification for loss of clarity, unless you
have first tested the program and found it to be too slow _and_
profiled it to identify the hotspots.  Simplicity and clarity are far
better, especially when it comes time to debug and maintain the code.
If you can't understand what it says right now, what are the chances
you can change it and still maintain correctness?

-D

-- 

(E)scape (M)eta (A)lt (C)ontrol (S)hift



From jrm@videotron.ca  Thu Dec  6 20:40:16 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Thu, 6 Dec 2001 22:40:16 +0200
Subject: [Tutor] simplifications : are they good ?
References: <Pine.LNX.4.21.0112061851150.19315-100000@hkn.eecs.berkeley.edu>
Message-ID: <008e01c17e96$364b8e40$0100c0a8@videotron.ca>

----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>

In the same vein, the author of:

> Label(fen1, text = 'Premier champ :').grid(sticky =E)
> Label(fen1, text = 'Second :').grid(sticky =E)
> Label(fen1, text = 'Troisième :').grid(sticky =E)

probably felt that giving a name to each Label was unnecessarily
convoluted, when the author wasn't planning to do anything more with the
Label.  This is often the case of Labels, because the user doesn't really
interact with labels after they're placed in a GUI.

The author could have written:

##
l1 = Label(fen1, text='Premier champ :')
l2 = Label(fen1, text='Second :')
l3 = Label(fen1, text = 'Troisième :')
l1.grid(sticky = E)
l2.grid(sticky = E)
l3.grid(sticky = E)
###

but as far as Python is concerned, there's negligible difference in the
efficiency of this process.


Hope this helps!

Yes it does. That's exactly what I wanted : reading your take on that.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



From jrm@videotron.ca  Thu Dec  6 21:51:58 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Thu, 6 Dec 2001 23:51:58 +0200
Subject: [Tutor] Now has come the time to choose an editor
Message-ID: <000a01c17ea0$3ad6b020$0100c0a8@videotron.ca>

    Emacs would be my first choice. Is there anything else that would run on
any platform ?

Jean M.



From kalle@gnupung.net  Fri Dec  7 06:00:18 2001
From: kalle@gnupung.net (Kalle Svensson)
Date: Fri, 7 Dec 2001 07:00:18 +0100
Subject: [Tutor] Now has come the time to choose an editor
In-Reply-To: <000a01c17ea0$3ad6b020$0100c0a8@videotron.ca>
References: <000a01c17ea0$3ad6b020$0100c0a8@videotron.ca>
Message-ID: <20011207070017.A26967@proton.lysator.liu.se>

[Jean Montambeault]
>     Emacs would be my first choice. Is there anything else that would run on
> any platform ?

Well, emacs runs on Unix and Windows.  If that's good enough, I'd suggest you
go for it.  Another alternative might be IDLE, which should run on most
platforms.  It is distributed with Python and is written in Python.  It's okay
for editing and debugging Python, but I prefer emacs.
Other editors that have been mentioned by people in similar threads include
 - vi(m) (at least Unix and Windows)
 - Ultraedit (only Windows?)
 - Pythonwin (only Windows)
 - Jed (Unix, maybe Windows?)
And probably more.  But remember (from
http://www.dina.kvl.dk/~abraham/religion/size.html):
"""
> Emacs is a pig.

Small minds -- small executables.
"""

Peace,
  Kalle
-- 
[  Laziness, impatience, hubris:  Pick two!  ]
[   International: http://www.gnupung.net/   ]
[ Svenska: http://www.lysator.liu.se/~kalle/ ]


From kalle@gnupung.net  Fri Dec  7 07:55:07 2001
From: kalle@gnupung.net (Kalle Svensson)
Date: Fri, 7 Dec 2001 08:55:07 +0100
Subject: [Tutor] [Kirk Bailey: idle is idle]
Message-ID: <20011207085507.B827@proton.lysator.liu.se>

I just got this message, and I haven't got an IDLE handy.  Anyone?

----- Forwarded message from Kirk Bailey <deliberatus@my995internet.com> -----

From: Kirk Bailey <deliberatus@my995internet.com>
To: Kalle Svensson <kalle@gnupung.net>
Subject: idle is idle
Date: Fri, 07 Dec 2001 02:12:39 -0500
X-Mailer: Mozilla 4.74 [en] (Win98; U)
Organization: Silas Dent Memorial Cabal of ERIS Esoteric and hot dog boiling society so there.
X-Accept-Language: en

OK, me goofed.

Went to enlarge the font. Read the help.txt file for idle, THOUGHT I was
doing the right thing. Set the font size to '12' and the font face to
'Lucidia Console'. Now it won't fire up at all. Grr...

Wish I saved the original file, I could have restored it. OK, gimee a
clue, how do I fix it gang?

In the help file, there is only one line that referrs to font, it says
how to change that one line, and I did it wrong. Please send me a copy
of that line, how to restore it, and how to change it so I can use a
larger font- size 12 would work on this screen resolution and this pair
of feeble eyeballs.

Grrr....

Kalle Svensson wrote:
[snip]

----- End forwarded message -----

Peace,
  Kalle
-- 
[  Laziness, impatience, hubris:  Pick two!  ]
[   International: http://www.gnupung.net/   ]
[ Svenska: http://www.lysator.liu.se/~kalle/ ]


From ak@silmarill.org  Fri Dec  7 09:04:34 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 07 Dec 2001 04:04:34 -0500
Subject: [Tutor] Now has come the time to choose an editor
In-Reply-To: <20011207070017.A26967@proton.lysator.liu.se>
References: <000a01c17ea0$3ad6b020$0100c0a8@videotron.ca>
 <20011207070017.A26967@proton.lysator.liu.se>
Message-ID: <20011207040434.A11562@sill.silmarill.org>

On Fri, Dec 07, 2001 at 07:00:18AM +0100, Kalle Svensson wrote:
> [Jean Montambeault]
> >     Emacs would be my first choice. Is there anything else that would run on
> > any platform ?
> 
> Well, emacs runs on Unix and Windows.  If that's good enough, I'd suggest you
> go for it.  Another alternative might be IDLE, which should run on most
> platforms.  It is distributed with Python and is written in Python.  It's okay
> for editing and debugging Python, but I prefer emacs.
> Other editors that have been mentioned by people in similar threads include
>  - vi(m) (at least Unix and Windows)
>  - Ultraedit (only Windows?)
>  - Pythonwin (only Windows)
>  - Jed (Unix, maybe Windows?)
> And probably more.  But remember (from
> http://www.dina.kvl.dk/~abraham/religion/size.html):
> """
> > Emacs is a pig.
> 
> Small minds -- small executables.
> """

Would that mean Gates is Mozart and Da Vinci rolled into one? :P

> 
> Peace,
>   Kalle
> -- 
> [  Laziness, impatience, hubris:  Pick two!  ]
> [   International: http://www.gnupung.net/   ]
> [ Svenska: http://www.lysator.liu.se/~kalle/ ]
> 
> _______________________________________________
> 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 alan.gauld@bt.com  Fri Dec  7 09:35:50 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 7 Dec 2001 09:35:50 -0000
Subject: [Tutor] sys.path..... - PATH, one more time...
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C182@mbtlipnt02.btlabs.bt.co.uk>

> There's also the .pth extension in Windows.  You can list
> directories there which you want 'import xxx' to search/find.

What's this then? Its new to me. 
Can you expand Kirby?

Alan G.


From kalle@gnupung.net  Fri Dec  7 09:41:42 2001
From: kalle@gnupung.net (Kalle Svensson)
Date: Fri, 7 Dec 2001 10:41:42 +0100
Subject: [Tutor] Now has come the time to choose an editor
In-Reply-To: <20011207040434.A11562@sill.silmarill.org>
References: <000a01c17ea0$3ad6b020$0100c0a8@videotron.ca> <20011207070017.A26967@proton.lysator.liu.se> <20011207040434.A11562@sill.silmarill.org>
Message-ID: <20011207104142.C827@proton.lysator.liu.se>

[Andrei Kulakov]
> On Fri, Dec 07, 2001 at 07:00:18AM +0100, Kalle Svensson wrote:
[snip]
> > And probably more.  But remember (from
> > http://www.dina.kvl.dk/~abraham/religion/size.html):
> > """
> > > Emacs is a pig.
> > 
> > Small minds -- small executables.
> > """
> 
> Would that mean Gates is Mozart and Da Vinci rolled into one? :P

Ouch. :)

Peace,
  Kalle
-- 
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]


From lonetwin@yahoo.com  Fri Dec  7 10:24:55 2001
From: lonetwin@yahoo.com (lonetwin)
Date: Fri, 7 Dec 2001 15:54:55 +0530
Subject: [Tutor] passing in string from command line
In-Reply-To: <C9054F12A3EED311B0160090274D912105C1A84D@shannon.ie.logica.com>
References: <C9054F12A3EED311B0160090274D912105C1A84D@shannon.ie.logica.com>
Message-ID: <01120715545506.20374@mercury.worli>

Hey There
On Thursday 06 December 2001 23:16, you wrote:
> Another Basic enough question I hope you can help with!
>
> I'm reading in values from the command line that I want to assign to
> variables within the code, i.e
>
> >>python file.py number word
>
> I know how to pass the typed number into a variable, i.e,
>
> --------------------
> try:
>    variable1 =int(sys.argv[1])
> except:
>    print "Sorry, but you did not enter a number"
>    sys.exit()
> -------------------
>
> What's the equivalent to "variable1 =int(sys.argv[1])" for assigning the
> entered word to a variable, something like this??????........
> "variable2 =string(sys.argv[2])"

 No, it's something like this :
    variable2 = sys.argv[2]
          The sys.argv list is a list of *strings* that are passed as 
command-line arguments.

Peace
Steve
-- 
----------------------------------------------
Every oak tree started out as a 
couple of nuts who stood their ground.
                                    Anonymous
----------------------------------------------



From lha2@columbia.edu  Fri Dec  7 11:28:24 2001
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Fri, 07 Dec 2001 06:28:24 -0500
Subject: [Tutor] [Kirk Bailey: idle is idle]
References: <20011207085507.B827@proton.lysator.liu.se>
Message-ID: <3C10A7D8.5612A96B@mail.verizon.net>

There should be a line in EditorWindow.py that reads

        text['font'] = edconf.get('font-name'), edconf.get('font-size')

and the entire contents of config-win.txt are

***begin config-win.txt***
[EditorWindow]
font-name: courier new
font-size: 10
***end config-win.txt***

I like to use a monospaced font, myself, so that tab-stops don't look
funny to me.

Kalle Svensson wrote:
> 
> I just got this message, and I haven't got an IDLE handy.  Anyone?
> 
> ----- Forwarded message from Kirk Bailey <deliberatus@my995internet.com> -----
> 
> From: Kirk Bailey <deliberatus@my995internet.com>
> To: Kalle Svensson <kalle@gnupung.net>
> Subject: idle is idle
> Date: Fri, 07 Dec 2001 02:12:39 -0500
> X-Mailer: Mozilla 4.74 [en] (Win98; U)
> Organization: Silas Dent Memorial Cabal of ERIS Esoteric and hot dog boiling society so there.
> X-Accept-Language: en
> 
> OK, me goofed.
> 
> Went to enlarge the font. Read the help.txt file for idle, THOUGHT I was
> doing the right thing. Set the font size to '12' and the font face to
> 'Lucidia Console'. Now it won't fire up at all. Grr...
> 
> Wish I saved the original file, I could have restored it. OK, gimee a
> clue, how do I fix it gang?
> 
> In the help file, there is only one line that referrs to font, it says
> how to change that one line, and I did it wrong. Please send me a copy
> of that line, how to restore it, and how to change it so I can use a
> larger font- size 12 would work on this screen resolution and this pair
> of feeble eyeballs.
> 
> Grrr....
> 
> Kalle Svensson wrote:
> [snip]
> 
> ----- End forwarded message -----
> 
> Peace,
>   Kalle
> --
> [  Laziness, impatience, hubris:  Pick two!  ]
> [   International: http://www.gnupung.net/   ]
> [ Svenska: http://www.lysator.liu.se/~kalle/ ]
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From python_sun"<python_sun@indiatimes.com  Fri Dec  7 12:32:15 2001
From: python_sun"<python_sun@indiatimes.com (python_sun)
Date: Fri, 07 Dec 2001 18:02:15 +0530
Subject: [Tutor] pointers in python
Message-ID: <200112071230.SAA08016@WS0005.indiatimes.com>

hi all,
 i am newbie in python i am aware with C. How python handle Pointers. if U know please help.

python_sun@indiatimes.com 
Get Your Private, Free E-mail from Indiatimes at http://email.indiatimes.com

 Buy Music, Video, CD-ROM, Audio-Books and Music Accessories from http://www.planetm.co.in



From alan.gauld@bt.com  Fri Dec  7 14:56:18 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 7 Dec 2001 14:56:18 -0000
Subject: [Tutor] I want the world to know !
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C184@mbtlipnt02.btlabs.bt.co.uk>

>     Disclaimer : I don't know the guy and I'm not sucking up 
> just because he's holding my cat hostage (j/k).

I told you not to mention the cat, now he gets it! :-)

But thanks anyway.

Alan G


From pythontutor@venix.com  Fri Dec  7 15:12:12 2001
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri, 07 Dec 2001 10:12:12 -0500
Subject: [Tutor] pointers in python
References: <200112071230.SAA08016@WS0005.indiatimes.com>
Message-ID: <3C10DC4C.1040506@venix.com>

Python variables are pointers to the memory locations that hold the Python objects.

HOWEVER, there is no pointer arithmatic and you don't actually deal with those addresses.
The id function returns a value that is based upon the memory address.  This lets you
see if two objects with the same content are actually the same object.

python_sun wrote:

> hi all,
>  i am newbie in python i am aware with C. How python handle Pointers. if U know please help.
> 
> python_sun@indiatimes.com 
> Get Your Private, Free E-mail from Indiatimes at http://email.indiatimes.com
> 
>  Buy Music, Video, CD-ROM, Audio-Books and Music Accessories from http://www.planetm.co.in
> 
> 
> _______________________________________________
> 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 arcege@speakeasy.net  Fri Dec  7 16:45:29 2001
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Fri, 7 Dec 2001 11:45:29 -0500
Subject: [Tutor] __cmp__() method examples?
In-Reply-To: <20011205213547.I27400@hal>; from i812@iname.com on Wed, Dec 05, 2001 at 09:35:47PM -0600
References: <20011205213547.I27400@hal>
Message-ID: <20011207114529.E884@speakeasy.net>

On Wed, Dec 05, 2001 at 09:35:47PM -0600, Rob McGee wrote:

> # now generate class instances -- this is always done automatically
> from string import uppercase
> for letter in uppercase:
>   execStr = letter + ' = Project("' + letter + '")'
>   # example -- 'A = Project("A")', 'Z = Project("Z")
>   exec(execStr)
> 
> {/code}
> 
> (Sorry about the exec's, but I really don't know another way to do what
> I want. I want these instances in the global namespace, and I need to
> know exactly what each one is named. At least I think I do. Suggestions
> about other ways to approach this would be welcomed, too. :) Like with
> no exec's, or with the instances in something other than globals(), how
> would I be able to retrieve and alter their properties?)

If you _really_ need have these as globals to that module, then you
can always import the module to a variable, then set the attributes
of that module:

# the name of the current module is in '__name__'
thismod = __import__(__name__)
from string import uppercase
for letter in uppercase:
  # same as module.A = Project("A")
  setattr(thismod, letter, Project(letter))

This is probably a better method than using exec.  But you might
also want to think about a different structure than global variables.

  -Arcege



From urnerk@qwest.net  Fri Dec  7 17:19:55 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 07 Dec 2001 09:19:55 -0800
Subject: [Tutor] __cmp__() method examples?
In-Reply-To: <20011207114529.E884@speakeasy.net>
References: <20011205213547.I27400@hal>
 <20011205213547.I27400@hal>
Message-ID: <4.2.0.58.20011207091911.015cdbe0@pop3.norton.antivirus>

>
>This is probably a better method than using exec.  But you might
>also want to think about a different structure than global variables.
>
>   -Arcege

Thanks for showing this.  I dinked around for awhile trying to
figure out how to do just that and failed.  Your code is most
instructive.  Great tutoring.

Kirby



From alan.gauld@bt.com  Fri Dec  7 17:26:24 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 7 Dec 2001 17:26:24 -0000
Subject: [Tutor] Tkinter stuff
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C186@mbtlipnt02.btlabs.bt.co.uk>

I missed this original post and the digest screwed up so 
I can't reply to it...

> JM Wrote:
>    Of course I'm a beginner, but when I see something like :
>
> Label(fen1, text = 'Premier champ :').grid(sticky =E)
> Label(fen1, text = 'Second :').grid(sticky =E)
> Label(fen1, text = 'Troisi=E8me :').grid(sticky =E)

This is OK and pretty standard style Tkinter since you rarely 
need to change Labels once created but...

> entr1 =3D Entry(fen1).grid(row =0, column =1)
> entr2 =3D Entry(fen1).grid(row =1, column =1)
> entr3 =3D Entry(fen1).grid(row =2, column =1)

This won't work because it assigns the value returned by 
grid() to the variables. grid() returns None!

The only way to get a handle on the widget, which I assume 
the original auther was trying to do, is to create the widget 
then grid or pack it. Like so:

entr3 = Entry(fen1)
entr3.grid(row =2, col = 1)

More long winded but has the advantage of actually working.

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


From clams17@yahoo.com  Fri Dec  7 19:08:37 2001
From: clams17@yahoo.com (Spiffy)
Date: Fri, 7 Dec 2001 11:08:37 -0800 (PST)
Subject: [Tutor] string conversion and formatters
Message-ID: <20011207190837.29701.qmail@web9503.mail.yahoo.com>

Hello! I am just beginning to learn programming and
Python. I am teaching myself using online tutorials
and documentation. Concerning output formatters...as
in "%d", "%s", etc. I know I have seen a listing of
all the types somewhere in the documentation, but for
the life of me I cannot relocate it. Where can I find
it?
 Now for the real question. Here is my first real
program. It is supposed to be a decimal/hex
convertor...
#Decimal/Hex Convertor

def print_options():
    print "Options:"
    print " 'a' decimal to hex"
    print " 'b' hex to decimal"
    print " 'c' print options"
    print " 'd' quit"

choice = "c"
while choice != "d":
    if choice == "a":
        dec = input("Decimal: ")
        print "Hex: %X" % (dec)
    elif choice == "b":
        hex = raw_input("Hex: ")
        print "Decimal: %d" % (hex)
    elif choice != "d":
        print_options()
    choice = raw_input("option: ")
    
If you run this program, it works fine until you try
to convert hex to decimal. Why does this not work? I
have tried using "string.atoi" and some other things,
but no luck. I am stumped. Please, give me some
explanations or hints to point me in the right
direction...I would very much appreciate it!

By the way, I'm using Python2.2 on Windows 98.
Thanks,

   Spiffy






__________________________________________________
Do You Yahoo!?
Send your FREE holiday greetings online!
http://greetings.yahoo.com


From jrm@videotron.ca  Fri Dec  7 12:42:13 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Fri, 7 Dec 2001 14:42:13 +0200
Subject: [Tutor] string conversion and formatters
References: <20011207190837.29701.qmail@web9503.mail.yahoo.com>
Message-ID: <000501c17f1c$98bfc100$0100c0a8@videotron.ca>

----- Original Message -----
From: "Spiffy" <clams17@yahoo.com>

> Hello! I am just beginning to learn programming and
> Python. I am teaching myself using online tutorials
> and documentation. Concerning output formatters...as
> in "%d", "%s", etc. I know I have seen a listing of
> all the types somewhere in the documentation, but for
> the life of me I cannot relocate it. Where can I find
> it?

    If you really want the lowdown on the subject go to Guido's tutorial
(found under help/python documentation in IDLE) at section 7. When you
finish that I doubt that you'll have any ? on the subject anymore.

Jean M.




From clams17@yahoo.com  Fri Dec  7 18:54:54 2001
From: clams17@yahoo.com (Spiffy)
Date: Fri, 7 Dec 2001 10:54:54 -0800 (PST)
Subject: [Tutor] string conversion and formatters
Message-ID: <20011207185454.54261.qmail@web9507.mail.yahoo.com>

Hello! I am just beginning to learn programming and
Python. I am teaching myself using online tutorials
and documentation. Concerning output formatters...as
in "%d", "%s", etc. I know I have seen a listing of
all the types somewhere in the documentation, but for
the life of me I cannot relocate it. Where can I find
it?
 Now for the real question. Here is my first real
program. It is supposed to be a decimal/hex
convertor...
#Decimal/Hex Convertor

def print_options():
    print "Options:"
    print " 'a' decimal to hex"
    print " 'b' hex to decimal"
    print " 'c' print options"
    print " 'd' quit"

choice = "c"
while choice != "d":
    if choice == "a":
        dec = input("Decimal: ")
        print "Hex: %X" % (dec)
    elif choice == "b":
        hex = raw_input("Hex: ")
        print "Decimal: %d" % (hex)
    elif choice != "d":
        print_options()
    choice = raw_input("option: ")
    
If you run this program, it works fine until you try
to convert hex to decimal. Why does this not work? I
have tried using "string.atoi" and some other things,
but no luck. I am stumped. Please, give me some
explanations or hints to point me in the right
direction...I would very much appreciate it!

Thanks,
  Spiffy





__________________________________________________
Do You Yahoo!?
Send your FREE holiday greetings online!
http://greetings.yahoo.com


From pythontutor@venix.com  Fri Dec  7 20:19:48 2001
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri, 07 Dec 2001 15:19:48 -0500
Subject: [Tutor] string conversion and formatters
References: <20011207190837.29701.qmail@web9503.mail.yahoo.com>
Message-ID: <3C112464.4000202@venix.com>

I made this change:
     elif choice == "b":
         hex_string = raw_input("Hex: ")
         hex = int(hex_string, 16)
         print "Decimal: %d" % (hex)

The raw_input is a string.  The %d print format expects an integer.
Fortunately, the int function allows you to specify the base for your string
when converting to integer.  You will get an error if you specify a base
larger than 36.

Spiffy wrote:

> Hello! I am just beginning to learn programming and
> Python. I am teaching myself using online tutorials
> and documentation. Concerning output formatters...as
> in "%d", "%s", etc. I know I have seen a listing of
> all the types somewhere in the documentation, but for
> the life of me I cannot relocate it. Where can I find
> it?
>  Now for the real question. Here is my first real
> program. It is supposed to be a decimal/hex
> convertor...
> #Decimal/Hex Convertor
> 
> def print_options():
>     print "Options:"
>     print " 'a' decimal to hex"
>     print " 'b' hex to decimal"
>     print " 'c' print options"
>     print " 'd' quit"
> 
> choice = "c"
> while choice != "d":
>     if choice == "a":
>         dec = input("Decimal: ")
>         print "Hex: %X" % (dec)
>     elif choice == "b":
>         hex = raw_input("Hex: ")
>         print "Decimal: %d" % (hex)
>     elif choice != "d":
>         print_options()
>     choice = raw_input("option: ")
>     
> If you run this program, it works fine until you try
> to convert hex to decimal. Why does this not work? I
> have tried using "string.atoi" and some other things,
> but no luck. I am stumped. Please, give me some
> explanations or hints to point me in the right
> direction...I would very much appreciate it!
> 
> By the way, I'm using Python2.2 on Windows 98.
> Thanks,
> 
>    Spiffy
> 
> 
> 
> 
> 
> 
> __________________________________________________
> Do You Yahoo!?
> Send your FREE holiday greetings online!
> http://greetings.yahoo.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 syrinx@simplecom.net  Sat Dec  8 01:14:00 2001
From: syrinx@simplecom.net (Scott)
Date: Fri, 7 Dec 2001 19:14:00 -0600
Subject: [Tutor] Initializing a list as an array
Message-ID: <200112071914453.SM06048@there>

Hello.

Suppose I want to initialize a list that I want to use like an array, setting 
the initial value of each element to zero.  Is there a more efficient way to 
do this than something like:

x = []
for i in range(10):
	x.append(0)

Thanks.




From syrinx@simplecom.net  Sat Dec  8 01:26:11 2001
From: syrinx@simplecom.net (Scott)
Date: Fri, 7 Dec 2001 19:26:11 -0600
Subject: [Tutor] Initializing a list as an array
In-Reply-To: <4.2.0.58.20011207172205.00a8cf10@pop3.norton.antivirus>
References: <4.2.0.58.20011207172205.00a8cf10@pop3.norton.antivirus>
Message-ID: <200112071926968.SM06048@there>

On Friday 07 December 2001 07:24 pm, you wrote:
>
 >Suppose I want to initialize a list that I want to use like an
> >array, setting the initial value of each element to zero.
> >
>    >>> mylist = [0]*10
>    >>> mylist
>    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

I thought it would be something like that.  I played around with several 
variations, but couldn't get it to work.  Thanks Kirby.


From kalle@gnupung.net  Sat Dec  8 02:18:15 2001
From: kalle@gnupung.net (Kalle Svensson)
Date: Sat, 8 Dec 2001 03:18:15 +0100
Subject: [Tutor] Initializing a list as an array
In-Reply-To: <200112071926968.SM06048@there>
References: <4.2.0.58.20011207172205.00a8cf10@pop3.norton.antivirus> <200112071926968.SM06048@there>
Message-ID: <20011208031814.B14085@sandra.lysator.liu.se>

[Scott]
> On Friday 07 December 2001 07:24 pm, you wrote:
> >
> > >Suppose I want to initialize a list that I want to use like an
> > >array, setting the initial value of each element to zero.
> > >
> >    >>> mylist = [0]*10
> >    >>> mylist
> >    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
> 
> I thought it would be something like that.  I played around with several 
> variations, but couldn't get it to work.  Thanks Kirby.

Just a little warning here, this doesn't extend to multidimensional lists:

>>> mymatrix = [[0]*3]*3
>>> mymatrix
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Seems nice enough, eh?  But:

>>> mymatrix[0][0] = 1
>>> mymatrix
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

The reason is that list are mutable objects (i.e. their contents can be
changed during the execution of the program).  Integers (such as 0) are not.
mylist = [0] * 3
creates a list containing three references to the object 0.
myarray = [[0] * 3] * 3
creates a list containing three references to a list object containing three
references to the object 0.

Weird?  Not helping?  Sorry. <wink>
In fact, this (references and mutable/immutable objects) is one of the things
I like very much about Python, but it took me a while to understand it.

Finally, code that does the thing you might expect from the example above:

>>> mymatrix = [[0] * 3 for x in xrange(3)]
>>> mymatrix[0][0] = 1
>>> mymatrix 
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

Oh, and I'm sure this is in the FAQ.  Hope you don't mind my posting anyway.

Peace,
  Kalle
-- 
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]


From jrm@videotron.ca  Fri Dec  7 22:56:28 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Sat, 8 Dec 2001 00:56:28 +0200
Subject: [Tutor] to whomever was looking for a list of %
Message-ID: <000701c17f72$67b810c0$0100c0a8@videotron.ca>

    Sorry if it took so long and for forgetting your name.

    The complete list of string formating "%" is at :
http://www.python.org/doc/current/lib/typesseq-strings.html

Jean M.



From DEVIOUSDIABLO@aol.com  Sat Dec  8 01:51:31 2001
From: DEVIOUSDIABLO@aol.com (DEVIOUSDIABLO@aol.com)
Date: Fri, 7 Dec 2001 20:51:31 EST
Subject: [Tutor] i want to ask something.
Message-ID: <141.5f4764e.2942cc23@aol.com>

--part1_141.5f4764e.2942cc23_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

i want to know if you have to have equipment and stuff for your computer to 
hack and how to hack on a game called diablo.please tell me how without 
equipment if you can.i seriously want to be a hacker.

--part1_141.5f4764e.2942cc23_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

<HTML><FONT FACE=arial,helvetica><FONT  SIZE=2>i want to know if you have to have equipment and stuff for your computer to hack and how to hack on a game called diablo.please tell me how without equipment if you can.i seriously want to be a hacker.</FONT></HTML>

--part1_141.5f4764e.2942cc23_boundary--


From dyoo@hkn.eecs.berkeley.edu  Sat Dec  8 07:02:58 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 7 Dec 2001 23:02:58 -0800 (PST)
Subject: [Tutor] Re: [Python] Help
In-Reply-To: <20011207.214710.-215185.0.kozaks_2000@juno.com>
Message-ID: <Pine.LNX.4.21.0112072301590.29939-100000@hkn.eecs.berkeley.edu>

On Fri, 7 Dec 2001, robert w kozak wrote:

> Yes a Distutils!! That is what I'm looking for I'm installing my
> calculator on a computer that doesn't have python. Also do you have a
> program that compiles a .py .pyc .pyo or whatever in to an executable
> windows file??

Yes, you can use py2exe to package .py files into an executable:

    http://py2exe.sourceforge.net/

Hope this helps!



From David@snowcrash.co.uk  Sat Dec  8 10:16:31 2001
From: David@snowcrash.co.uk (David)
Date: Sat, 8 Dec 2001 10:16:31 -0000
Subject: [Tutor] Blank line added when reading in from file????
In-Reply-To: <F1473iVdGJ5OGQOuE3c00014119@hotmail.com>
Message-ID: <000601c17fd1$683b1740$f0c67bd5@HIRO>

This is a multi-part message in MIME format.

------=_NextPart_000_0007_01C17FD1.683C9DE0
Content-Type: text/plain;
	charset="us-ascii"
Content-Transfer-Encoding: 7bit

Phelim
 
I think that Andrei means the email you are sending to the list is HTML
as opposed to plain text.  Many email programs do not display HTML
format email.  This is usually desirable as this is one of the easiest
ways to spread viri by email (as you can config the HTML pages to
autorun the "bad" scripts).  It is hard to switch off the display of
HTML email in MSOutlook but Russ Cooper of NTBugtraq has released a
patch to do this, very sad MS don't have this as a standard option.
 
<g> completely unpython related response but hope it fills in a blank
bit!

Cheers

David 

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org] On Behalf
Of Phelim Kelly
Sent: 05 December 2001 10:11
To: ak@silmarill.org; tutor@python.org
Subject: Re: [Tutor] Blank line added when reading in from file????



Thanks for your response Andrei,

                                                I'm not sure I
understand your response! I'm not using HTML files, I'm working on a
UNIX machine. The file I'm reading from is a plain text file.

 

Hello, 

Many e-mail programs can't edit HTML directly. If you want to get 
maximum response, send plain text messages. 
- Andrei 
-- 
Cymbaline: intelligent learning mp3 player - python, linux, console. 
get it at: cy.silmarill.org 
_______________________________________________ 
Tutor maillist - Tutor@python.org 
http://mail.python.org/mailman/listinfo/tutor 

  _____  

Get your FREE download of MSN Explorer at http://explorer.msn.com
<http://go.msn.com/bql/hmtag_itl_EN.asp> 
_______________________________________________ Tutor maillist -
Tutor@python.org http://mail.python.org/mailman/listinfo/tutor 


------=_NextPart_000_0007_01C17FD1.683C9DE0
Content-Type: text/html;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3Dus-ascii">
<TITLE>Message</TITLE>

<META content=3D"MSHTML 6.00.2600.0" name=3DGENERATOR></HEAD>
<BODY>
<DIV><SPAN class=3D089431210-08122001><FONT face=3DArial color=3D#0000ff =

size=3D2>Phelim</FONT></SPAN></DIV>
<DIV>&nbsp;</DIV>
<DIV><SPAN class=3D089431210-08122001><FONT face=3DArial color=3D#0000ff =
size=3D2>I=20
think that Andrei means the email you are sending to the list is HTML as =
opposed=20
to plain text.&nbsp; Many email programs do not display HTML format =
email.&nbsp;=20
This is usually desirable as this is one of the easiest ways to spread =
viri by=20
email (as you can config the HTML pages to autorun the "bad" =
scripts).&nbsp; It=20
is hard to switch off the display of HTML email in MSOutlook but Russ =
Cooper of=20
NTBugtraq has released a patch to do this, very sad MS don't have this =
as a=20
standard option.</FONT></SPAN></DIV>
<DIV><SPAN class=3D089431210-08122001><FONT face=3DArial color=3D#0000ff =

size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D089431210-08122001><FONT face=3DArial color=3D#0000ff =

size=3D2>&lt;g&gt; completely unpython related response but hope it =
fills in a=20
blank bit!</FONT></SPAN></DIV><!-- Converted from text/plain format -->
<P><FONT size=3D2>Cheers<BR><BR>David </FONT></P>
<BLOCKQUOTE style=3D"MARGIN-RIGHT: 0px">
  <DIV></DIV>
  <DIV class=3DOutlookMessageHeader lang=3Den-us dir=3Dltr =
align=3Dleft><FONT=20
  face=3DTahoma size=3D2>-----Original Message-----<BR><B>From:</B>=20
  tutor-admin@python.org [mailto:tutor-admin@python.org] <B>On Behalf Of =

  </B>Phelim Kelly<BR><B>Sent:</B> 05 December 2001 10:11<BR><B>To:</B>=20
  ak@silmarill.org; tutor@python.org<BR><B>Subject:</B> Re: [Tutor] =
Blank line=20
  added when reading in from file????<BR><BR></FONT></DIV>
  <DIV>
  <DIV>
  <P>Thanks for your response Andrei,</P>
  =
<P>&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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
  I'm not sure I understand your response! I'm not using HTML files, I'm =
working=20
  on a UNIX machine. The file I'm reading from is a plain text file.</P>
  <P>&nbsp;</P>
  <P>Hello, </P></DIV>
  <DIV></DIV>
  <DIV></DIV>Many e-mail programs can't edit HTML directly. If you want =
to get=20
  <DIV></DIV>maximum response, send plain text messages.=20
  <DIV></DIV>
  <DIV></DIV>- Andrei=20
  <DIV></DIV>
  <DIV></DIV>--=20
  <DIV></DIV>Cymbaline: intelligent learning mp3 player - python, linux, =

  console.=20
  <DIV></DIV>get it at: cy.silmarill.org=20
  <DIV></DIV>
  <DIV></DIV>_______________________________________________=20
  <DIV></DIV>Tutor maillist - Tutor@python.org=20
  <DIV></DIV>http://mail.python.org/mailman/listinfo/tutor=20
  <DIV></DIV></DIV><BR clear=3Dall>
  <HR>
  Get your FREE download of MSN Explorer at <A=20
  =
href=3D"http://go.msn.com/bql/hmtag_itl_EN.asp">http://explorer.msn.com</=
A><BR>_______________________________________________=20
  Tutor maillist - Tutor@python.org=20
  http://mail.python.org/mailman/listinfo/tutor =
</BLOCKQUOTE></BODY></HTML>

------=_NextPart_000_0007_01C17FD1.683C9DE0--



From glingl@aon.at  Sat Dec  8 11:17:17 2001
From: glingl@aon.at (Gregor Lingl)
Date: Sat, 8 Dec 2001 12:17:17 +0100
Subject: [Tutor] i want to ask something.
References: <141.5f4764e.2942cc23@aol.com>
Message-ID: <001401c17fd9$e5b8d150$1664a8c0@mega>

then first read this.

http://www.tuxedo.org/~esr/faqs/hacker-howto.html

is it this what you want?

Gregor

----- Original Message -----
From: DEVIOUSDIABLO@aol.com
To: tutor@python.org
Sent: Saturday, December 08, 2001 2:51 AM
Subject: [Tutor] i want to ask something.


i want to know if you have to have equipment and stuff for your computer to
hack and how to hack on a game called diablo.please tell me how without
equipment if you can.i seriously want to be a hacker.



From urnerk@qwest.net  Sat Dec  8 16:44:57 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 08 Dec 2001 08:44:57 -0800
Subject: [Tutor] Initializing a list as an array
In-Reply-To: <20011208031814.B14085@sandra.lysator.liu.se>
References: <200112071926968.SM06048@there>
 <4.2.0.58.20011207172205.00a8cf10@pop3.norton.antivirus>
 <200112071926968.SM06048@there>
Message-ID: <4.2.0.58.20011208084327.01abe800@pop3.norton.antivirus>

>
>Just a little warning here, this doesn't extend to multidimensional
>lists:
> >>> mymatrix = [[0]*3]*3
> >>> mymatrix
>[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Excellent point re a common pitfall for new Python
programmers, Kalle.  Your example is very clear.


>Finally, code that does the thing you might expect from the example above:
>
> >>> mymatrix = [[0] * 3 for x in xrange(3)]
> >>> mymatrix[0][0] = 1
> >>> mymatrix
>[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

...as is your solution.

Kirby



From kromag@nsacom.net  Sat Dec  8 18:51:43 2001
From: kromag@nsacom.net (kromag@nsacom.net)
Date: Sat, 8 Dec 2001 12:51:43 -0600 (CST)
Subject: [Tutor] (no subject)
Message-ID: <200112081851.fB8Ipge22195@pop.nsacom.net>



From kromag@nsacom.net  Sat Dec  8 19:09:05 2001
From: kromag@nsacom.net (kromag@nsacom.net)
Date: Sat, 8 Dec 2001 13:09:05 -0600 (CST)
Subject: [Tutor] _curses.error: addstr() returned ERR
Message-ID: <200112081909.fB8J95e10633@pop.nsacom.net>

Howdy,

I have run on to a bit of a head scratcher with curses.

(The entire script with all the attendant postgres stuff can be found at 
http://www.angryrobot.org/Jabulon.py)


while 1:
        for room in roomlist:
            text='%s. '%(room)
            screen.addstr(text)
            prompt=screen.getstr()
            if prompt == 'read':
                pointer.execute("select * from post where room_name='%s'"%
(room))
                #pe is shorthand for "post element".
                for pe in pointer.fetchall():
                    msg_output=" Posted by %s, %s.n%snn"%(pe[2],time.ctime
(string.atof(pe[0])),pe[4])
                    screen.addstr(msg_output)
                    text='Press return to continuen'
                    screen.addstr(text)
                    screen.getch()
            elif prompt=='quit':
                sys.exit()
            elif prompt == '':
                pass
            elif prompt == 'enter':
                text="Enter Messagen> "
                screen.addstr(text)
                msg=screen.getstr()
                #testing only...
                rm='%s'%(room)
                dummy=time.time(),rm,username,msg
                pointer.execute("insert into post values(%s,'%s','%s','','%
s')"%(dummy))
                db.commit()
            else:
                pass


The first time I run through the loop 'reading' works just fine. However upon 
the second run it poops out with:

Traceback (most recent call last):
  File "./jabulon.py", line 90, in ?
    screen.addstr(msg_output)
_curses.error: addstr() returned ERR

The library reference states:

ERR 
Some curses routines that return an integer, such as getch(), return ERR upon 
failure. 

so I figure (brilliant, I know) that addstr() also returns ERR upon failure. 
Does the problem somehow lie in:

msg_output=" Posted by %s, %s.n%snn"%(pe[2],time.ctime(string.atof(pe
[0])),pe[4])

when I convert the date string to a float? Is there a safer way to do this?








From kromag@nsacom.net  Sat Dec  8 19:11:54 2001
From: kromag@nsacom.net (kromag@nsacom.net)
Date: Sat, 8 Dec 2001 13:11:54 -0600 (CST)
Subject: [Tutor] _curses.error: addstr() returned ERR
Message-ID: <200112081911.fB8JBse21788@pop.nsacom.net>

Howdy,

I have run on to a bit of a head scratcher with curses.

(The entire script with all the attendant postgres stuff can be found at 
http://www.angryrobot.org/Jabulon.py)


while 1:
        for room in roomlist:
            text='%s. '%(room)
            screen.addstr(text)
            prompt=screen.getstr()
            if prompt == 'read':
                pointer.execute("select * from post where room_name='%s'"%
(room))
                #pe is shorthand for "post element".
                for pe in pointer.fetchall():
                    msg_output=" Posted by %s, %s.n%snn"%(pe[2],time.ctime
(string.atof(pe[0])),pe[4])
                    screen.addstr(msg_output)
                    text='Press return to continuen'
                    screen.addstr(text)
                    screen.getch()
            elif prompt=='quit':
                sys.exit()
            elif prompt == '':
                pass
            elif prompt == 'enter':
                text="Enter Messagen> "
                screen.addstr(text)
                msg=screen.getstr()
                #testing only...
                rm='%s'%(room)
                dummy=time.time(),rm,username,msg
                pointer.execute("insert into post values(%s,'%s','%s','','%
s')"%(dummy))
                db.commit()
            else:
                pass


The first time I run through the loop 'reading' works just fine. However upon 
the second run it poops out with:

Traceback (most recent call last):
  File "./jabulon.py", line 90, in ?
    screen.addstr(msg_output)
_curses.error: addstr() returned ERR

The library reference states:

ERR 
Some curses routines that return an integer, such as getch(), return ERR upon 
failure. 

so I figure (brilliant, I know) that addstr() also returns ERR upon failure. 
Does the problem somehow lie in:

msg_output=" Posted by %s, %s.n%snn"%(pe[2],time.ctime(string.atof(pe
[0])),pe[4])

when I convert the date string to a float? Is there a safer way to do this?








From syrinx@simplecom.net  Sun Dec  9 04:23:45 2001
From: syrinx@simplecom.net (Scott)
Date: Sat, 8 Dec 2001 22:23:45 -0600
Subject: [Tutor] Making a better list
Message-ID: <200112082224734.SM06048@there>

In Python, if I want to make a list-like class (a specialized list of x's, 
say), is it generally better to create a class with a member list, or derive 
a class from the built-in 'list' type (I don't know how to do that yet.)
HTNTS

(that means 'hope that's not too stupid'  :)

Thanks.




From dyoo@hkn.eecs.berkeley.edu  Sun Dec  9 05:57:30 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 8 Dec 2001 21:57:30 -0800 (PST)
Subject: [Tutor] Making a better list
In-Reply-To: <200112082224734.SM06048@there>
Message-ID: <Pine.LNX.4.21.0112082130430.17035-100000@hkn.eecs.berkeley.edu>

On Sat, 8 Dec 2001, Scott wrote:

> In Python, if I want to make a list-like class (a specialized list of
> x's, say), is it generally better to create a class with a member
> list, or derive a class from the built-in 'list' type (I don't know
> how to do that yet.)


Hi Scott.  Yes, it's very possible to derive from the UserList class:

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

What we can do is subclass a UserList, and then modify specific behavior,
like how the list pulls elements out.  Here's a list of the possible
list-like things that we can redefine:

    http://python.org/doc/current/ref/sequence-types.html


For example, perhaps we might want to make a list that capitalizes any
string that we put into it.  We could do something like this:

###
>>> class CapitalList(UserList.UserList):
...     def __setitem__(self, key, value):
...         if type(value) == types.StringType:
...             value = string.upper(value)
...         self.data[key] = value
>>> l = CapitalList(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[4] = 'hello, this is a test'
>>> l
[0, 1, 2, 3, 'HELLO, THIS IS A TEST', 5, 6, 7, 8, 9]
###


Ok, ok, I admit, this example is completely Useless.  *grin* But it shows
that this stuff shouldn't be too difficult to do.



A more serious example might be to make a kind of list that doesn't give
IndexErrors if we try to assign elements beyond the list's size.

###
import UserList
class LooseList(UserList.UserList):
    def __setitem__(self, key, value):
        if key >= len(self.data):
            self.expandList(key - len(self.data) + 1)
        self.data[key] = value

    def expandList(self, length):
        for i in range(length):
            self.append(None)
###

Let's see if it works ok:

###
>>> l = LooseList(['hello', 'world'])
>>> l = LooseList(['hello', 'world'])
>>> l[4] = 'divas'
>>> l[42] = 'answer to life'
>>> l
['hello', 'world', None, None, 'divas', None, None, None, None, None,
 None, None, None, None, None, None, None, None, None, None, None, None,
 None, None, None, None, None, None, None, None, None, None, None, None,
 None, None, None, None, None, None, None, None, 'answer to life']
###

As a warning: this is not to say that I encourage the use of this
LooseList: I think it's way too loose.  *grin* But it's nice to see that
we have the power to extend Python this way if we wanted.




> HTNTS
> 
> (that means 'hope that's not too stupid'  :)

That's not a stupid question at all!  That was a fun question.  I hope
this helps!



From toodles@yifan.net  Sun Dec  9 11:48:21 2001
From: toodles@yifan.net (Andy W)
Date: Sun, 9 Dec 2001 19:48:21 +0800
Subject: [Tutor] asynchat
Message-ID: <000701c180a7$681ed770$0300a8c0@sun>

Hi people

Has anyone seen any programs that use asynchat? At the moment I'm reading
through asynchat.py, but I'd like an example to follow through as well.

Regards,
Andy.



From lha2@columbia.edu  Sun Dec  9 12:29:09 2001
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Sun, 09 Dec 2001 07:29:09 -0500
Subject: [Tutor] Making a better list
References: <Pine.LNX.4.21.0112082130430.17035-100000@hkn.eecs.berkeley.edu>
Message-ID: <3C135915.11CE6F7A@mail.verizon.net>

Danny Yoo wrote:
> 
> ###
> import UserList
> class LooseList(UserList.UserList):
>     def __setitem__(self, key, value):
>         if key >= len(self.data):
>             self.expandList(key - len(self.data) + 1)
>         self.data[key] = value
> 
>     def expandList(self, length):
>         for i in range(length):
>             self.append(None)
> ###
> 
> Let's see if it works ok:
> 
> ###
> >>> l = LooseList(['hello', 'world'])
> >>> l = LooseList(['hello', 'world'])
> >>> l[4] = 'divas'
> >>> l[42] = 'answer to life'
> >>> l
> ['hello', 'world', None, None, 'divas', None, None, None, None, None,
>  None, None, None, None, None, None, None, None, None, None, None, None,
>  None, None, None, None, None, None, None, None, None, None, None, None,
>  None, None, None, None, None, None, None, None, 'answer to life']
> ###
> 
> As a warning: this is not to say that I encourage the use of this
> LooseList: I think it's way too loose.  *grin* But it's nice to see that
> we have the power to extend Python this way if we wanted.
> 

But if we replace "None" with "0", and make the list two dimensional,
this would be just the ticket for converting a sparse matrix defined by
the dictionary method (i.e., entries that exist have key of index and
value of value) into explicit matrices (two dimensional lists, with zero
as the value of entries that didn't previously "exist").

Or did somebody already uselessize this.


From dsh8290@rit.edu  Sun Dec  9 13:11:54 2001
From: dsh8290@rit.edu (dman)
Date: Sun, 9 Dec 2001 08:11:54 -0500
Subject: [Tutor] Making a better list
In-Reply-To: <Pine.LNX.4.21.0112082130430.17035-100000@hkn.eecs.berkeley.edu>; from dyoo@hkn.eecs.berkeley.edu on Sat, Dec 08, 2001 at 09:57:30PM -0800
References: <200112082224734.SM06048@there> <Pine.LNX.4.21.0112082130430.17035-100000@hkn.eecs.berkeley.edu>
Message-ID: <20011209081154.C11320@harmony.cs.rit.edu>

On Sat, Dec 08, 2001 at 09:57:30PM -0800, Danny Yoo wrote:
| On Sat, 8 Dec 2001, Scott wrote:
| 
| > In Python, if I want to make a list-like class (a specialized list of
| > x's, say), is it generally better to create a class with a member
| > list, or derive a class from the built-in 'list' type (I don't know
| > how to do that yet.)
| 
| 
| Hi Scott.  Yes, it's very possible to derive from the UserList class:
| 
|     http://www.python.org/doc/lib/module-UserList.html

Or, if you have 2.2, you can subclass the built-in 'list'.

class MyList( list ) :
    pass

I think a good rule-of-thumb for deciding whether to use inheritance
or composition is :

    o   how much is your new type supposed to behave like the existing
        type?

    o   how much of the existing functionality do you want to keep
        as-is?

If you only want to change a little bit of the functionality,
inheritance would be easier, but composition is still easy enough with
the __getattr__ and __setattr__ methods.

HTH,
-D

-- 

Contrary to popular belief, Unix is user friendly.
It just happens to be selective about who it makes friends with.
                                               -- Dave Parnas



From fpeavy@pop.net  Sun Dec  9 18:27:45 2001
From: fpeavy@pop.net (Frank Peavy)
Date: Sun, 09 Dec 2001 10:27:45 -0800
Subject: [Tutor] OO terms and definitions
Message-ID: <5.1.0.14.0.20011209102056.00aa9c60@mail45566.popserver.pop.net>

I am a little(or is that a lot) confused about some OO terminology.
I have some quite a bit on the web and I have seen all sorts of definitions 
for the following terms:
Module
    Class
       Function?
       Method?
       Procedure?

It seems to me that there is a hierarchy to some degree, as idented above.
And, I am under the impression that a Module is usually a file with a .py 
extension that contains the other items.

Does a Module always have a Class? I am under the impression that this is 
not the case.

How do Function, Method and Procedure differ? Or are they the same...?



From ak@silmarill.org  Sun Dec  9 18:42:38 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Sun, 09 Dec 2001 13:42:38 -0500
Subject: [Tutor] OO terms and definitions
In-Reply-To: <5.1.0.14.0.20011209102056.00aa9c60@mail45566.popserver.pop.net>
References: <5.1.0.14.0.20011209102056.00aa9c60@mail45566.popserver.pop.net>
Message-ID: <20011209134238.A9767@sill.silmarill.org>

On Sun, Dec 09, 2001 at 10:27:45AM -0800, Frank Peavy wrote:
> I am a little(or is that a lot) confused about some OO terminology.
> I have some quite a bit on the web and I have seen all sorts of definitions 
> for the following terms:
> Module
>    Class
>       Function?
>       Method?
>       Procedure?
> 
> It seems to me that there is a hierarchy to some degree, as idented above.
> And, I am under the impression that a Module is usually a file with a .py 
> extension that contains the other items.

Yep

> 
> Does a Module always have a Class? I am under the impression that this is 
> not the case.

You're right. Class is a "kind" of something. For example, you might
have a class Tree, 2 subclasses - Pine and Oak, and 2 instances of Pine
- pine that grows in your garden and pine that grows in Central Park in
  manhattan.


> 
> How do Function, Method and Procedure differ? Or are they the same...?

Procedure is just another name for a function. Function is some code
that is grouped under one name and can be called and executed using that
name. Method is a function that is associated with an object - for
example, the Pine class may have a method called die that would kill the
pine when run.

class Tree:
    # method that runs when class is instantiated
    def __init__(self):
        self.alive = "yes"

    def die(self):
        self.alive = "no"
        print "This tree is dead now."

class Pine(Tree):
    # I don't remember exactly but I think the __init__ method is an
    # exception because you have to explicitly re-run it in inherited
    # class.. die method will be inherited automatically
    def __init__(self):
        Tree.__init__()     # run Tree's __init__

my_garden_pine = Pine()         # make an instance of Pine (instantiate
                                # Pine)
print my_garden_pine.alive      # will print "yes"
my_garden_pine.die()            # run die method; will print "this tree
                                # is dead now"
print my_garden_pine.alive      # will print "no"

> 
> 
> _______________________________________________
> 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 fpeavy@pop.net  Sun Dec  9 18:54:10 2001
From: fpeavy@pop.net (Frank Peavy)
Date: Sun, 09 Dec 2001 10:54:10 -0800
Subject: [Tutor] compiled Python Files ?? and a little OO
Message-ID: <5.1.0.14.0.20011209102938.00aae780@mail45566.popserver.pop.net>

I created three simple files to test with:
*************************************************************
F1.py file and all it contains is:

print "Hello"
*************************************************************
Another file F2.py that contains:

print "JSmith"
*************************************************************
I have one more FX.py file that contains:

import F1.py
import F2.py
*************************************************************
My end result was:

Hello
JSmith

The results seem correct, in my opinion.
So, here are my questions. Although I didn't request it, Python did a line 
feed between Hello and JSmith, is this normal?

After I ran this, I noticed that I had two new versions of F1 and F2; the 
directory showed "Compiled Python file" as a description and they had .pyc 
extensions. Why didn't I see this happening with my other tests? Is it 
because the other tests imported Tkinter?

I understand I can run the .pyc files, instead of the .py files. Is this true?

Why didn't I get a FX.pyc file also... ? The first two files compiled but 
the third file that imported the other two didn't.

A little confused...  :-)



From ak@silmarill.org  Sun Dec  9 18:57:47 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Sun, 09 Dec 2001 13:57:47 -0500
Subject: [Tutor] compiled Python Files ?? and a little OO
In-Reply-To: <5.1.0.14.0.20011209102938.00aae780@mail45566.popserver.pop.net>
References: <5.1.0.14.0.20011209102938.00aae780@mail45566.popserver.pop.net>
Message-ID: <20011209135747.A9869@sill.silmarill.org>

On Sun, Dec 09, 2001 at 10:54:10AM -0800, Frank Peavy wrote:
> I created three simple files to test with:
> *************************************************************
> F1.py file and all it contains is:
> 
> print "Hello"
> *************************************************************
> Another file F2.py that contains:
> 
> print "JSmith"
> *************************************************************
> I have one more FX.py file that contains:
> 
> import F1.py
> import F2.py
> *************************************************************
> My end result was:
> 
> Hello
> JSmith
> 
> The results seem correct, in my opinion.
> So, here are my questions. Although I didn't request it, Python did a line 
> feed between Hello and JSmith, is this normal?

You did request it by using print statement - it prints a newline as a
default, because in most cases you want it there. To have a space
instead of a newline, put a comma after the first print:
print "blah",
print "trah"

> 
> After I ran this, I noticed that I had two new versions of F1 and F2; the 
> directory showed "Compiled Python file" as a description and they had .pyc 
> extensions. Why didn't I see this happening with my other tests? Is it 
> because the other tests imported Tkinter?
> 
> I understand I can run the .pyc files, instead of the .py files. Is this 
> true?
> 
> Why didn't I get a FX.pyc file also... ? The first two files compiled but 
> the third file that imported the other two didn't.
> 
> A little confused...  :-)

They get compiled to .pyc when they're imported.

> 
> 
> _______________________________________________
> 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 dsh8290@rit.edu  Sun Dec  9 20:19:27 2001
From: dsh8290@rit.edu (dman)
Date: Sun, 9 Dec 2001 15:19:27 -0500
Subject: [Tutor] OO terms and definitions
In-Reply-To: <5.1.0.14.0.20011209102056.00aa9c60@mail45566.popserver.pop.net>; from fpeavy@pop.net on Sun, Dec 09, 2001 at 10:27:45AM -0800
References: <5.1.0.14.0.20011209102056.00aa9c60@mail45566.popserver.pop.net>
Message-ID: <20011209151927.C11602@harmony.cs.rit.edu>

On Sun, Dec 09, 2001 at 10:27:45AM -0800, Frank Peavy wrote:
| I am a little(or is that a lot) confused about some OO terminology.
| I have some quite a bit on the web and I have seen all sorts of definitions 
| for the following terms:
| Module
|     Class
|        Function?
|        Method?
|        Procedure?
| 
| It seems to me that there is a hierarchy to some degree, as idented above.
| And, I am under the impression that a Module is usually a file with a .py 
| extension that contains the other items.
| 
| Does a Module always have a Class? I am under the impression that this is 
| not the case.

So far so good.

Note that in some languages classes and functions can nest, and others
have restrictions on it.  Python falls in the former category.  In C
and C++ there is no nesting allowed.  In Java a class can be nested
inside another class or method, but methods cannot be nested in other
methods.  I don't know if Eiffel allows nesting or not.

| How do Function, Method and Procedure differ? Or are they the same...?

Pragmatically they are the same.

The Java community likes to call them "methods".  The C/C++ community
calls them functions (whether they are in a class or not).  The Eiffel
community calls the ones that modify state but don't return a value
"procedures" and the ones that return a value but don't modify state
"functions" (and they don't like ones that do both).

Technically in Python a "function" is not part of a class.  Either it
is at the module level or it is a nested function in the local
namespace of another function.  A "method" is part of a class.  If it
is unbound it has no instance associated with it, if it is bound it
has an instance associated with it.

You can pretty much use the terms interchangeably, except when you get
into the semantic details of "function" vs. "unbound method" vs.
"bound method".

-D

-- 

In his heart a man plans his course,
but the Lord determines his steps.
        Proverbs 16:9



From dsh8290@rit.edu  Sun Dec  9 20:25:18 2001
From: dsh8290@rit.edu (dman)
Date: Sun, 9 Dec 2001 15:25:18 -0500
Subject: [Tutor] compiled Python Files ?? and a little OO
In-Reply-To: <5.1.0.14.0.20011209102938.00aae780@mail45566.popserver.pop.net>; from fpeavy@pop.net on Sun, Dec 09, 2001 at 10:54:10AM -0800
References: <5.1.0.14.0.20011209102938.00aae780@mail45566.popserver.pop.net>
Message-ID: <20011209152518.D11602@harmony.cs.rit.edu>

On Sun, Dec 09, 2001 at 10:54:10AM -0800, Frank Peavy wrote:
...
| After I ran this, I noticed that I had two new versions of F1 and F2; the 
| directory showed "Compiled Python file" as a description and they had .pyc 
| extensions. Why didn't I see this happening with my other tests? Is it 
| because the other tests imported Tkinter?

When a module is imported, the bytecodes are stored in a .pyc file.
This allows for faster loading the next time the module is imported,
if the source hasn't changed.

| I understand I can run the .pyc files, instead of the .py files. Is
| this true?

I believe you can remove the .py file from the directory and the
program would run the same.  I have never had a need to do this, so I
haven't tested it out.

| Why didn't I get a FX.pyc file also... ? The first two files compiled but 
| the third file that imported the other two didn't.

This is because ran that file directly, instead of importing it.  A
typical layout is to have a file named for the application (with no
.py extension) file that looks like

--------
#!/usr/bin/env python
import main
main.main()
--------

then have a main.py that includes a main() function[1] where the
program's logic begins.

-D


[1]  Note :  unlike C, C++, and Java there is no requirement on the
     name given, "main" just happens to be quite common (no doubt as a
     result of practice with the above languages).

-- 

"Don't use C;  In my opinion,  C is a library programming language
 not an app programming language."  - Owen Taylor (GTK+ developer)



From urnerk@qwest.net  Sun Dec  9 21:29:21 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 09 Dec 2001 13:29:21 -0800
Subject: [Tutor] OO terms and definitions
In-Reply-To: <20011209151927.C11602@harmony.cs.rit.edu>
References: <5.1.0.14.0.20011209102056.00aa9c60@mail45566.popserver.pop.net>
 <5.1.0.14.0.20011209102056.00aa9c60@mail45566.popserver.pop.net>
Message-ID: <4.2.0.58.20011209132810.015a7c30@pop3.norton.antivirus>

I seem to recall reading somewhere at the Python site
that soon, if not already, we'd be able to subclass
modules themselves, making them seem more like classes.
Was I dreaming?

Kirby



From dsh8290@rit.edu  Sun Dec  9 21:32:00 2001
From: dsh8290@rit.edu (dman)
Date: Sun, 9 Dec 2001 16:32:00 -0500
Subject: [Tutor] OO terms and definitions
In-Reply-To: <4.2.0.58.20011209132810.015a7c30@pop3.norton.antivirus>; from urnerk@qwest.net on Sun, Dec 09, 2001 at 01:29:21PM -0800
References: <5.1.0.14.0.20011209102056.00aa9c60@mail45566.popserver.pop.net> <5.1.0.14.0.20011209102056.00aa9c60@mail45566.popserver.pop.net> <20011209151927.C11602@harmony.cs.rit.edu> <4.2.0.58.20011209132810.015a7c30@pop3.norton.antivirus>
Message-ID: <20011209163200.A12102@harmony.cs.rit.edu>

On Sun, Dec 09, 2001 at 01:29:21PM -0800, Kirby Urner wrote:
| 
| I seem to recall reading somewhere at the Python site
| that soon, if not already, we'd be able to subclass
| modules themselves, making them seem more like classes.
| Was I dreaming?

I don't know, but it would be cool if you weren't :-).  We can
subclass built-in types in 2.2.

-D

-- 

If your company is not involved in something called "ISO 9000" you
probably have no idea what it is.  If your company _is_ involved in ISO
9000 then you definitely have no idea what it is.
                                (Scott Adams - The Dilbert principle)



From dyoo@hkn.eecs.berkeley.edu  Sun Dec  9 21:59:23 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 9 Dec 2001 13:59:23 -0800 (PST)
Subject: [Tutor] compiled Python Files ?? and a little OO (fwd)
Message-ID: <Pine.LNX.4.21.0112091356260.2172-100000@hkn.eecs.berkeley.edu>

Hi Frank,

I think you meant to send this to the "tutor@python.org" address.  The
"tutor-admin@python.org" only sends it off to the list admins.

I'll forward your message to the rest of the list.  Best of wishes to you.


---------- Forwarded message ----------
Date: Sun, 09 Dec 2001 10:54:10 -0800
From: Frank Peavy <fpeavy@pop.net>
To: tutor-python.org <tutor@python.org>
Subject: [Tutor] compiled Python Files ?? and a little OO

I created three simple files to test with:
*************************************************************
F1.py file and all it contains is:

print "Hello"
*************************************************************
Another file F2.py that contains:

print "JSmith"
*************************************************************
I have one more FX.py file that contains:

import F1.py
import F2.py
*************************************************************
My end result was:

Hello
JSmith

The results seem correct, in my opinion.
So, here are my questions. Although I didn't request it, Python did a line 
feed between Hello and JSmith, is this normal?

After I ran this, I noticed that I had two new versions of F1 and F2; the 
directory showed "Compiled Python file" as a description and they had .pyc 
extensions. Why didn't I see this happening with my other tests? Is it 
because the other tests imported Tkinter?

I understand I can run the .pyc files, instead of the .py files. Is this true?

Why didn't I get a FX.pyc file also... ? The first two files compiled but 
the third file that imported the other two didn't.

A little confused...  :-)


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




From dyoo@hkn.eecs.berkeley.edu  Sun Dec  9 22:25:21 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 9 Dec 2001 14:25:21 -0800 (PST)
Subject: [Tutor] compiled Python Files ?? [print / .pyc and import]
In-Reply-To: <Pine.LNX.4.21.0112091356260.2172-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.21.0112091400320.2172-100000@hkn.eecs.berkeley.edu>

> I created three simple files to test with:
> *************************************************************
> F1.py file and all it contains is:
> 
> print "Hello"
> *************************************************************
> Another file F2.py that contains:
> 
> print "JSmith"
> *************************************************************
> I have one more FX.py file that contains:
> 
> import F1.py
> import F2.py

Hmmm... did this work?  Your FX.py file might need:

###
import F1
import F2
###

instead: Python knows how to look for Python modules, as long as we give
it the name.  It knows that '.py' files hold Python modules, so we don't
need to put the extension here when we import modules.



> So, here are my questions. Although I didn't request it, Python did a
> line feed between Hello and JSmith, is this normal?

Yes.  The 'print' statement puts in a "line feed" for convenience, so that
people aren't surprised when they try something like this:

###
>>> def test():
...     print "Hello"
...     print  
...     print "world!"
... 
>>> test()
Hello

world!
###


This way, we can skip lines just by doing a

###
print
###

which many feel is nice.


However, perhaps we don't want 'print' to skip lines.  If we put a
trailing comma on a print statement, 'print' will put a space instead:

###
>>> def test2():
...     print "hello",
...     print "world!"
... 
>>> test2()
hello world!
###



> After I ran this, I noticed that I had two new versions of F1 and F2;
> the directory showed "Compiled Python file" as a description and they
> had .pyc extensions. Why didn't I see this happening with my other
> tests? Is it because the other tests imported Tkinter?

It's because your FX.py program imported the other two 'modules' --- doing
an import has this effect.  Let's talk about this below.



> I understand I can run the .pyc files, instead of the .py files. Is
> this true?

Yes, it's true.  However, I wouldn't recommend deleting the .py files,
sine the .pyc files are very unreadable.  *grin*



> Why didn't I get a FX.pyc file also... ? The first two files compiled but 
> the third file that imported the other two didn't.

Ah!  But if we had a third program that did something like:

###
import FX
###

Python will make an FX.pyc file for us.

A 'pyc' file is Python's representation of our program.  Python needs to
chew our Python "source" into small bytecodes, because the underlying
Python engine can deal with these bites...er... bytes fairly easily.  In
many cases, these bytecodes are just kept in memory, and disappear after a
program is done.

However, If a module is imported, Python expects that it might be worth it
to save the bytecodes to disk, so that next time, if we ever import that
module again, Python can just slurp up the .pyc file instead of chewing.  
.pyc files are there to allow our programs to be loaded faster, but that's
about it.



From pierre.leonavicius@pandora.be  Sun Dec  9 17:49:40 2001
From: pierre.leonavicius@pandora.be (Pierre Leonavicius)
Date: Sun, 9 Dec 2001 18:49:40 +0100
Subject: [Tutor] screen display commands
Message-ID: <NFBBIPNLMLPABKNCPPJPEEFGCAAA.pierre.leonavicius@pandora.be>

This is a multi-part message in MIME format.

------=_NextPart_000_0000_01C180E2.427DF600
Content-Type: multipart/alternative;
	boundary="----=_NextPart_001_0001_01C180E2.42871DC0"


------=_NextPart_001_0001_01C180E2.42871DC0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hi,

Where can i find the syntax for screen commands?
Such als displaying/inputing text on a specific place on computer-screen?
Colors, blinking and so on.

thanks for help

Pierre Leonavicius

gsm:+32(0)473/99.14.85

* pierre.leonavicius@pandora.be

fax1:+32(0)11/84.46.29




------=_NextPart_001_0001_01C180E2.42871DC0
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">
<STYLE>BODY {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
P.msoNormal {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
LI.msoNormal {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
PRE {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
BLOCKQUOTE {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
A {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
MENU {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
DD {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
UL {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
DT {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
DIR {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
ADDRESS {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
H1 {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
H2 {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
H3 {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
H4 {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
H5 {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
H6 {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
HR {
	MARGIN-TOP: 0em; FONT-SIZE: 12pt; MARGIN-BOTTOM: 0em; COLOR: #000000; =
FONT-FAMILY: "Arial"
}
</STYLE>

<META content=3D"MSHTML 6.00.2600.0" name=3DGENERATOR></HEAD>
<BODY background=3Dcid:850244517@09122001-2a81>
<DIV><SPAN class=3D850244517-09122001><FONT face=3D'"Arial"'=20
size=3D2>Hi,</FONT></SPAN></DIV>
<DIV><SPAN class=3D850244517-09122001><FONT =
size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D850244517-09122001><FONT size=3D2>Where can i find =
the syntax for=20
screen commands?</FONT></SPAN></DIV>
<DIV><SPAN class=3D850244517-09122001><FONT size=3D2>Such als =
displaying/inputing=20
text on a specific place on&nbsp;computer-screen?</FONT></SPAN></DIV>
<DIV><SPAN class=3D850244517-09122001><FONT size=3D2>Colors, blinking =
and so=20
on.</FONT></SPAN></DIV>
<DIV><SPAN class=3D850244517-09122001><FONT =
size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D850244517-09122001><FONT size=3D2>thanks for=20
help</FONT></SPAN></DIV>
<DIV><SPAN class=3D850244517-09122001><FONT =
size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV class=3DSection1>
<P class=3DMsoNormal style=3D"mso-layout-grid-align: none"><B><SPAN =
lang=3DFR=20
style=3D"FONT-SIZE: 10pt; COLOR: blue; FONT-FAMILY: Arial; =
mso-ansi-language: FR">Pierre=20
Leonavicius</SPAN></B><SPAN lang=3DFR=20
style=3D"mso-ansi-language: FR"><?xml:namespace prefix =3D o ns =3D=20
"urn:schemas-microsoft-com:office:office" /><o:p></o:p></SPAN></P>
<P class=3DMsoNormal style=3D"mso-layout-grid-align: none"><B><SPAN =
lang=3DFR=20
style=3D"FONT-SIZE: 10pt; COLOR: blue; FONT-FAMILY: Arial; =
mso-ansi-language: FR">gsm:+32(0)473/99.14.85<o:p></o:p></SPAN></B></P>
<P class=3DMsoNormal style=3D"mso-layout-grid-align: none"><B><SPAN =
lang=3DDE=20
style=3D"COLOR: silver; FONT-FAMILY: Wingdings; mso-ansi-language: DE; =
mso-bidi-font-family: Arial">*</SPAN></B><SPAN=20
lang=3DDE=20
style=3D"FONT-SIZE: 8.5pt; COLOR: silver; FONT-FAMILY: 'MS Sans Serif'; =
mso-ansi-language: DE; mso-bidi-font-family: Arial">=20
</SPAN><B><SPAN lang=3DFR=20
style=3D"FONT-SIZE: 10pt; COLOR: silver; FONT-FAMILY: Arial; =
mso-ansi-language: =
FR">pierre.leonavicius@pandora.be<o:p></o:p></SPAN></B></P>
<P class=3DMsoNormal style=3D"mso-layout-grid-align: none"><B><SPAN =
lang=3DNL-BE=20
style=3D"FONT-SIZE: 10pt; COLOR: silver; FONT-FAMILY: Arial; =
mso-ansi-language: =
NL-BE">fax1:+32(0)11/84.46.29<o:p></o:p></SPAN></B></P>
<P class=3DMsoNormal style=3D"mso-layout-grid-align: none"><FONT=20
face=3D'"Arial"'></FONT>&nbsp;</P></DIV></BODY></HTML>

------=_NextPart_001_0001_01C180E2.42871DC0--

------=_NextPart_000_0000_01C180E2.427DF600
Content-Type: image/gif;
	name="tech.gif"
Content-Transfer-Encoding: base64
Content-ID: <850244517@09122001-2a81>

R0lGODlhFAAUAPcAAP//////zP//mf//Zv//M///AP/M///MzP/Mmf/MZv/MM//MAP+Z//+ZzP+Z
mf+ZZv+ZM/+ZAP9m//9mzP9mmf9mZv9mM/9mAP8z//8zzP8zmf8zZv8zM/8zAP8A//8AzP8Amf8A
Zv8AM/8AAMz//8z/zMz/mcz/Zsz/M8z/AMzM/8zMzMzMmczMZszMM8zMAMyZ/8yZzMyZmcyZZsyZ
M8yZAMxm/8xmzMxmmcxmZsxmM8xmAMwz/8wzzMwzmcwzZswzM8wzAMwA/8wAzMwAmcwAZswAM8wA
AJn//5n/zJn/mZn/Zpn/M5n/AJnM/5nMzJnMmZnMZpnMM5nMAJmZ/5mZzJmZmZmZZpmZM5mZAJlm
/5lmzJlmmZlmZplmM5lmAJkz/5kzzJkzmZkzZpkzM5kzAJkA/5kAzJkAmZkAZpkAM5kAAGb//2b/
zGb/mWb/Zmb/M2b/AGbM/2bMzGbMmWbMZmbMM2bMAGaZ/2aZzGaZmWaZZmaZM2aZAGZm/2ZmzGZm
mWZmZmZmM2ZmAGYz/2YzzGYzmWYzZmYzM2YzAGYA/2YAzGYAmWYAZmYAM2YAADP//zP/zDP/mTP/
ZjP/MzP/ADPM/zPMzDPMmTPMZjPMMzPMADOZ/zOZzDOZmTOZZjOZMzOZADNm/zNmzDNmmTNmZjNm
MzNmADMz/zMzzDMzmTMzZjMzMzMzADMA/zMAzDMAmTMAZjMAMzMAAAD//wD/zAD/mQD/ZgD/MwD/
AADM/wDMzADMmQDMZgDMMwDMAACZ/wCZzACZmQCZZgCZMwCZAABm/wBmzABmmQBmZgBmMwBmAAAz
/wAzzAAzmQAzZgAzMwAzAAAA/wAAzAAAmQAAZgAAMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAFAAUAEAIQwBJCBxI
sKBBAAgTKlyYUCDDhwsdQpwoceLDihYjksh4cSNHjR9BhmzocSQAjCFRflTJkWVGlxZhUiw5UiZE
gzhzBgQAOw==

------=_NextPart_000_0000_01C180E2.427DF600--



From highprimate@howlermonkey.net  Sun Dec  9 22:26:07 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Sun, 9 Dec 2001 17:26:7 -0500
Subject: [Tutor] further ignorant babbling, but with prettier words
Message-ID: <200112092226.fB9MQA325669@ns.howlermonkey.net>

Lookee what I been up to.

----------begin seasoned bits----------------
#!/usr/local/bin/python
# Tinylist module, Pitchtime unit.
# this handles receiving and sending out postings to a list.

import sys, re, string, rfc822, smtplib

localhost = 'howlermonkey.net'	# make sure you set this to the domain YOU use!!!

pathtostuff = '/www/www.howlermonkey.net/cgi-bin/'	#please edit this to suit your system.
						# note this tells where to start looking.
						# everything is either here, ur under this
						# point in a systematic manner.
					
listname = argv[1]			# we read a command line arguement to determine the list 
name
						# Arguement 0 is the name of the script run, 1 is the
						# first arguement
						# after that name in the command line, so if this were
						# program FOO,
						# that line would be "|/path/FOO listname"
						# and the arguement here would be 'listname'!
					
message = raw_input.lines()		# Variable 'message' is assigned the entire message
						# which is piped to the program by the alias definition
						# such as:
						# foolist:"|/pathtoprogram/programname foolist"

						# now we must determine the sender and see if they are in
						# the subscriber file!
from = message["From"]

open a.file(pathtostuff + "/lists/" + listname, 'r')						
members = a.readlines()
a.close()

if pos( from, message] :	# IF the sender is in the subscriber file, THEN:
		subject = '[' + listname + ']' + subject		# '[listname] whatever they said'
		X-Mailing-List = listname + "@" + localhost	# This breaks email loops from 
forming.
		Reply_to = listname + "@" + localhost		# this sets the reply-to field.
	else
		listnamemembers = from	# only one 'member' in the list of 'subscribers' here!
		message = ""		# clear the unauthorized posting.
		From = "From: tinylist@" + localhost + \n # From: tinylist@mydomain.foo !
		Subject = message + "Subject: Unauthorized posting to list" + listname + \n
		Reply_to = message + "Reply-to:postmaster@" + localhost + \n
		message = message + """
		To whom it may concern;
		
		Sorry, but as you are not a current member of """ + listname + """, 
		you may not post to it. Your recent posting has been rejected and destroyed.
		
		Feel free to contact the postmaster if there is any question.
		Any reply to this letter should go directly to the postmaster.
		
		You can also subscribe to this list if you like.
		
		Goodbye.
		
		"""

# ok, if they are not a member, THEY GET THE REPLY SHOWN ABOVE MAILED TO THEM!
# above is a blank line, DO NOT DELETE IT! it defines the end of the if then else 
structure!
# there is no endif or fi in python. whitespace is rather important here.
# now we send whatever message is to go out to whatever is in the recipient tupple.

for i in listnamemembers :
	helo()
	a.connect()
	a.sendmail(from_addr, to_addr, Subject, reply-to, to, X-Mailing-List, msg)
	a.quit()
	
# make sure this script runs as a TRUSTED USER- and NOT as root!!! Make sure a
# NON-priviliged user can run this script, and make sure it is owned by that identity!
--------------end seasoned bits------------


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From dyoo@hkn.eecs.berkeley.edu  Sun Dec  9 22:44:16 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 9 Dec 2001 14:44:16 -0800 (PST)
Subject: [Tutor] further ignorant babbling, but with prettier words
In-Reply-To: <200112092226.fB9MQA325669@ns.howlermonkey.net>
Message-ID: <Pine.LNX.4.21.0112091429220.2172-100000@hkn.eecs.berkeley.edu>

On Sun, 9 Dec 2001, Kirk Bailey wrote:

> Lookee what I been up to.

Cool!  Let's take a look.



> import sys, re, string, rfc822, smtplib
> 
> localhost = 'howlermonkey.net'	# make sure you set this to the domain YOU use!!!
> 
> pathtostuff = '/www/www.howlermonkey.net/cgi-bin/'	#please edit this to suit your system.
> 						# note this tells where to start looking.
> 						# everything is either here, ur under this
> 						# point in a systematic manner.
> 					
> listname = argv[1]			# we read a command line arguement to determine the list 


You'll probably need to use 'sys.argv' instead, because:

> import sys

doesn't automatically pull the 'argv' arguments variable out of the
module.  If we do something like:

###
argv = sys.argv
###

right at the beginning, though, that'll allow us to get at sys.argv by
just saying 'argv'.





> message = raw_input.lines()		# Variable 'message' is assigned the entire message

Try:

    message = sys.stdin.read()

instead.  raw_input() is a function that only knows how to read a single
line --- it won't respond favorably if we try to use it to read multiple
lines at a time:

###
>>> raw_input.lines()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: lines
###


'sys.stdin', on the other hand, is a "file":

    http://www.python.org/doc/lib/bltin-file-objects.html

that should know how to read():

###
>>> message = sys.stdin.read()
hello world
this is a test
I'd better stop now.
## At this point, I press Ctrl-D.  On Windows systems, Ctrl-Z should
## also get Python to stop reading from standard input.
>>> message
"hello world\nthis is a test\nI'd better stop now.\n"
###





> from = message["From"]

Before doing this, we'll probably need to 'parse' or process the message
string out to grab at the message's headers, probably using the rfc822
module we talked about a few days ago:

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



> open a.file(pathtostuff + "/lists/" + listname, 'r')

Try:

    a = open(pathtostuff + "/lists/" + listname)

which translates to "Let's assign 'a' to the open()ing of this file.  
What you had below tries to say "Try calling the file() method of 'a'"
which dosen't work, because Python doesn't know what 'a' means yet.



See if it works a little better.  Also, remember that you can always using
the interpreter to play around and experiment with Python.



From highprimate@howlermonkey.net  Sun Dec  9 22:49:11 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Sun, 9 Dec 2001 17:49:11 -0500
Subject: [Tutor] Paths
Message-ID: <200112092249.fB9MnE325766@ns.howlermonkey.net>

I am a heretic.

There is a really popular standard for how to organize directory trees on a un*x computer, and it drives me 
bats. It is functionally structured. But I'm apparently dysfunctional, and give not a damn for this 
approach. 
I like my data safe, and organized on a conceptual association basis.

For instance, it is unwise to let the world run files located in the same dir as many system files. so 
instead 
of execiting web or email cgi scripts in /bin or /sbin with a link, I place them right in the cgi-bin, which 
is the ONLY place the world can run or access such stuff. I make sure the scripts are owned by a identity 
with 
restricted permissions.

The files for an application are placed in directories under the cgi-bin, and if more than one is needed, I 
try to keep them gogether on  one bag (parent direcory) under the cgi-bin.

Do let's assume a function FOOBAR uses 3 directories, FOOBAIT, FOODATA, FOORECORDS.

The tree would be:

/www/cgi-bin/+foobar
             +/foobar+
                     +/FOOBAIT
                     +/FOODATA
                     +/FOORECORDS

Which seems to make sense to me somehow, whereas the system some people want to declare the offical standard 
leaves me drooling on my keyboard as the brains turn into sludge.

Now, I am working on a simple list management program, and to make each part simpler and smaller, it will be 
modular. Each module will only entail a narrow scope of tasks. The part I posted now (which is not yet 
complete) is the one to handle incoming posts to existing lists, the posttime module. 

One way to organize information is to place every list in a directory called TinyLists. Each list has a flat 
text file of addresses alone, which has the name of that list. other files for that list should also wear 
that 
list's name, and a word to describe what the file is. So if there was a footer file, and the list was named 
Teddybearclub, the footer file would be called 'teddybearclub.footer'. Using name conventions such as this 
let 
me place all the list stuff in a single directory. 

Sorting them out to a group of directories would mean each directory had the name of the list, and all sich 
contained a pile of files which had identical names from dir to dir, the ontly thing which changes is the 
PATH. Although this makes the bath more complex, handling the file names is simpler. Just change the path 
ONCE, and the program referrs to the standard files in that location, no firther stuff required. I am 
wunderins what the advantages of each are, such as speed of access, potential for operator mindfuck, and 
other  
possibly not noticed as of yet issues. 

I invite discussion.




end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|





From highprimate@howlermonkey.net  Sun Dec  9 23:04:53 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Sun, 9 Dec 2001 18:4:53 -0500
Subject: [Tutor] (no subject)
Message-ID: <200112092305.fB9N4v325881@ns.howlermonkey.net>

Updated cooking.
--------------------new bits-------------------------
#!/usr/local/bin/python
# Tinylist module, Pitchtime unit.
# this handles receiving and sending out postings to a list.

import sys, re, string, rfc822, smtplib

localhost = 'howlermonkey.net'	# make sure you set this to the domain YOU use!!!

pathtostuff = '/www/www.howlermonkey.net/cgi-bin/'	#please edit this to suit your system.
						# note this tells where to start looking.
						# everything is either here, ur under this
						# point in a systematic manner.
					
listname = sys.argv[1]			# we read a command line arguement to determine the list name
						# Arguement 0 is the name of the script run, 1 is the
						# first arguement
						# after that name in the command line, so if this were
						# program FOO,
						# that line would be "|/path/FOO listname"
						# and the arguement here would be 'listname'!
					
message = raw_input.lines()		# Variable 'message' is assigned the entire message
						# which is piped to the program by the alias definition
						# such as:
						# foolist:"|/pathtoprogram/programname foolist"

						# now we must determine the sender and see if they are in
						# the subscriber file!
						# still got to learn more about how this thing handles
						# parsing the incoming message, but smtp and rfc822
						# are dep sorcery on this material.
from = message["From"]

open a.file(pathtostuff + "/lists/" + listname, 'r')						
members = a.readlines()
a.close()

if string.find(members, from):					# IF the sender is in the subscriber, 
		subject = '[' + listname + ']' + subject		# then acept the submission.
		X-Mailing-List = listname + "@" + localhost	# This breaks email loops from forming.
		Reply_to = listname + "@" + localhost		# this sets the reply-to field.
		ftr = b.open(pathtostuff + "/lists/footer,"+ listname,'r')
		footer = ftr.readlines()				# reads the footer into the script
		ftr.close()
		message = message + footer				# and append it to the message.
	else
		listnamemembers = from					# we do this if the posterwas not found!
		message = ""						# clear the unauthorized posting.
		From = "From: tinylist@" + localhost + \n 	# From: tinylist@mydomain.foo !
		Subject = message + "Subject: Unauthorized posting to list" + listname + \n
		Reply_to = message + "Reply-to:postmaster@" + localhost + \n
		message = message + """
		To whom it may concern;
		
		Sorry, but as you are not a current member of """ + listname + """, 
		you may not post to it. Your recent posting has been rejected and destroyed.
		
		Feel free to contact the postmaster if there is any question.
		Any reply to this letter should go directly to the postmaster.
		
		You can also subscribe to this list if you like.
		
		Goodbye.
		
		"""

# ok, if they are not a member, THEY GET THE REPLY SHOWN ABOVE MAILED TO THEM!
# above is a blank line, DO NOT DELETE IT! it defines the end of the if then else structure!
# there is no endif or fi in python. whitespace is rather important here.
# now we send whatever message is to go out to whatever is in the recipient tupple.

for i in listnamemembers :
	helo()
	a.connect()
	a.sendmail(from_addr, to_addr, Subject, reply-to, to, X-Mailing-List, msg)
	a.quit()
	
# make sure this script runs as a TRUSTED USER- and NOT as root!!! Make sure a
# NON-priviliged user can run this script, and make sure it is owned by that identity!
----------------------------------end new bits------------------------------------------


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From highprimate@howlermonkey.net  Sun Dec  9 23:35:01 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Sun, 9 Dec 2001 18:35:1 -0500
Subject: [Tutor] (no subject)
Message-ID: <200112092335.fB9NZ4326016@ns.howlermonkey.net>

ok, in IDLE I created a variable, listnamemembers, and inserted a bunch of info in it, with triple quotes.
listnamemembers = """me@here.net
you@there.org
Me@here2.com
everybody@earth.edu
nobody@domainerror.cc
"""

and I tried to look at these chunks of data.

for i in listnamemembers:
	print i

and got this:
y
o
u
@
t
h
e
r
e
.
o
r
g

m
e
@
h
e
r
e
.
o
r
g
.... you get the idea.

ok, how do I read each line as an entire line, not char by char?




end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From jrm@videotron.ca  Sun Dec  9 17:13:25 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Sun, 9 Dec 2001 19:13:25 +0200
Subject: [Tutor] screen display commands
References: <NFBBIPNLMLPABKNCPPJPEEFGCAAA.pierre.leonavicius@pandora.be>
Message-ID: <001001c180d4$d049bcc0$0100c0a8@videotron.ca>

----- Original Message -----
From: "Pierre Leonavicius" <pierre.leonavicius@pandora.be>

> Where can i find the syntax for screen commands?
> Such als displaying/inputing text on a specific place on computer-screen?
> Colors, blinking and so on.

    I'll try that one,

        - first, don't use HTML on a mailing list like you just did : it
ruffles the feathers of many who are using text only mail readers. They get
a mess of HTML code that is quite hard to read, especially when it comes
from Oulook Express.

        Now to the question. I guess that you looking for GUI (graphical
user interface) programming. Otherwise you would need "curses", another
interface that has windows but which is text only.
        There are many flavors of GUI for Python :
            -Tkinter is the one that comes with your distribution of Python.
It is the most universal working on Windows, Unixes (all of them ?) and Mac
(reasonnably well or so they say). I use it and it's OK. I need something
portable.
            -wxPython : pretty face, supposed to be easier to program but
not available for Mac.
            -pyGTK and pyKDE: for flavors of Unixes mostly, if I'm not
mistaking.

    So look for these names in Google and you should find plenty information
on each. Also Alan Gauld's tutorial at
http://www.freenetpages.co.uk/hp/alan.gauld/ ; the guy has a book in print
so some ass will consider what I'm doing to be spamming : the heck with him.
Since your first name is Pierre and you're calling from Belgium there are
chances that you can read French :
http://www.ulg.ac.be/cifen/inforef/swi/python.htm offers some really
excellent notes and involves itself pretty quickly with GUI programming
(Tkinter as it's almost always the case). Look at the bottom of the TOC page
for a link to a PDF version.
    Something I missed the first time I searched :
http://www.nmt.edu/tcc/help/lang/python/tkinter.html look for the first of
the local link since that doc uses plain English the most of all available
on the net.

    In any case you will have to understand the basis of (Pyton) programming
(data types, branching, looping, that stuff) to effectively create a GUI.

    Bon plaisir ;)

    Jean M.






From jrm@videotron.ca  Sun Dec  9 17:43:42 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Sun, 9 Dec 2001 19:43:42 +0200
Subject: [Tutor] Is there a heaven for old instances ?
Message-ID: <000701c180d9$0b64d2a0$0100c0a8@videotron.ca>

    I wonder :
        when I re-assing a variable like this :
            a=3
            a=4
            a="Couldn't you make up you mind ?"
    the old values (e.g. 3 and 4) are destroyed or so I read. (BTW is that
what "garbage collection" does ?).

    Now if I create and instance, let's say this way:
        instance1=Button(somewhere, lots of options or none)
    and then for some (stupid?) reason I go:
        instance1=Button(somewhere_else_or_not, new options_maybe)
    what happens to the first instance which is much more complex than a
simple variable ?

    Jean M.




From wilson@visi.com  Mon Dec 10 01:30:14 2001
From: wilson@visi.com (Timothy Wilson)
Date: Sun, 9 Dec 2001 19:30:14 -0600 (CST)
Subject: [Tutor] string formatting and right justifying text
Message-ID: <Pine.GSO.4.21.0112091927540.12950-100000@isis.visi.com>

Hi everyone,

I'm working on the next project for my students and I'd like to have them
print a table of stock prices, number of shares, etc. I can't figure out the
string formatting codes to right-justify integers or floating point numbers
so I can make the table look right. Any pointers?

-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 dsh8290@rit.edu  Mon Dec 10 02:48:03 2001
From: dsh8290@rit.edu (dman)
Date: Sun, 9 Dec 2001 21:48:03 -0500
Subject: [Tutor] Is there a heaven for old instances ?
In-Reply-To: <000701c180d9$0b64d2a0$0100c0a8@videotron.ca>; from jrm@videotron.ca on Sun, Dec 09, 2001 at 07:43:42PM +0200
References: <000701c180d9$0b64d2a0$0100c0a8@videotron.ca>
Message-ID: <20011209214803.B12822@harmony.cs.rit.edu>

On Sun, Dec 09, 2001 at 07:43:42PM +0200, Jean Montambeault wrote:
|     I wonder :
|         when I re-assing a variable like this :
|             a=3
|             a=4
|             a="Couldn't you make up you mind ?"
|     the old values (e.g. 3 and 4) are destroyed or so I read. (BTW is that
| what "garbage collection" does ?).

Yes.  It just so happens that CPython creates the integers -1..99 at
startup because they are so commonly used, so in this case it doesn't
go away.  (I don't know if Jython does this or not)  Aside from this
special case, you are correct.

|     Now if I create and instance, let's say this way:
|         instance1=Button(somewhere, lots of options or none)
|     and then for some (stupid?) reason I go:
|         instance1=Button(somewhere_else_or_not, new options_maybe)
|     what happens to the first instance which is much more complex than a
| simple variable ?

The same thing.  If there are no more references to the first Button
instance, it is destroyed.  If you have stuck it in a frame or kept a
reference somewhere, it is not destroyed, you just don't have a
reference in the local scope.

-D

-- 

If your life is a hard drive,
Christ can be your backup.



From dsh8290@rit.edu  Mon Dec 10 02:53:59 2001
From: dsh8290@rit.edu (dman)
Date: Sun, 9 Dec 2001 21:53:59 -0500
Subject: [Tutor] screen display commands
In-Reply-To: <001001c180d4$d049bcc0$0100c0a8@videotron.ca>; from jrm@videotron.ca on Sun, Dec 09, 2001 at 07:13:25PM +0200
References: <NFBBIPNLMLPABKNCPPJPEEFGCAAA.pierre.leonavicius@pandora.be> <001001c180d4$d049bcc0$0100c0a8@videotron.ca>
Message-ID: <20011209215358.C12822@harmony.cs.rit.edu>

On Sun, Dec 09, 2001 at 07:13:25PM +0200, Jean Montambeault wrote:
| ----- Original Message -----
| From: "Pierre Leonavicius" <pierre.leonavicius@pandora.be>
| 
| > Where can i find the syntax for screen commands?
| > Such als displaying/inputing text on a specific place on computer-screen?
| > Colors, blinking and so on.
 
If you want a text screen look at the 'curses' module.  It is
available only for Unix systems, but cygwin on windows has curses
support too (you'll need a python built with cygwin, 2.1 comes
ready-made).

| -wxPython : pretty face, supposed to be easier to program but not
| available for Mac.

wxPython is a nice consistent interface around the native toolkit.
That is, on windows is looks just like other windows apps, and on *nix
it looks just like other GTK or Motif apps (depending on the users
version).  A Mac port is in the works, but I'm not up on the status of
it.

| -pyGTK and pyKDE: for flavors of Unixes mostly, if I'm not mistaking.

There is actually 4 different frameworks mentioned here :

PyGTK
PyGNOME

PyQt
PyKDE


PyGTK and PyQt work on Unix and Windows.  GTK and Qt are GUI toolkits,
not entire desktop environments.

I expect PyKDE to work since I have personally run KDE (1.1.2) on
Windows (with cygwin and xfree).  Someone got GNOME to run on windows,
but I haven't gotten it to compile.  Typically GNOME and KDE are Unix
desktop environments.

If you use PyGTK or PyGNOME, then take a look at the 'glade' program
and the 'libglade' library.  It greatly simplifies making a GUI.

-D

-- 

"...the word HACK is used as a verb to indicate a massive amount
of nerd-like effort."  -Harley Hahn, A Student's Guide to Unix



From dsh8290@rit.edu  Mon Dec 10 02:57:42 2001
From: dsh8290@rit.edu (dman)
Date: Sun, 9 Dec 2001 21:57:42 -0500
Subject: [Tutor] string formatting and right justifying text
In-Reply-To: <Pine.GSO.4.21.0112091927540.12950-100000@isis.visi.com>; from wilson@visi.com on Sun, Dec 09, 2001 at 07:30:14PM -0600
References: <Pine.GSO.4.21.0112091927540.12950-100000@isis.visi.com>
Message-ID: <20011209215742.D12822@harmony.cs.rit.edu>

On Sun, Dec 09, 2001 at 07:30:14PM -0600, Timothy Wilson wrote:
| Hi everyone,
| 
| I'm working on the next project for my students and I'd like to have them
| print a table of stock prices, number of shares, etc. I can't figure out the
| string formatting codes to right-justify integers or floating point numbers
| so I can make the table look right. Any pointers?

All the format string codes are documented in 'man printf'.  It is
identical to C/C++ string formatting.  To right justify text in a
fixed-width field :

>>> print "%20s" % "yo"
                  yo
>>> print "%-20s" % "yo"
yo                  
>>> print "%20d" % 5
                  5
>>> print "%-20d" % 5
5      
>>>

HTH,
-D

-- 

If any of you lacks wisdom, he should ask God, who gives generously to
all without finding fault, and it will be given to him.  But when he
asks he must believe and not doubt, because he who doubts is like a wave
of the sea, blown and tossed by the wind.
        James 1:5-6



From pythonpython@hotmail.com  Mon Dec 10 03:51:02 2001
From: pythonpython@hotmail.com (HY)
Date: Mon, 10 Dec 2001 12:51:02 +0900
Subject: [Tutor] sys.argv  and windows 2k
Message-ID: <OE58dD9f6MGjN59koV50000db42@hotmail.com>

I have python script which takes 3 arguments.
Under Windows 98 and Linux(Unix) prompt, it works fine:
python action.py arg1 arg2 arg3

If I "print sys.argv", I get ['action.py', 'arg1', 'arg2', 'arg3'] .


However,$B!!(Bwhen I try to run the script under a Windows 2000's cmd prompt the
script stopped taking 3 arguments.
It now only accept the first two the arguments I typed.
When I do a "print sys.argv", I only get ['action.py', 'arg1', 'arg2'] .

Could you please tell me why this is possible and how to make the script
work under Windows 2000?

Thanks a lot.


Hy


From dyoo@hkn.eecs.berkeley.edu  Mon Dec 10 04:03:38 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 9 Dec 2001 20:03:38 -0800 (PST)
Subject: [Tutor] string splitting
In-Reply-To: <200112092335.fB9NZ4326016@ns.howlermonkey.net>
Message-ID: <Pine.LNX.4.21.0112091942210.11171-100000@hkn.eecs.berkeley.edu>

Hi Kirk,


On Sun, 9 Dec 2001, Kirk Bailey wrote:

> ok, in IDLE I created a variable, listnamemembers, and inserted a
> bunch of info in it, with triple quotes.
> listnamemembers = """me@here.net
> you@there.org
> Me@here2.com
> everybody@earth.edu
> nobody@domainerror.cc
> """

'listnamemembers' here is a string.  Although we as humans might consider
it a bunch of lines, Python's instincts is to treat strings as a sequence
of single characters, which is why when we do a 'for' loop across it:

> for i in listnamemembers:
> 	print i

Python will go through each character in 'listnamemembers'.  That's why
the program prints every character, one per line.  Personally, I like
this, because it allows certain things to be easy, like this:

###
>>> def isVowel(letter):
...     return letter in 'aeiouAEIOU'
... 
>>> isVowel('z')
0
>>> isVowel('e')
1
###



Anyway, back to your question: what we want to do, instead, is tell Python
to "split" between the lines, to break our string down between new lines.  
We can do this if we use the string.split() function, like this:

###
>>> string.split(listnamemembers, '\n')
['me@here.net', 'you@there.org', 'Me@here2.com', 'everybody@earth.edu',
 'nobody@domainerror.cc', '']
###


That gives us a list of single lines, exactly what you're looking for!
It's also something we can feed into a for loop:

###
>>> for address in string.split(listnamemembers, '\n'):
...     print "Here's one email address: ", address
... 
Here's one email address:  me@here.net
Here's one email address:  you@there.org
Here's one email address:  Me@here2.com
Here's one email address:  everybody@earth.edu
Here's one email address:  nobody@domainerror.cc
Here's one email address:  
###


In the command above, '\n' is the "newline" string, so we're telling
Python to split up listnamemembers between new lines.  We can be silly and
split against something, else, like the '@' symbol:

###
>>> string.split(listnamemembers, '@')
['me', 'here.net\nyou', 'there.org\nMe', 'here2.com\neverybody',
 'earth.edu\nnobody', 'domainerror.cc\n']
###

Actually, this might actually be useful, since splitting between '@'
allows us to pull out a user's name from their email address.  
string.split() is a very good tool, and worth using.



> In total confusion,

Hey, don't worry about it; it'll make sense eventually.  Programming take
practice, so don't be too hard on yourself.  Just wondering, are you
reading through a tutorial from the Python web site, or something else?

I'm going to get some dinner now.  I'll talk to you later!



From dyoo@hkn.eecs.berkeley.edu  Mon Dec 10 04:49:19 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 9 Dec 2001 20:49:19 -0800 (PST)
Subject: [Tutor] string splitting (fwd)
Message-ID: <Pine.LNX.4.21.0112092049010.11305-100000@hkn.eecs.berkeley.edu>


---------- Forwarded message ----------
Date: Sun, 9 Dec 2001 23:45:58 -0500
From: Kirk Bailey <highprimate@howlermonkey.net>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: Re: [Tutor] string splitting

At 12/9/01 8:03:00 PM, you wrote:
>Hi Kirk,
>
>
>On Sun, 9 Dec 2001, Kirk Bailey wrote:
>
>> ok, in IDLE I created a variable, listnamemembers, and inserted a
>> bunch of info in it, with triple quotes.
>> listnamemembers = """me@here.net
>> you@there.org
>> Me@here2.com
>> everybody@earth.edu
>> nobody@domainerror.cc
>> """
>
>'listnamemembers' here is a string.  Although we as humans might consider
>it a bunch of lines, Python's instincts is to treat strings as a sequence
>of single characters, which is why when we do a 'for' loop across it:
>
>> for i in listnamemembers:
>> 	print i
>
>Python will go through each character in 'listnamemembers'.  That's why
>the program prints every character, one per line.  Personally, I like
>this, because it allows certain things to be easy, like this:
>

Well, I read a file into the idle, and looked at the variable which I loaded it into with readlines, and it 
was ['data\ndata\ndata\ndata\n'] which was disturbing. But educational.

>###
>>>> def isVowel(letter):
>....     return letter in 'aeiouAEIOU'
>.... 
>>>> isVowel('z')
>0
>>>> isVowel('e')
>1
>###
>
>
>
>Anyway, back to your question: what we want to do, instead, is tell Python
>to "split" between the lines, to break our string down between new lines.  
>We can do this if we use the string.split() function, like this:
>
>###
>>>> string.split(listnamemembers, '\n')
>['me@here.net', 'you@there.org', 'Me@here2.com', 'everybody@earth.edu',
> 'nobody@domainerror.cc', '']
>###
>
>
>That gives us a list of single lines, exactly what you're looking for!
>It's also something we can feed into a for loop:
>
>###
>>>> for address in string.split(listnamemembers, '\n'):
>....     print "Here's one email address: ", address
>.... 
>Here's one email address:  me@here.net
>Here's one email address:  you@there.org
>Here's one email address:  Me@here2.com
>Here's one email address:  everybody@earth.edu
>Here's one email address:  nobody@domainerror.cc
>Here's one email address:  
>###
>
>
>In the command above, '\n' is the "newline" string, so we're telling
>Python to split up listnamemembers between new lines.  We can be silly and
>split against something, else, like the '@' symbol:
>
>###
>>>> string.split(listnamemembers, '@')
>['me', 'here.net\nyou', 'there.org\nMe', 'here2.com\neverybody',
> 'earth.edu\nnobody', 'domainerror.cc\n']
>###
>
>Actually, this might actually be useful, since splitting between '@'
>allows us to pull out a user's name from their email address.  
>string.split() is a very good tool, and worth using.

Well worth studying then. Grindgrindgrindgrind...

>
>
>
>> In total confusion,
>
>Hey, don't worry about it; it'll make sense eventually.  Programming take
>practice, so don't be too hard on yourself.  Just wondering, are you
>reading through a tutorial from the Python web site, or something else?

Yes, and yes. Book from library which is clear as mud, and 3 different tutorals, and the on line reference.

And this correspondance.
>
>I'm going to get some dinner now.  I'll talk to you later!

Yum, Laser chicken stir fry. Quack-quack and I had ravioli earlier this evening.
Quack Quack, aka QUACKULA, is a quaker parrot. Got another one, Tiny, on my neck supervising right now. We 
have a bunch of parrots ya see. Florida is funny that way, bird people all over, it's the climate. Where you 
is?

>
>
>


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From highprimate@howlermonkey.net  Mon Dec 10 05:14:08 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Mon, 10 Dec 2001 0:14:8 -0500
Subject: [Tutor] ohoh...
Message-ID: <200112100514.fBA5EF328109@ns.howlermonkey.net>

This account has it's own dedicated client, and there is no replyall button!!! oops...

I think this is a drastic omission. Better see if I can ask the writer of the program(foxmail) if thre is a 
newer version out with a replyall button.


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|





From urnerk@qwest.net  Mon Dec 10 06:40:23 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 09 Dec 2001 22:40:23 -0800
Subject: [Tutor] (no subject)
In-Reply-To: <200112092335.fB9NZ4326016@ns.howlermonkey.net>
Message-ID: <4.2.0.58.20011209223351.019e2680@pop3.norton.antivirus>

At 06:35 PM 12/9/2001 -0500, Kirk Bailey wrote:
>ok, in IDLE I created a variable, listnamemembers, and
>inserted a bunch of info in it, with triple quotes.
>listnamemembers = """me@here.net
>you@there.org
>Me@here2.com
>everybody@earth.edu
>nobody@domainerror.cc
>"""

Instead of making your data be one long character string,
you might use a list with string elements:

  >>> listmembers = ['me@here.net',
                     'you@there.org',
                     'Me@here2.com',
                     'everybody@earth.edu',
                     'nobody@domainerror.cc']
  >>>
  >>> for i in listmembers:  print i

  me@here.net
  you@there.org
  Me@here2.com
  everybody@earth.edu
  nobody@domainerror.cc

When you iterate over a list, you get its elements,
whereas when you iterate over a string, you get each
character, which is what was happening when you went
the triple-quotes route.

Kirby



From highprimate@howlermonkey.net  Mon Dec 10 06:54:00 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Mon, 10 Dec 2001 1:54:0 -0500
Subject: [Tutor] (no subject)
Message-ID: <200112100654.fBA6s7328698@ns.howlermonkey.net>

Well, see, I am sneaking up on reading a text file which is a list of subscribers to a list.

The idea is to read it in, and store it in a list, with each line in that file a item in the list.
But I see what you mean. I should load it as several strings, not one long string. Loading it as one long 
string it fails to recognize the thing is many chunks of data, and treats it as one big chunk.

I am currently playing with a created file with some dummy accounts (all are real, and I own them all, so 
when i finally move to testing on live code, no one is going to yell at me).



At 12/9/01 10:40:00 PM, you wrote:
>At 06:35 PM 12/9/2001 -0500, Kirk Bailey wrote:
>>ok, in IDLE I created a variable, listnamemembers, and
>>inserted a bunch of info in it, with triple quotes.
>>listnamemembers = """me@here.net
>>you@there.org
>>Me@here2.com
>>everybody@earth.edu
>>nobody@domainerror.cc
>>"""
>
>Instead of making your data be one long character string,
>you might use a list with string elements:
>
>  >>> listmembers = ['me@here.net',
>                     'you@there.org',
>                     'Me@here2.com',
>                     'everybody@earth.edu',
>                     'nobody@domainerror.cc']
>  >>>
>  >>> for i in listmembers:  print i
>
>  me@here.net
>  you@there.org
>  Me@here2.com
>  everybody@earth.edu
>  nobody@domainerror.cc
>
>When you iterate over a list, you get its elements,
>whereas when you iterate over a string, you get each
>character, which is what was happening when you went
>the triple-quotes route.
>
>Kirby
>
>
>


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From highprimate@howlermonkey.net  Mon Dec 10 07:03:11 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Mon, 10 Dec 2001 2:3:11 -0500
Subject: [Tutor] defining functions
Message-ID: <200112100703.fBA73I328917@ns.howlermonkey.net>

Gang, in some languages you MUST define somethign before usign it, in others no, as long as it is defined 
SOMEPLACE, the language will find it and be cognisant of it (perl for instance). Must I list all definitions 
ABOVE the code using them in python, or can I bury them in the bottom? And do I have to take precautions to 
ensure the program does not execute them as it corses through the file? For instance, in BASIC, I must ensure 
the thing exits before it arrives at lines defining subroutines ( ancestral opbjects). If it falls through the 
end of the program to these definitions, it trys to execute them- then arrives at a return and BARFS IT'S 
COOKIES beause there was no matching gosub. In PASCAL one must define anything and everything before using it- 
a true BONDAGE AND DISIPLINE language If I ever avoided one. Gimmee a clue or two on these issues, would you?


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From highprimate@howlermonkey.net  Mon Dec 10 07:14:07 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Mon, 10 Dec 2001 2:14:7 -0500
Subject: [Tutor] defining functions
Message-ID: <200112100714.fBA7EF329042@ns.howlermonkey.net>

At 12/9/01 11:07:00 PM, you wrote:
>$ python /tmp/foo.py 
>Traceback (most recent call last):
>  File "/tmp/foo.py", line 1, in ?
>    foo()
>NameError: name 'foo' is not defined
>$ cat /tmp/foo.py 
>foo()
>
>def foo():
>        print "foo"
>
>looks like you have to define it before you use it (-:  That wasn't too hard.
>
>
That's was in interactive mode, where the thing CANNOT scan a file before begin executing it.

Of course in that mode it has to be defined first. this is not the sense of my question.

When python loads the script, it looks things over. When it detect certain glaring problems, it refuses to 
execute, and growls at me about the broblem.

OK, I will simply write a script and define something simple and workable, and referr to it before defining it 
and see what happens.


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From highprimate@howlermonkey.net  Mon Dec 10 07:37:28 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Mon, 10 Dec 2001 2:37:28 -0500
Subject: [Tutor] defining functions
Message-ID: <200112100737.fBA7bb329179@ns.howlermonkey.net>

Ah, I see that now. Dumb of me. Must be getting late, 

Looking, I see the big light over in the big room is out quite a while now. Maybe I should execute a refresh 
cycle and return to this later. Clock says it is 2:36 AM. Goodnight all.

At 12/9/01 11:22:00 PM, you wrote:
>
>On 10-Dec-2001 Kirk Bailey wrote:
>> At 12/9/01 11:07:00 PM, you wrote:
>>>$ python /tmp/foo.py 
>>>Traceback (most recent call last):
>>>  File "/tmp/foo.py", line 1, in ?
>>>    foo()
>>>NameError: name 'foo' is not defined
>>>$ cat /tmp/foo.py 
>>>foo()
>>>
>>>def foo():
>>>        print "foo"
>>>
>>>looks like you have to define it before you use it (-:  That wasn't too hard.
>>>
>>>
>> That's was in interactive mode, where the thing CANNOT scan a file before
>> begin executing it.
>> 
>
>
>um, no, that was "run this script I just gave you" mode.  I told python to run
>the script foo.py.  The '$' is my system prompt.
>
>


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From kalle@gnupung.net  Mon Dec 10 07:50:15 2001
From: kalle@gnupung.net (Kalle Svensson)
Date: Mon, 10 Dec 2001 08:50:15 +0100
Subject: [Tutor] defining functions
In-Reply-To: <200112100703.fBA73I328917@ns.howlermonkey.net>
References: <200112100703.fBA73I328917@ns.howlermonkey.net>
Message-ID: <20011210085015.A17039@proton.lysator.liu.se>

[Kirk Bailey]
> Gang, in some languages you MUST define somethign before usign it, in others
> no, as long as it is defined SOMEPLACE, the language will find it and be
> cognisant of it (perl for instance). Must I list all definitions ABOVE the
> code using them in python, or can I bury them in the bottom? And do I have
> to take precautions to ensure the program does not execute them as it corses
> through the file? For instance, in BASIC, I must ensure the thing exits
> before it arrives at lines defining subroutines ( ancestral opbjects). If it
> falls through the end of the program to these definitions, it trys to
> execute them- then arrives at a return and BARFS IT'S COOKIES beause there
> was no matching gosub. In PASCAL one must define anything and everything
> before using it- a true BONDAGE AND DISIPLINE language If I ever avoided
> one. Gimmee a clue or two on these issues, would you?

In python, things must be defined before they are used.
For example:

>>> i
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'i' is not defined
>>> i = 1
>>> i
1

This doesn't necessarily mean that the definition must come earlier in the
source file than use, just in the control flow:

def f():
    print foo
foo = 1
f()

is perfectly valid.

def f():
    print foo
f()
foo = 1

is not.

Peace,
  Kalle
-- 
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]


From scarblac@pino.selwerd.nl  Mon Dec 10 08:39:28 2001
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Mon, 10 Dec 2001 09:39:28 +0100
Subject: [Tutor] defining functions
In-Reply-To: <200112100703.fBA73I328917@ns.howlermonkey.net>; from highprimate@howlermonkey.net on Mon, Dec 10, 2001 at 02:03:11AM -0500
References: <200112100703.fBA73I328917@ns.howlermonkey.net>
Message-ID: <20011210093928.A6667@pino.selwerd.nl>

On  0, Kirk Bailey <highprimate@howlermonkey.net> wrote:
> Gimmee a clue or two on these issues, would you?

A Python 'def' statement is a statement like any other: functions aren't
declared at compile time, but during runtime!


Something like

x = 3
def y(): return 3

Has two different statements that aren't fundamentally different.
First the name 'x' is introduced to refer to 3, then the name 'y' refers to
a new function that returns 3. Both happen at runtime.

So function definitions must be run before they are used, but it doesn't
matter where in the file you place them (as long as they are run at the
right moment).

So

def a():
   return b()
   
def b():
   return 5
   
a()

is ok, since at the moment a() is called, b() was already defined.

However, this is not ok:

def a():
   return b()
   
a()

def b():
   return 5
   
Since now the function a is called before b was defined, so there is no
function b yet.

Hope this clears it up a little. Functions definitions happen at runtime
just like everything else.

-- 
Remco Gerlich


From alan.gauld@bt.com  Mon Dec 10 11:17:05 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 10 Dec 2001 11:17:05 -0000
Subject: [Tutor] OO terms and definitions
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C187@mbtlipnt02.btlabs.bt.co.uk>

> I am a little(or is that a lot) confused about some OO terminology.

Thats OK
OO terminology is beginning to settle down but for a long time there 
have been numerous different terms for the same concept and subtle 
differences in usage of these terms too. It is confusing even to 
experts!

> I have some quite a bit on the web and I have seen all sorts 
> of definitions for the following terms:

> Module

A Module in the pure sense is any kind of reusable software component.
It could be a function, a procedure, a class, a file, or a library.
Anything that is atomic and can be reused can be called a module.

In Python a module has the more precise meaning of a file.
The file can contain constant/variable definitions, clsass definitions 
and function definitions. It can even contain executable code
(ie executed when the module is loaded)

>     Class

Geneally refers to a description, in code, of some object type.

>        Function?

Technically a function is a (possibly parametereised) executable block 
of code which returns a value. A procedure looks a lot like a function 
but does not return a value. Functions and procedures exist outside of 
classes (usually!).

In python procedures are just functions that return None by implication.
They are executable blocks of code existing outside a class but may, 
or may not, be inside a module.

>        Method?

A method is technically the code block executed on receipt of a given 
message by an object. It usually looks a lot like a function definition 
but is always defined within a class. In python it has a first parameter 
representing the current instance, named by convention 'self'.


>        Procedure?

A function that does not return a value(see function above).

> It seems to me that there is a hierarchy to some degree

Only to a degree, and the extent of that depends on the programming 
language. Languages like Lisp/Scheme change the picture significantly 
compared to Python.

> Does a Module always have a Class? 

No, it may not even have functions!

> How do Function, Method and Procedure differ? 

See above but Functions/Procedures exist outsife classes. Methods 
are functions insiode classes that are activated by the owning 
object receiving a "message". In Python a message looks a lot like 
a function call...

HTH, For more on this look at my web tutor under 
"modules & functions" and the OO topic.

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


From alan.gauld@bt.com  Mon Dec 10 11:24:55 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 10 Dec 2001 11:24:55 -0000
Subject: [Tutor] OO terms and definitions
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C188@mbtlipnt02.btlabs.bt.co.uk>

> Pragmatically they are the same.

Umm no, there are significant differences. We get regular cries 
for help from beginners who have defined a function when they 
meant to define a method! (ie they missed out self...)

> The Java community likes to call them "methods".  The C/C++ community
> calls them functions (whether they are in a class or not).  

They shouldn''t - its supposed to be "member functions" when 
in a class and plain "functions" when outside.
ie "member function" == "method"

> community calls the ones that modify state but don't return a value
> "procedures" 

As does the Algol, ADA, Pascal and VB communities(actually VB 
uses SUBroutine for procedure) Procedure is a commonly used term 
for a subroutine that does not return a value.

> You can pretty much use the terms interchangeably, except when you get
> into the semantic details of "function" vs. "unbound method" vs.
> "bound method".

But only if you want to perpetuate the confusion that caused 
the poster to ask the question! Its much better for everyone
if we all use the terms correctly IMO!

Alan g.


From alan.gauld@bt.com  Mon Dec 10 11:30:52 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 10 Dec 2001 11:30:52 -0000
Subject: [Tutor] compiled Python Files ?? and a little OO
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C189@mbtlipnt02.btlabs.bt.co.uk>

Others have answered most of your questions but this one 
seemed to get missed:

> After I ran this, I noticed that I had two new versions of F1 
> and F2; the directory showed "Compiled Python file" as 
> ...
> extensions. Why didn't I see this happening with my other 
> tests? Is it because the other tests imported Tkinter?

My guess is you used Tkinter like:

from Tkinter import *

Thus you never imported Tkinter itself, you imported specific items
(everything in this cae!) from within it. Thus python didn't compile 
Tkinter. If you had done this:

import Tkinter

top = Tkinter.Tk()  #etc...

Then you would have gotten a Tkinter.pyc

Alan G.


From alan.gauld@bt.com  Mon Dec 10 11:40:30 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 10 Dec 2001 11:40:30 -0000
Subject: [Tutor] Is there a heaven for old instances ?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C18A@mbtlipnt02.btlabs.bt.co.uk>

>     Now if I create and instance, let's say this way:
>         instance1=Button(somewhere, lots of options or none)
>     and then for some (stupid?) reason I go:
>         instance1=Button(somewhere_else_or_not, new options_maybe)
>     what happens to the first instance which is much more 

First its not any more complex from Python's point of view 
- its just a reference to an object.

BUT because you are presumably referring to Tkinter buttons here you will 
when you created themn have passed a parent object as the first parameter. 
That Parent keeps a reference to its children, thus although you lost your 
reference(instance1) the parent keeps its and the object is not destroyed 
until the parent is...

If you still have a reference to the parent you can access the children 
from there - but its a bit messy. You can go the other way to because 
the widget keeps a reference to its parent too.

Try creating a Frame, sticking some child widgets in it and then doing 
a dir() on the Frame and accessing some of the inyteresting properties...

Alan G.


From alan.gauld@bt.com  Mon Dec 10 11:49:38 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 10 Dec 2001 11:49:38 -0000
Subject: [Tutor] string formatting and right justifying text
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C18B@mbtlipnt02.btlabs.bt.co.uk>

> string formatting codes to right-justify integers or floating 

%<width>.<precision><code>

Thus:

>>> print "Tot: %12.3f" % 123.45678
Tot:      123.457
>>> print "Tot: %15.2f" % 123.45678
Tot:         123.46

A negative sign left justifies:

>>> print "Tot: %-15.2f dollars" % 123.45678
Tot: 123.46         dollars

Is that what you wanted?

Alan g.


From alan.gauld@bt.com  Mon Dec 10 11:58:23 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 10 Dec 2001 11:58:23 -0000
Subject: [Tutor] defining functions
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C18C@mbtlipnt02.btlabs.bt.co.uk>

> Gang, in some languages you MUST define somethign before 
> using it, in others no, as long as it is defined 

In Python you can reference it before its defined but you cant execute it.

Thus:

def func1():
   print "func2 says: %d" % func2()  # refer to func 2 before defining

# func1()  # ERROR cause func2 now gets called before being defined!

def func2(): return 42

func1()  # Now OK cause func2 exists.

Does that help?

Alan G.
> In PASCAL one must define anything and everything before using it

Good practice and the reason why, once you get a Pascal program 
to compile it usually runs pretty much as you expect!

And that, after all, was the whole purpose of Pascal 
- to teach good programming practice!

Alan g.


From dsh8290@rit.edu  Mon Dec 10 14:56:35 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 10 Dec 2001 09:56:35 -0500
Subject: [Tutor] OO terms and definitions
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C188@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Mon, Dec 10, 2001 at 11:24:55AM +0000
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C188@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20011210095635.A15632@harmony.cs.rit.edu>

On Mon, Dec 10, 2001 at 11:24:55AM +0000, alan.gauld@bt.com wrote:
| > Pragmatically they are the same.
| 
| Umm no, there are significant differences. We get regular cries 
| for help from beginners who have defined a function when they 
| meant to define a method! (ie they missed out self...)

See my last paragraph from before,

        except when you get into the semantic details of "function"
        vs. "unbound method" vs. "bound method".

That is a situation where the semantics of how you define it (in code)
become significant.

| > The Java community likes to call them "methods".  The C/C++ community
| > calls them functions (whether they are in a class or not).  
| 
| They shouldn''t - its supposed to be "member functions" when 

Oops, yeah, I forgot the "member".

| > community calls the ones that modify state but don't return a value
| > "procedures" 
| 
| As does the Algol, ADA, Pascal and VB communities(actually VB 
| uses SUBroutine for procedure) Procedure is a commonly used term 
| for a subroutine that does not return a value.
| 
| > You can pretty much use the terms interchangeably, except when you get
| > into the semantic details of "function" vs. "unbound method" vs.
| > "bound method".
| 
| But only if you want to perpetuate the confusion that caused 
| the poster to ask the question! Its much better for everyone
| if we all use the terms correctly IMO!

Well, what is "correctly"?  I gave 4 examples of correct, but
different usages (or non-usages) of the terms, and each is considered
correct by their respective community.  It becomes even more difficult
when you frequently work with 2 or more languages.  People are
creatures of habit.  If I spend most of my time in python calling the
things "functions", then when I do some java I'll likely call it a
function there, and vice-versa.

If everyone could agree on a single set of correct terms then it would
be easier to prevent the confusion.  In addition, the terms should not
have such slight semantic differences because that makes the
terminology just as confusing as some code.  If you take the Eiffel
approach to the terms, what term do you give to a procedure that
returns a value?  The compiler doesn't prohibit it, you know.

-D

-- 

Q: What is the difference betwee open-source and commercial software?
A: If you have a problem with commercial software you can call a phone
   number and they will tell you it might be solved in a future version.
   For open-source sofware there isn't a phone number to call, but you
   get the solution within a day.



From alan.gauld@bt.com  Mon Dec 10 17:24:27 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 10 Dec 2001 17:24:27 -0000
Subject: [Tutor] OO terms and definitions
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C190@mbtlipnt02.btlabs.bt.co.uk>

> See my last paragraph from before,
> That is a situation where the semantics of how you define it (in code)
> become significant.

Yes that's what I meant.

> | > The Java community likes to call them "methods".  
> The C/C++ community calls them functions 

> Well, what is "correctly"?  I gave 4 examples of correct, but
> different usages (or non-usages) of the terms, and each is considered
> correct by their respective community.  

If used correctly the terms are consistent. A method is a commonly 
understood term throughout all OO communities. The fact that the C++ 
community happen to have a specific term (member function) to define 
how they implement methods is neither here nor there. What is 
definitely wrong and should be avoided is calling methods functions. 
They are fundamentally different concepts.

[ In passing, it is also important to distinguish methods from 
messages, since in some languages the method has a different 
name to the message. ]

> when you frequently work with 2 or more languages. 

It can be slightly more confusing I agree but as I said in a 
previous post it is becoming much more consistent. Method is 
now a pretty standard term as is class. Function and 
procedure have been standard in CS terms for years.

> things "functions", then when I do some java 

Functions in Python are different from methods. If you use the 
distinction consistently you avoid confusion not cause it.
Methods are "bound functions". Functions are "unbound functions"!
There is a difference and whichever term we use they remain 
different.

> If everyone could agree on a single set of correct terms 

They pretty much have done, bar some minor semantic issues.

> .....  If you take the Eiffel
> approach to the terms, what term do you give to a procedure that
> returns a value?  

A function.
A procedure by definition does not return a value. 
Thus if we all stick to the accepted correct definitions 
then the ambiguity is removed.

In fact checking my copy of OOSC by Meyer, Eiffel itself has 
no keyword distinction beteen function and procedure, they 
are just features. Meyer himself clearly makes the distinction 
in the book on the basis of whether they return a value(function) 
or not(procedure). When he is talking about the general 
concept (ie beyond classes) he uses the term "routine". 
Meyer is always very precise in his terminology in my experience.

> The compiler doesn't prohibit it, you know.
The compiler just sees a "feature".
Semantically the difference exists and is clear.

Alan g.


From jeff@ccvcorp.com  Mon Dec 10 18:30:11 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 10 Dec 2001 10:30:11 -0800
Subject: [Tutor] OO terms and definitions
References: <E16DTnj-0005yh-00@mail.python.org>
Message-ID: <3C14FF33.CAAF85A7@ccvcorp.com>

> On Mon, 10 Dec 2001 09:56:35 -0500,
> dman <dsh8290@rit.edu> wrote:
>
> On Mon, Dec 10, 2001 at 11:24:55AM +0000, alan.gauld@bt.com wrote:
>
> | > You can pretty much use the terms interchangeably, except when you get
> | > into the semantic details of "function" vs. "unbound method" vs.
> | > "bound method".
> |
> | But only if you want to perpetuate the confusion that caused
> | the poster to ask the question! Its much better for everyone
> | if we all use the terms correctly IMO!
>
> Well, what is "correctly"?  I gave 4 examples of correct, but
> different usages (or non-usages) of the terms, and each is considered
> correct by their respective community.  It becomes even more difficult
> when you frequently work with 2 or more languages.  People are
> creatures of habit.  If I spend most of my time in python calling the
> things "functions", then when I do some java I'll likely call it a
> function there, and vice-versa.

As I understand it, Java doesn't allow anything outside of class definitions,
and therefore requires everything to be a method.

It seems that a fairly standard usage (from my limited experience), is that
methods belong to classes, functions don't.  I've seen this usage in Python,
BASIC, C++ (though often "member function" replaces method, as noted), and the
few bits about Smalltalk that I've read.  The distinction between functions
and procedures (or subroutines) doesn't exist in some languages, but where it
does, it depends on the return value--functions return a value, procedures
don't.


> If everyone could agree on a single set of correct terms then it would
> be easier to prevent the confusion.  In addition, the terms should not
> have such slight semantic differences because that makes the
> terminology just as confusing as some code.

No arguments on that!  :)

Jeff Shannon
Technician/Programmer
Credit International




From Bruce.Lee-Shanok@cognos.com  Mon Dec 10 18:46:49 2001
From: Bruce.Lee-Shanok@cognos.com (Lee-Shanok, Bruce)
Date: Mon, 10 Dec 2001 13:46:49 -0500
Subject: [Tutor] Application Error after end of program
Message-ID: <FB15E670DA55D51185350008C786514A0140EB44@sottexch1.cognos.com>

Hello all,

	I'm currently running Python (ActiveState 2.1.1, build 212), on
Windows 2000. Now, I've written a program that used to run fine from
beginning to end, and I recently started making use of the random and =
thread
libraries... associated with this is an unusual error. Unusual in the =
sense
that it occurs sometime after the very last line of code (a print
statement).=20

Otherwise it's your generic sort of "The instruction at "<some hex =
address>"
referenced memory at "<some hex address>" the memory could not be =
written.

Going into more detail with a debug gives me the fact that it's an
"Unhandled exception in python (NTDLL.DLL): 0xC0000005: Access =
Violation.
and a bunch of assembly I couldn't read to save my live.

Anyone have any ideas as to what might be causing this or where I =
should be
looking? I'm at a complete loss. I even reduced the number of threads =
to 1
in case there was some funny business going on with multiple writes, =
but
nothing of the sort is possible now.

Bruce Lee-Shanok
Access Manager
(613) 738-1338 ext 5764
Cognos, Ottawa=20
[Riverside, 4th Floor, E9]

Ce message peut contenir des informations prot=E9g=E9es et/ou =
confidentielles.
Si vous avez re=E7u ce mail par erreur ou si vous n'en =EAtes pas le
destinataire, il vous est interdit d'utiliser, de copier, de diffuser =
ou de
distribuer les pi=E8ces qui y sont jointes. Supprimez-le et notifiez
imm=E9diatement par e-mail la personne qui vous l'a envoy=E9e. Merci =
d'avance.


This message may contain privileged and/or confidential information.  =
If you
have received this e-mail in error or are not the intended recipient, =
you
may not use, copy, disseminate, or distribute it; do not open any
attachments, delete it immediately from your system and notify the =
sender by
e-mail promptly that you have done so.  Thank You.


From dyoo@hkn.eecs.berkeley.edu  Mon Dec 10 19:10:30 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 10 Dec 2001 11:10:30 -0800 (PST)
Subject: [Tutor] defining functions  [if __name__ == '__main__']
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C18C@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.21.0112101053240.31869-100000@hkn.eecs.berkeley.edu>

On Mon, 10 Dec 2001 alan.gauld@bt.com wrote:

> > Gang, in some languages you MUST define somethign before 
> > using it, in others no, as long as it is defined 

Here's an example that shows how to get it so you can call functions in
the order you want:

###
## testmain1.py
def main():
    sayFirstVerse()
    print "For the rain, it raineth every day"

def sayFirstVerse():
    print "Hey, ho, the wind and the rain"

main()
###


There are two important parts to this:

    1.  Put our main part of our program in a separate function.  Because
it's a function, it's somewhat inactive.  We're only telling Python what
it looks like, but also asking to hold off calling it until we ask for it.

    2.  Put a statement at the very bottom of our program that calls that
main() function, which gets things started.


This trick should help avoid the kind of ordering problems that you might
have with your program.


[Side note below.]

By the way, there's a variation of this that Python programmers can use
when they're writing modules.  It looks like this:

###
## testmain2.py
def main():
    sayFirstVerse()
    print "For the rain, it raineth every day"

def sayFirstVerse():
    print "Hey, ho, the wind and the rain"

if __name__ == '__main__':          ## Here's the important part.
    main()
###

The difference between this and the above example is that, in this case,
main() will not get called if we 'import' testmain2 as a module.  If we
run testmain2.py directly:

###
[dyoo@tesuque dyoo]$ python testmain2.py 
Hey, ho, the wind and the rain
For the rain, it raineth every day
###

But, if we're already in Python, we can 'import' testmain2 and use it as
if it were a toolbox of stuff:

###
>>> import testmain2
>>> dir(testmain2)
['__builtins__', '__doc__', '__file__', '__name__', 'main',
'sayFirstVerse']
>>> testmain2.sayFirstVerse()
Hey, ho, the wind and the rain
###

If we had tried this import with testmain1.py, the main() function would
fire off immediately:

###
>>> import testmain1
Hey, ho, the wind and the rain
For the rain, it raineth every day
###


Good luck to you!



From shalehperry@attbi.com  Mon Dec 10 07:22:14 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun, 09 Dec 2001 23:22:14 -0800 (PST)
Subject: [Tutor] defining functions
In-Reply-To: <200112100714.fBA7EF329042@ns.howlermonkey.net>
Message-ID: <XFMail.20011209232214.shalehperry@attbi.com>

On 10-Dec-2001 Kirk Bailey wrote:
> At 12/9/01 11:07:00 PM, you wrote:
>>$ python /tmp/foo.py 
>>Traceback (most recent call last):
>>  File "/tmp/foo.py", line 1, in ?
>>    foo()
>>NameError: name 'foo' is not defined
>>$ cat /tmp/foo.py 
>>foo()
>>
>>def foo():
>>        print "foo"
>>
>>looks like you have to define it before you use it (-:  That wasn't too hard.
>>
>>
> That's was in interactive mode, where the thing CANNOT scan a file before
> begin executing it.
> 


um, no, that was "run this script I just gave you" mode.  I told python to run
the script foo.py.  The '$' is my system prompt.


From shalehperry@attbi.com  Mon Dec 10 07:07:00 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun, 09 Dec 2001 23:07:00 -0800 (PST)
Subject: [Tutor] defining functions
In-Reply-To: <200112100703.fBA73I328917@ns.howlermonkey.net>
Message-ID: <XFMail.20011209230700.shalehperry@attbi.com>

$ python /tmp/foo.py 
Traceback (most recent call last):
  File "/tmp/foo.py", line 1, in ?
    foo()
NameError: name 'foo' is not defined
$ cat /tmp/foo.py 
foo()

def foo():
        print "foo"

looks like you have to define it before you use it (-:  That wasn't too hard.


From dyoo@hkn.eecs.berkeley.edu  Mon Dec 10 19:34:45 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 10 Dec 2001 11:34:45 -0800 (PST)
Subject: [Tutor] compiled Python Files ?? [print / .pyc and import] (fwd)
Message-ID: <Pine.LNX.4.21.0112101133541.31869-100000@hkn.eecs.berkeley.edu>

Hi Frank,

Let me send your respond to the list, so that the others there can respond
as well.  Talk to you later!

---------- Forwarded message ----------
Date: Mon, 10 Dec 2001 09:39:43 -0800
From: Frank Peavy <fpeavy@pop.net>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] compiled Python Files ?? [print / .pyc and import]


> > I have one more FX.py file that contains:
> >
> > import F1.py
> > import F2.py
>
>Hmmm... did this work?  Your FX.py file might need:
>
>###
>import F1
>import F2
>###

Yes, you were correct, my FX.py file contains only:
import F1
import F2

 >However, perhaps we don't want 'print' to skip lines.  If we put a
>trailing comma on a print statement, 'print' will put a space instead:

Thanks for the "heads up" on this one. Always nice to get additional 
information.

>It's because your FX.py program imported the other two 'modules' --- doing
>an import has this effect.  Let's talk about this below.

So, if I understand you correctly. If I have one file that imports other 
"modules", the modules get compiled but the calling file doesn't. This 
seems a little strange to me, but that is how it is, that is how it is.

Perhaps this is where all the OO stuff comes into play, eh?
In my opinion, it implies that most applications should be written in 
"modules" and imported by a single, short .py file. Is this correct?  It 
would seem to me that that would give you imported compiled modules that 
execute the quickest.

> > I understand I can run the .pyc files, instead of the .py files. Is
> > this true?
>
>Yes, it's true.  However, I wouldn't recommend deleting the .py files,
>sine the .pyc files are very unreadable.  *grin*
If I run my F1.pyc file with the following command:

python F1.pyc

I get:

hello
run_pyc_file: nested_scopes: 0

What does this mean? If running a .py is the same as running a .pyc, then 
shouldn't I get the same results?

> > Why didn't I get a FX.pyc file also... ? The first two files compiled but
> > the third file that imported the other two didn't.
>
>Ah!  But if we had a third program that did something like:
>
>###
>import FX
>###
>
>Python will make an FX.pyc file for us.

So, as my comments above about OO, there should be a single small file that 
calls all the other modules, correct?




From dsh8290@rit.edu  Mon Dec 10 19:38:53 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 10 Dec 2001 14:38:53 -0500
Subject: [Tutor] Application Error after end of program
In-Reply-To: <FB15E670DA55D51185350008C786514A0140EB44@sottexch1.cognos.com>; from Bruce.Lee-Shanok@cognos.com on Mon, Dec 10, 2001 at 01:46:49PM -0500
References: <FB15E670DA55D51185350008C786514A0140EB44@sottexch1.cognos.com>
Message-ID: <20011210143850.B17537@harmony.cs.rit.edu>

On Mon, Dec 10, 2001 at 01:46:49PM -0500, Lee-Shanok, Bruce wrote:
| Hello all,
| 
| 	I'm currently running Python (ActiveState 2.1.1, build 212), on
| Windows 2000. Now, I've written a program that used to run fine from
| beginning to end, and I recently started making use of the random and thread
| libraries... associated with this is an unusual error. Unusual in the sense
| that it occurs sometime after the very last line of code (a print
| statement). 

Once you make a (new) thread, it is as if you have two programs
running at the same time, but they share the same address space.  If
the "main" thread terminates (after that "last print" you mention) but
you have another non-daemon thread running, it keeps running.  The
program isn't over yet.

| Otherwise it's your generic sort of "The instruction at "<some hex address>"
| referenced memory at "<some hex address>" the memory could not be written.
| 
| Going into more detail with a debug gives me the fact that it's an
| "Unhandled exception in python (NTDLL.DLL): 0xC0000005: Access Violation.
| and a bunch of assembly I couldn't read to save my live.

Heh, NTDLL.DLL?  Sounds to me like a (buggy!) system library.  On a
non-buggy system (or at least, less so) errors only happen in
applications, not in the system itself.  I don't know what's going on,
but I expect it is thread related.

Can you get a core file in windows?  If so you can look at the
backtrace to see where (in the C/C++ part of the system) the error
occurred.  Ideally you can work backwards from there to the portion(s)
of your code that might initiate those operations, then use the
"print" technique to debug it.

-D

-- 

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



From Bruce.Lee-Shanok@cognos.com  Mon Dec 10 20:13:14 2001
From: Bruce.Lee-Shanok@cognos.com (Lee-Shanok, Bruce)
Date: Mon, 10 Dec 2001 15:13:14 -0500
Subject: [Tutor] Application Error after end of program
Message-ID: <FB15E670DA55D51185350008C786514A0140EB4B@sottexch1.cognos.com>

>Once you make a (new) thread, it is as if you have two programs
>running at the same time, but they share the same address space.  If
>the "main" thread terminates (after that "last print" you mention) but
>you have another non-daemon thread running, it keeps running.  The
>program isn't over yet.

I thought that might be it, but from the looks of it, I've pasted a print
statement
at the end of every run() method in my Thread object, which I understand is
the very
last command.. although I suppose the thread could switch over immediately
after the
pause, but I do a join for each thread from the main thread.

I've tried it with a single thread and join and it still occurs. :)

>Heh, NTDLL.DLL?  Sounds to me like a (buggy!) system library.  On a
>non-buggy system (or at least, less so) errors only happen in
>applications, not in the system itself.  I don't know what's going on,
>but I expect it is thread related.

  I've no idea how to get a core file. :) But yeah.. one of my hopes
was that Python might do some necessary cleaning up and that I was 
somehow mucking that up.. but my calls are pretty straightforward, it's
a simple:

j = HopperThread()
j.start()
j.join()
print "Are we done?"

... and it's still mucking up. :)

I'm probably going to end up randomly commenting sections of code in some
trial
and error setup anyway, but I thought I'd see if anyone could explain the
magic
bullet (read: where I'm royally messing things up) before I reduce my code
to a 
single nonfunctioning print statement. :)

Thanks for the idea though.. if I can ever find out "where" the program
screws up
(where "where" is some line number < lines of code :) ).. I'll whittle my
way through..

Cheers,
Bruce

This message may contain privileged and/or confidential information.  If you
have received this e-mail in error or are not the intended recipient, you
may not use, copy, disseminate, or distribute it; do not open any
attachments, delete it immediately from your system and notify the sender by
e-mail promptly that you have done so.  Thank You.


From dyoo@hkn.eecs.berkeley.edu  Mon Dec 10 23:21:30 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 10 Dec 2001 15:21:30 -0800 (PST)
Subject: [Tutor] Application Error after end of program
In-Reply-To: <FB15E670DA55D51185350008C786514A0140EB4B@sottexch1.cognos.com>
Message-ID: <Pine.LNX.4.21.0112101517470.9873-100000@hkn.eecs.berkeley.edu>

On Mon, 10 Dec 2001, Lee-Shanok, Bruce wrote:

> >Once you make a (new) thread, it is as if you have two programs
> >running at the same time, but they share the same address space.  If
> >the "main" thread terminates (after that "last print" you mention) but
> >you have another non-daemon thread running, it keeps running.  The
> >program isn't over yet.
> 
> I thought that might be it, but from the looks of it, I've pasted a
> print statement at the end of every run() method in my Thread object,
> which I understand is the very last command.. although I suppose the
> thread could switch over immediately after the pause, but I do a join
> for each thread from the main thread.

This might be something you want to post on the main comp.lang.python
newsgroup as well as Tutor.  These kind of errors should not happen in
Python, so perhaps someone on comp.lang.python might be able to point out
a service pack fix in NT that corrects this.


> >Heh, NTDLL.DLL?  Sounds to me like a (buggy!) system library.  On a
> >non-buggy system (or at least, less so) errors only happen in
> >applications, not in the system itself.  I don't know what's going on,
> >but I expect it is thread related.

Agreed; I don't think this has to do with your program, but with some
system library of the operating system.

Good luck to you.



From e.kotyk@shaw.ca  Tue Dec 11 14:07:08 2001
From: e.kotyk@shaw.ca (Eve Kotyk)
Date: Tue, 11 Dec 2001 14:07:08 +0000
Subject: [Tutor] Lists within lists return
Message-ID: <3C16130C.D51B77C5@shaw.ca>

I'm working through the Josh Cogliati tutorial on the Python site.  In
the secton on lists, example 8.3, test.py is given along with a sample
output.  I've typed up the program using Idle but I do not get the
expected output.  In fact I get no output at all and I don't get any
error messages.  Below see the example code as cut and pasted from my
file.  I would appreciate any help you might be able to give me.

##This program is called test.py
# This program runs a test of knowledge

true = 1
false = 0

#First get the test questions
#Later this will be modified to use file io.
def get_questions():
    #notice how the data is stored as a list of lists 
    return [["What color is the daytime sky on a clear day? ","blue"],\
    	["What is the answer to life, the universe and everything? ",
"42"]\
    	["What is a three letter word for mouse trap? ","cat"]]
    
    	
#This will test a single question
#it takes a single questin in
#it returns true if the user typed the correct answer, otherwise false
def check_question(question_and_answer):
    #extract the question and the answer from the list
    question = question_and_answer[0]
    answer = question_and_answer[1]
    #give the question to the user
    given_answer = raw_input(question)
    #compare the user's answer to the testers answer
    if answer == given_answer:
        print "Correct"
        return true
    else:
        print "Incorrect, correct was: ", answer
        return false
    
    #This will run through all the questions
    def run_test(questions):
        if len(questions) == 0:
            print "No questions were given."
            #the return exits the function
            return
        index = 0
        right = 0
        while index < len(questions):
            #Check the question
            if check_question(questions[index]):
                right = right + 1
                #go to the next question
                index = index + 1
        #notice the order of the computation, first multiply, then
divide
        print "you got ",right*100/len(questions), "% right out of",\ 		
len(questions)
    #now lets run the questions
    run_test(get_questions())

-- 

ekotyk

http://members.shaw.ca/e.kotyk/virtualstudio.htm


From van@lindbergs.org  Tue Dec 11 01:12:42 2001
From: van@lindbergs.org (VanL)
Date: Mon, 10 Dec 2001 18:12:42 -0700
Subject: [Tutor] Popen help?
Message-ID: <3C155D8A.2000501@lindbergs.org>

Hello,

I'm trying to get the output of a script that prints to stdout.  The 
problem is, the script is on another server.

Can I use popen to ssh to another server, run a command, and get the output?

Or would telnetlib be better?  I just shy away from telnet because of 
security issues.

Thanks,

Van



From dyoo@hkn.eecs.berkeley.edu  Tue Dec 11 02:26:39 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 10 Dec 2001 18:26:39 -0800 (PST)
Subject: [Tutor] Lists within lists return
In-Reply-To: <3C16130C.D51B77C5@shaw.ca>
Message-ID: <Pine.LNX.4.21.0112101823560.16361-100000@hkn.eecs.berkeley.edu>

On Tue, 11 Dec 2001, Eve Kotyk wrote:

> I'm working through the Josh Cogliati tutorial on the Python site.  In
> the secton on lists, example 8.3, test.py is given along with a sample
> output.  I've typed up the program using Idle but I do not get the
> expected output.  In fact I get no output at all and I don't get any
> error messages.  Below see the example code as cut and pasted from my
> file.  I would appreciate any help you might be able to give me.

I think this is the culprit: the last half of your program, starting from
this line:

>     #This will run through all the questions
>     def run_test(questions):
>         if len(questions) == 0:
>             print "No questions were given."
>             #the return exits the function
>             return
>         index = 0
>         right = 0
>         while index < len(questions):
>             #Check the question
>             if check_question(questions[index]):
>                 right = right + 1
>                 #go to the next question
>                 index = index + 1
>         #notice the order of the computation, first multiply, then
> divide
>         print "you got ",right*100/len(questions), "% right out of",\ 		
> len(questions)
>     #now lets run the questions
>     run_test(get_questions())

is indented too far.  You probably want the definition of run_test() to be
outside check_question().

If you bring the indentation level down one level for these lines, you
should be ok.  Hope this helps!




From dyoo@hkn.eecs.berkeley.edu  Tue Dec 11 02:30:16 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 10 Dec 2001 18:30:16 -0800 (PST)
Subject: [Tutor] Popen help?
In-Reply-To: <3C155D8A.2000501@lindbergs.org>
Message-ID: <Pine.LNX.4.21.0112101827240.16361-100000@hkn.eecs.berkeley.edu>

On Mon, 10 Dec 2001, VanL wrote:

> I'm trying to get the output of a script that prints to stdout.  The 
> problem is, the script is on another server.
> 
> Can I use popen to ssh to another server, run a command, and get the
> output?

Yes, we can use popen() with ssh.


Many people don't realize that the 'ssh' command can be used like 'rsh',
so we can do something like this:

###
>>> import os
>>> my_bash_profile = os.popen('ssh aztec ls -l .bash_profile').read()
>>> my_bash_profile
'-rw-r--r--    1 dyoo     users         354 Aug 23 12:04 .bash_profile\n
###


Hope this helps!



From e.kotyk@shaw.ca  Tue Dec 11 14:38:16 2001
From: e.kotyk@shaw.ca (Eve Kotyk)
Date: Tue, 11 Dec 2001 14:38:16 +0000
Subject: [Tutor] Lists within lists return
References: <Pine.LNX.4.21.0112101823560.16361-100000@hkn.eecs.berkeley.edu>
Message-ID: <3C161A58.27234724@shaw.ca>

> >     #now lets run the questions
> >     run_test(get_questions())
> 
> is indented too far.  You probably want the definition of run_test() to be
> outside check_question().

Thanks Danny.  I thought this might be the case but when I do that I get
the following error:
 python test.py
Traceback (innermost last):
  File "test.py", line 50, in ?
    run_test(get_questions())
NameError: run_test       

And I cannot see where I have the name error.


-- 

ekotyk

http://members.shaw.ca/e.kotyk/virtualstudio.htm


From dyoo@hkn.eecs.berkeley.edu  Tue Dec 11 02:51:11 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 10 Dec 2001 18:51:11 -0800 (PST)
Subject: [Tutor] Lists within lists return
In-Reply-To: <3C161A58.27234724@shaw.ca>
Message-ID: <Pine.LNX.4.21.0112101846530.16361-100000@hkn.eecs.berkeley.edu>

On Tue, 11 Dec 2001, Eve Kotyk wrote:

> 
> > >     #now lets run the questions
> > >     run_test(get_questions())
> > 
> > is indented too far.  You probably want the definition of run_test() to be
> > outside check_question().
> 
> Thanks Danny.  I thought this might be the case but when I do that I get
> the following error:
>  python test.py
> Traceback (innermost last):
>   File "test.py", line 50, in ?
>     run_test(get_questions())
> NameError: run_test       

Without seeing your changes, I'll have to make a wildly inaccurate guess.  
Did you do this to just the last line?  You also need to move the whole
run_test() definition "outside" of check_question().

I don't like wildly guessing though, since its often very ineffective.  
Instead, can you show us what your program looks like, now that you've
applied your changes?




From wilson@visi.com  Tue Dec 11 03:35:06 2001
From: wilson@visi.com (Timothy Wilson)
Date: Mon, 10 Dec 2001 21:35:06 -0600 (CST)
Subject: [Tutor] retrieving stock quotes
Message-ID: <Pine.GSO.4.21.0112102133120.27812-100000@isis.visi.com>

Hi everyone,

Does anyone know of an ftp site or Web site that has fairly current stock
quotes in an easily parsable format? I'm working on a stock portfolio
tracker assignment for my students and I think some of them will want to
update prices automatically. They had fun with the weather assignment and
will want to try some more urllib2 tricks.

-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 e.kotyk@shaw.ca  Tue Dec 11 15:37:05 2001
From: e.kotyk@shaw.ca (Eve Kotyk)
Date: Tue, 11 Dec 2001 15:37:05 +0000
Subject: [Tutor] Lists within lists return
References: <Pine.LNX.4.21.0112101846530.16361-100000@hkn.eecs.berkeley.edu>
Message-ID: <3C162821.3891CF3D@shaw.ca>

 
> I don't like wildly guessing though, since its often very ineffective.
Agreed.


I resolved the problem:

There were two incorrect items:

1)  As you mentioned the function call run_test(get_questions()) was
indented too far.

2)  The other one was tricker.  It involved the 3 return lines in the
list in the first definition.  These lines needed to line up and mine
where originally not lined up.  See below:


# New version that works
# This program runs a test of knowledge

true = 1
false = 0

#First get the test questions
#Later this will be modified to use file io.
def get_questions():
    #notice how the data is stored as a list of lists 
    return [["What color is the daytime sky on a clear day? ","blue"],\
    	    ["What is the answer to life, the universe and everything? ",
"42"],\
    	    ["What is a three letter word for mouse trap? ","cat"]]


# Old version that doesn't work.
#this program runs a test of knowledge

true = 1
false = 0

#first get the test question
#later this will be modified to use file io
def get_questions():
    #notice how the data is stored in a list of lists
    return (["What colour is the daytime sky on a clear day? ","blue"]\
    	["What is the answer to life, the universe and everything?", "42"]\
    	["What is a three letter word for a mouse trap?", "cat"])
	    

Notice the square bracket of the above 3 lines do not line up.  This
seems like a weird thing.  I'm using Idle as my test editor and a line
break after the first statement dropped the next line down under
'return'.  One tab over wasn't far enough and two tabs over was too
far.  I finally settle for a combination of one tab and four spaces

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

-- 

ekotyk

http://members.shaw.ca/e.kotyk/virtualstudio.htm


From wilson@visi.com  Tue Dec 11 03:57:55 2001
From: wilson@visi.com (Timothy Wilson)
Date: Mon, 10 Dec 2001 21:57:55 -0600 (CST)
Subject: [Tutor] retrieving stock quotes
In-Reply-To: <Pine.GSO.4.21.0112102133120.27812-100000@isis.visi.com>
Message-ID: <Pine.GSO.4.21.0112102148190.28442-100000@isis.visi.com>

On Mon, 10 Dec 2001, Timothy Wilson wrote:

> Does anyone know of an ftp site or Web site that has fairly current stock
> quotes in an easily parsable format?

<lame self-reply>
Very cool! I happened upon exactly what I needed. Go to
http://finance.yahoo.com/ and enter a ticker symbol (RHAT, for
example). Notice the 'Download Spreadsheet' link below the quote
table? That's a link to a simple comma-separated list of values. Bingo!

Here's some sample code.

wilson@copland:~$ python2.1
Python 2.1.1 (#1, Nov 11 2001, 18:19:24)
[GCC 2.95.4 20011006 (Debian prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> import urllib2
>>> base = 'http://finance.yahoo.com/d/quotes.csv?s='
>>> tail = '&f=sl1d1t1c1ohgv&e=.csv'
>>> ticker = 'RHAT'
>>> url = base+ticker+tail
>>> url
'http://finance.yahoo.com/d/quotes.csv?s=RHAT&f=sl1d1t1c1ohgv&e=.csv'
>>> quote = urllib2.urlopen(url).read()
>>> quote
'"RHAT",7.76,"12/10/2001","3:59PM",-0.20,7.85,8,7.65,1520500\r\n'
>>>

Now you can slice and dice at will and pull out all sorts of good info. My
students will have fun with this.

</lame self-reply>

-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 deliberatus@my995internet.com  Tue Dec 11 07:03:01 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Tue, 11 Dec 2001 02:03:01 -0500
Subject: [Tutor] further ignorant babbling
Message-ID: <3C15AFA5.7AADE457@my995internet.com>

Well, I just don't know when to quit. Further progress in the script,
and a minor refinement in the sending of the messages, still sends each
one in it's own envlope, but this way it only opens the connection once,
and closes it once, saving a little time.

And it set's the X-Mail-Loop header to prevent mail loops. Not only with
the list traffic, but in the reject reply, so we don't get into a sort
of autoreply war- important concept, that.

-------------------begin cheezy programming--------------------------
#!/usr/local/bin/python
# Tinylist module, Pitchtime unit.
# this handles receiving and sending out postings to a list.

import sys, re, string, rfc822, smtplib

localhost = 'howlermonkey.net'	# make sure you set this to the domain
YOU use!!!

pathtostuff = '/www/www.howlermonkey.net/cgi-bin/'	#please edit this to
suit your system.
						# note this tells where to start looking.
						# everything is either here, ur under this
						# point in a systematic manner.
					
listname = sys.argv[1]			# we read a command line arguement to determine
the list name
						# Arguement 0 is the name of the script run, 1 is the
						# first arguement.
						# after that name in the command line, so if this were
						# program FOO,
						# that line would be "|/path/FOO listname"
						# and the arguement here would be 'listname'!
					
message = raw_input.lines()		# Variable 'message' is assigned the entire
message
						# which is piped to the program by the alias definition
						# such as:
						# foolist:"|/pathtoprogram/programname foolist"

						# now we must determine the sender and see if they are in
						# the subscriber file!
						# still got to learn more about how this thing handles
						# parsing the incoming message, but smtp and rfc822
						# are dep sorcery on this material.
from = message["From"]

open a.file(pathtostuff + "/lists/" + listname, 'r')						
members = a.readlines()
a.close()

if string.find(members, from):					# IF the sender is in the subscriber, 
		subject = '[' + listname + ']' + subject		# then acept the submission.
		Reply_to = listname + "@" + localhost		# this sets the reply-to field.
		X-Loop = "X-Loop: " + listname + "@" + localhost	# This breaks email
loops from form
		ftr = b.open(pathtostuff + "/lists/" + listname + ".footer",'r') #
read the footer
		footer = ftr.readlines()				# reads the footer into the variable
		ftr.close()							# close that file,
		message = message + footer				# and append it to the message. 
	else									# BUT IF THEY ARE NOT SUBSCRIBED...
		listnamemembers = from					# put their addres as the only recipient
		message = ""						# clear the mesage.
		From = "From: tinylist@" + localhost + \n 	# From:
tinylist@mydomain.foo !
		Subject = "Subject: Unauthorized posting to list" + listname + \n
		Reply_to = "Reply-to:postmaster@" + localhost + \n # no comments
possible now!
		X-Loop = "X-Loop: postmaster@" + localhost	# This breaks email loops
from forming
		message = """
		
		To whom it may concern;
		
		Sorry, but as you are not a current member of """ + listname + """, 
		you may not post to it. Your recent posting has been rejected and
destroyed.
		
		Feel free to contact the postmaster if there is any question.
		Any reply to this letter should go directly to the postmaster.
		
		You can also subscribe to this list if you like.
		
		Goodbye.
		
		"""
		
		# there cannot be comments in those line above this one,
		# or they would be part of the string!

# ok, if they are not a member, THEY GET THE REPLY SHOWN ABOVE MAILED TO
THEM!
# above is a blank line, DO NOT DELETE IT! *IMPORTANT!*
# there is no endif or fi in python. whitespace and tabulation therefore
# is rather important here.
#
# now we send whatever message is to go out to whatever is in the
recipient tupple.
#
helo()				# open a connection to the smtp server,
a.connect()				# and log in to the thing as the identity this script
runs as.
for i in listnamemembers :	# for each address in the list
listnamemembers,
	a.sendmail(from_addr, to_addr, Subject, reply-to, to, X-Loop, msg)
#send a envlope!
					#
a.quit()				# then close the connection.

	
					# make sure this script runs as a TRUSTED USER-
					# and NOT as root!!! Make sure that a
					# NON-priviliged user can run this script,
					# and make sure it is owned by that identity!
					
-----------------------end aged cheeze------------------------------

As for path and naming conventions, I am leaning to using a
"./lists/listname.filetype" approach, to reduce the creation of dir's.
formulating filenames is apparently pretty simple stuf in python, so
let's keep simple simple.




FORTH rant
For some reason, I keep thinking of FORTH. Only thing I ever saw that's
more easily extensible than python. EVERYTHING is an extension of forth!
There are no actual forth programs other than forth itself. There are
only new words in it's vocabulary.

Here is helloworld in forth:

:helloworld ."Hello world!" ;

If you type that in a computer running forth, it is now part of the
language, compiled as soon as it registered the CR from the keyboard. It
is now compiled into the dictionary. When you issue a command, it
interpets it, looking it up in the dictionary of runtime addresses.

Factoring is very important in forth, to get it's wonderful power of
compactness. programs in forth are on average only 1/2.5 the size of the
same thing in assembly.

No, I am not kidding.

Stack oriented, threaded, FORTH is writen top down, composed and
compiled bottom up, is a interpeting compiling language with Reverse
Polish Notation, is stack oriented, and includes all existant and not
yet existant assembly languages as subsets of the language, along with
the kitchen sink and BIG RED STRAPS.

Leo Brodie wrote that it is best for beginning programmers to learn
FORTH, as experienced ones tend to experience stress trauma from it's
odd and unique nature. It is usually used for controllers and other
imbedded computers, and also in many workstations, as it lets a minimum
of electronics be VERY smart, so a lot of unix workstations run small
cpu's nd a flavor of forth, making a tiny thing mildly smart, with a
minimum of silicon.
END OF RANT





-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Sat Dec  8 21:16:35 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sat, 08 Dec 2001 16:16:35 -0500
Subject: [Tutor] Guess what I found!
Message-ID: <3C128333.1360AE45@my995internet.com>

Lookee! A python mail list manager! Free for use! 

LOOK OUT FOR WORD WRAP PROBLEMS!!!

---------------------------start quote-----------------------------
#!/bin/python

# MailList is copyright (c) 2000 of Programmed Integration
# You may use this code in any way you see fit, but please
# let use know where it is being used. If you make any changes to
# the source code, please send us a copy so we can incorporate
# the changes in future releases. If you have any other comments
# please feel free to contact us at support@programmedintegration.com

# MailList version 1.0.0 22 August 2000

import sys
sys.path.append('/lib/python1.5')          # My ISP requires this to
correctly locate Python Modules

import cgi, re, string                     # Import all the required
modules

try:
   useHead=open("head.txt", "r")           # Open the HTML header file
   useFoot=open("foot.txt", "r")           # Open the HTML footer file

   ContentLine="Content-type: text/html"   # Standard content type for
HTML files

   useform=cgi.FieldStorage()              # Assign all variables on web
form to UseForm variable
   email= useform["email"].value           # Assign from form to local
variables. Proposed email address
   email2= useform["email2"].value         # ditto, verified email
address
   password= useform["password"].value     # ditto, proposed password
   password2= useform["password2"].value   # ditto, verified password
   action=useform["action"].value          # ditto, action, i.e
subscribe or unsubscribe      

   try:   
      optout=useform["optout"].value       # ditto, optout clause, yes
or no
   except:                                 # I've enclosed this in a
try/except
      optout='no'                          # as if the checkbox is
unchecked, nothing
                                           # was returned.  This way
'no' is returned

   print ContentLine                       # Print standard content line
   print                                   # Needs a blank line
following
   print useHead.read()                    # Print HTML header
   if email!=email2:                       # Checks to see if two
entered email addresses match
      print "Email addresses do not match" # If no match print error 
      sys.exit(0)                          # Exit script with error 0
   elif password!=password2:               # Checks to see if two
entered passwords match
      print "Passwords do not match"       # If no match print error
      sys.exit(0)                          # Exit script with error 0
   
   useMailList=open("maillist.txt", "r")   # Open mailling list
   memMailList=useMailList.readlines()     # Assign mailing list to
internal list
   useMailList.close                       # Close mailing list
   found=0                                 # Create found variable
   counter=0                               # Create counter variable
   for UseLine in memMailList:             # For loop until list end is
reached
      if string.find(string.upper(UseLine), string.upper(email))!=-1: #
Checks to see if email is in mailing list
         found=1                           # If yes, found = true (1)
         UseSplit=re.split(',',UseLine)    # Create list of found line
and delimit with a comma
         break                             # Exit for loop
      counter=counter+1                    # If not found incrememnt
count and repeat
   if not found:                           # If email address not found
in mailing list
      if action=="unsubscribe":            # And if action is
unsubscribe
         print "Email address <B>"+email+"</B> does not exist on our
database" # Print error message
      else:                                # Otherwise
         lineuse=email+","+password+','+optout+"\n" # Form valid mailing
list entry
         memMailList.append(lineuse)       # Add to internal list
         print "Subscription for <B>"+email+"</B> successful<P>" #Print
success to HTML
         print "Many thanks for subscribing.  Please be sure to make a
note"
         print "of the email address you subscribed with.  You will
only"
         print "be able to unsubscribe if you use that email address."
   else:                                   # Otherwise if email address
not found in mailing list
      if action=="unsubscribe":            # And if actions is
unsubscribe
         if password==UseSplit[1]:         # If password is valid
            memMailList[counter]=''        # Empty internal mailing list
entry
            print "Unsubscription for <B>"+email+"</B> successful" #
Print unsubscribe success to HTML
         else:                             # Otherwise if password not
valid
            print "Unsubscription for <B>"+email+"</B> unsuccessful. 
Password is invalid" # Print unsubscribe unsuccessful to HTML
            print "Remember that passwords are case sensitive.  i.e.
password is not the same as PassWord"
      else:                                # Otherwise if subscribe
         print "Subscription for <B>"+email+"</B> already exists" #
Print subscription already exists to HTML
       
finally:                                   # Finally
   useMailList=open("maillist.txt", "w")   # Open Mailing List for
writing
   useMailList.writelines(memMailList)     # Copy internal mailing list
to file
   useMailList.close                       # Close mailing list
   print useFoot.read()                    # Print HTML footer
   useHead.close;                          # Close HTML header
   useFoot.close;                          # Close HTML footer
------------- ----------------end
quote----------------------------------

This also referrs to a few other files.
1 of 3
-------------------------head.txt---------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
	<title>Programmed Integration - Mailing List</title>
</head>

<body BGCOLOR="BLACK" text="#FFFFFF" link="#66CCFF" vlink="#66CC99"
alink="#FF6666">
<font face="arial">
<TABLE width=100%>
<TR><TD BGCOLOR="#fe4221" WIDTH=100%><CENTER><b>Mailing
List</b></CENTER></TD></TR>
</TABLE>
<P>
<small>
-----------------------------end---------------------------

2 of 3
----------------------foot.txt-------------------------
</small>   
</FONT>
</body>
</html>
-------------------end-----------------------

3 of 3
-------------------maillist.htm---------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
	<title>Programmed Integration - Delphi</title>
<META http-equiv="content-type" content="text/html; charset=iso-8859-1">
<META NAME="GENERATOR" CONTENT="PI-Premote:
www.programmedintegration.com">
<META NAME="description" content="Bespoke software solutions and
Internet websites. Freeware and commercial software. Free PIPL MP3
player. Delphi and Python computer languages">
<META NAME="keywords" content="delphi, consultancy, programming,
bespoke, web, design, MP3, components">
<META NAME="robots" CONTENT="ALL">
<META NAME="revisit-after" CONTENT="30 days">
</head>

<body BGCOLOR="BLACK" text="#FFFFFF" link="#66CCFF" vlink="#66CC99"
alink="#FF6666">
<font face="arial">
<TABLE width=100%>
<TR><TD BGCOLOR="#fe4221" WIDTH=100%><CENTER><b>Mailing
List</b></CENTER></TD></TR>
</TABLE>
<P>
<small>
Over the period of the year we aim to send out bulletins of what we are
up to and any other news that you might find of interest.  If you would
like to subscribe to this list, please fill in your details below.  We
apologise for the double verification of email and password, but we find
it prevents a lot of rogue subscriptions.  We look forward to having you
on our list.<P>

<CENTER>
<form action="cgibin/maillist.py" method="POST">
Your email address (eg. yourname@mydomain.com):<BR>
<input name="email" type="text" value="" SIZE=40 MAXLENGTH=80><BR>
Please re-enter your email address:<BR>
<input name="email2" type="text" value="" SIZE=40 MAXLENGTH=80><P>
<TABLE>
<TR>
<TD ALIGN=RIGHT><small>Please enter a password: </small></TD>
<TD><input name="password" type="text" value="" SIZE=10
MAXLENGTH=20></TD></TR>
<TR><TD ALIGN=RIGHT><small>Please re-enter your password: </small></TD> 
<TD><input name="password2" type="text" value="" SIZE=10
MAXLENGTH=20></TD></TR>
</TABLE>
<P>
Subscribe <input name="action" type="radio" value="subscribe" checked>

UnSubscribe <input name="action" type="radio" value="unsubscribe">
<P ALIGN=LEFT>
Programmed Integration and organisations with whom we have a close
working relationship, may from time to time write to you about specific
services, products and offers which could be of interest. Please
unselect the checkbox if you would prefer not to receive such mailings.
<input type="checkbox" name="optout" value="yes" checked></P>  
<P>

<INPUT TYPE="submit" VALUE="Process">
</form>
</CENTER>

</small>   

</FONT>
</body>
</html>
--------------------------------end-------------------------------







-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/




From deliberatus@my995internet.com  Sat Dec  8 22:02:55 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sat, 08 Dec 2001 17:02:55 -0500
Subject: [Tutor] where it came from
Message-ID: <3C128E0F.259939@my995internet.com>

Here is the link to the page at the site it came from:

http://www.programmedintegration.com/cgi-bin/page.py?pmaillist

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/




From Bruce.Lee-Shanok@cognos.com  Tue Dec 11 16:01:35 2001
From: Bruce.Lee-Shanok@cognos.com (Lee-Shanok, Bruce)
Date: Tue, 11 Dec 2001 11:01:35 -0500
Subject: [Tutor] Application Error after end of program
Message-ID: <FB15E670DA55D51185350008C786514A0140EB5E@sottexch1.cognos.com>

>This might be something you want to post on the main comp.lang.python
>newsgroup as well as Tutor.  These kind of errors should not happen in
>Python, so perhaps someone on comp.lang.python might be able to point out
>a service pack fix in NT that corrects this.

Hmm. I don't have access to newsgroups from here, but I'll look into posting
that later. Thanks! :) And I'm actually running 2K with the latest
everything on it.. to the best of my knowledge.

>Agreed; I don't think this has to do with your program, but with some
>system library of the operating system.

Well it's good to be absolved of guilt. :) There is definitely something odd
going on. I gave it a chug through Purify and I guess the failed assertion
below is what causes the untimely death:

[I] Message: Assertion failed: pHead->nBlockUse == nBlockUse

... whatever that means. :) pHead.. I can remember someone in grade school
calling me that once...

For the interested reader, here's the last three errors..:

[E] FIM: Freeing invalid memory in LocalFree {4 occurrences}
        Address 0x00142788 points into a HeapAlloc'd block in unallocated
region of the default heap
        Location of free attempt
            LocalFree      [KERNEL32.dll]
            DeleteSecurityPackageW [SECUR32.dll]
            LsaDeregisterLogonProcess [SECUR32.dll]
            LdrShutdownProcess [ntdll.dll]
            ExitProcess    [KERNEL32.dll]
            ExitProcess    [KERNEL32.dll]
            cexit          [msvcrt.dll]
            SetFilePointer [KERNEL32.dll]
[E] FIM: Freeing invalid memory in LocalFree {4 occurrences}
        Address 0x00145c08 points into a HeapAlloc'd block in unallocated
region of the default heap
        Location of free attempt
            LocalFree      [KERNEL32.dll]
            DeleteSecurityPackageW [SECUR32.dll]
            LsaDeregisterLogonProcess [SECUR32.dll]
            LdrShutdownProcess [ntdll.dll]
            ExitProcess    [KERNEL32.dll]
            ExitProcess    [KERNEL32.dll]
            cexit          [msvcrt.dll]
            SetFilePointer [KERNEL32.dll]
[I] Message: Assertion failed: pHead->nBlockUse == nBlockUse
        Call location
            malloc_dbg     [dbgheap.c:164]
            free_dbg_lk    [dbgheap.c:1084]
            free_dbg       [dbgheap.c:1001]
            free_dbg       [dbgheap.c:993]
            CRT_INIT       [crtdll.c:236]
            DllMainCRTStartup [crtdll.c:289]
            LdrShutdownProcess [ntdll.dll]
            ExitProcess    [KERNEL32.dll]
            ExitProcess    [KERNEL32.dll]
            cexit          [msvcrt.dll]
            SetFilePointer [KERNEL32.dll]
[I] Exiting with code -1073741819 (0xc0000005)
        Process time: 92482 milliseconds
[I] Program terminated at 12/10/2001 22:39:35

Cheers,
Bruce

This message may contain privileged and/or confidential information.  If you
have received this e-mail in error or are not the intended recipient, you
may not use, copy, disseminate, or distribute it; do not open any
attachments, delete it immediately from your system and notify the sender by
e-mail promptly that you have done so.  Thank You.


From highprimate@howlermonkey.net  Tue Dec 11 16:05:29 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Tue, 11 Dec 2001 11:5:29 -0500
Subject: [Tutor] double messages double messages
Message-ID: <200112111606.fBBG67339588@ns.howlermonkey.net>

Listowner; I am getting everything from the list to this account twice.
Listowner, I am getting everything for this account from the list twice.
Listowner, I think you server is infested with mice.
is that nice?

please advise.


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From deliberatus@my995internet.com  Tue Dec 11 16:19:08 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Tue, 11 Dec 2001 11:19:08 -0500
Subject: [Tutor] another intresting script
Message-ID: <3C1631FC.26E222D2@my995internet.com>

ok, I copied this from the online reference, and messed with it and
messed with it, and the hound won't hunt.
---------------begin pooping------------------
#!/usr/local/bin/python
    import smtplib
    import string

    def prompt(prompt):
        return raw_input(prompt)string.strip()

    fromaddr = prompt("From: ")
    toaddrs  = prompt("To: ").split()
    print "Enter message, end with ^D:"

    # Add the From: and To: headers at the start!
    msg = ("From: %s\r\nTo: %s\r\n\r\n"
           % (fromaddr, string.join(toaddrs, ", ")))
    while 1:
        try:
            line = raw_input()
        except EOFError:
            break
        if not line:
            break
        msg = msg + line

    print "Message length is " + `len(msg)`

    server = smtplib.SMTP('localhost')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, toaddrs, msg)
    server.quit()
-----------------end of poop-----------------------
thing refuses to include a newline character to the variable! bad token
stuff galore!

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Tue Dec 11 16:28:09 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Tue, 11 Dec 2001 11:28:09 -0500
Subject: [Tutor] the original mouse copied
Message-ID: <3C163419.78D32331@my995internet.com>

here is the original. it barks also, but differently.
-------------------begin k9 script--------------------
    import smtplib
    import string

    def prompt(prompt):
        return raw_input(prompt).strip()

    fromaddr = prompt("From: ")
    toaddrs  = prompt("To: ").split()
    print "Enter message, end with ^D:"

    # Add the From: and To: headers at the start!
    msg = ("From: %s\r\nTo: %s\r\n\r\n"
           % (fromaddr, string.join(toaddrs, ", ")))
    while 1:
        try:
            line = raw_input()
        except EOFError:
            break
        if not line:
            break
        msg = msg + line

    print "Message length is " + `len(msg)`

    server = smtplib.SMTP('localhost')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, toaddrs, msg)
    server.quit()
------------------end woofwoof---------------------



-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From fpeavy@pop.net  Tue Dec 11 17:16:19 2001
From: fpeavy@pop.net (Frank Peavy)
Date: Tue, 11 Dec 2001 09:16:19 -0800
Subject: [Tutor] .cgi or .py for Python CGIs
Message-ID: <5.1.0.14.0.20011211091442.00a978d0@mail45566.popserver.pop.net>

I have seen references to various CGI scripts and some have the .cgi 
extension and some have a .py extension. Which is correct? Is there a 
preferred method?



From scarblac@pino.selwerd.nl  Tue Dec 11 17:16:44 2001
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Tue, 11 Dec 2001 18:16:44 +0100
Subject: [Tutor] .cgi or .py for Python CGIs
In-Reply-To: <5.1.0.14.0.20011211091442.00a978d0@mail45566.popserver.pop.net>; from fpeavy@pop.net on Tue, Dec 11, 2001 at 09:16:19AM -0800
References: <5.1.0.14.0.20011211091442.00a978d0@mail45566.popserver.pop.net>
Message-ID: <20011211181644.A9376@pino.selwerd.nl>

On  0, Frank Peavy <fpeavy@pop.net> wrote:
> I have seen references to various CGI scripts and some have the .cgi 
> extension and some have a .py extension. Which is correct? Is there a 
> preferred method?

Python doesn't care. It only needs .py when you import modules from another
module.

There *might* be server settings so that it matters, like I can imagine that
on a Windows server the .py is needed to associate it with Python, but on a
Unix server it should never matter, extensions are irrelevant.

So it's probably a matter of taste.

-- 
Remco Gerlich


From jeff@ccvcorp.com  Tue Dec 11 17:44:15 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue, 11 Dec 2001 09:44:15 -0800
Subject: [Tutor] another intresting script
References: <E16DqHT-0001Wn-00@mail.python.org>
Message-ID: <3C1645EE.A128AA8A@ccvcorp.com>

Kirk Bailey wrote:

>     def prompt(prompt):
>         return raw_input(prompt)string.strip()

Here, you've got an extra 'string' that is non-functional.  Looks like you corrected
this in your second example, though.  You're also re-using the same name for two
different things (the function, and its parameter), which is probably not a good idea.
It should be

def prompt(promptstring):
    return raw_input(promptstring).strip()

Other than that, it's hard to guess what exactly is happening, since you don't give
specific error messages, or say which variable is not getting the newline that you think
it should (and we don't know *where* you expect that newline to be added, either).  You
might try adding a "print repr(msg)" at the same point that you're printing the message
length, and see if it looks like you expect there.

Oh, wait, I see what's probably happening...

    while 1:
        try:
            line = raw_input()
        except EOFError:
            break
        if not line:
            break
        msg = msg + line

You're not getting newlines at the end of each line, here, right?  They are not
automatically added by raw_input(), so you'd need to add them yourself, something like
this:

    msg = msg + line + '\n'

Hope that helps!

Jeff Shannon
Technician/Programmer
Credit International




From deliberatus@my995internet.com  Tue Dec 11 17:45:56 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Tue, 11 Dec 2001 12:45:56 -0500
Subject: [Tutor] intresting gibberish, this. Looks like perl on the rag...
Message-ID: <3C164654.6F9E16BE@my995internet.com>

>From that original quoteed script, I read:

>msg = ("From: %s\r\nTo: %s\r\n\r\n"
           % (fromaddr, string.join(toaddrs, ", ")))

which is word wrapped, so here it is strait:
msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, string.join(toaddrs, ",
")))

this means:
"From: (str(repr(\n)repr(\n)) str(fromaddr, string.join(toaddr, ", ")))

ok, first part is sensible, but last part is a pooch. why do we want to
bibble with from and two in this place, and end it with a comma and no
trailing CRLF?

Seems I cannoy simply append a CRLF into the end of a string or a list
or anything else, I have to play intresting games to accomplish it.
FUCK, said the king.

I should invent a new definition, CRLF, as 

def CRLF:
	CRLF =("%s\r\n")
Then can use it casually in string concatenation, and plaster it on the
end of a variable, 
No? yes?

This sort of grunting gibbercode is why I avoided perl after failing to
sledgehammer it through my concrete skull.

Discussion?

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From cliff@ember.com  Tue Dec 11 18:51:48 2001
From: cliff@ember.com (cliff@ember.com)
Date: Tue, 11 Dec 2001 13:51:48 -0500
Subject: [Tutor] 2 questions on Tkinter
Message-ID: <3C160F74.29459.173C2C1@localhost>

Hi List.

Q1.

In the Tkinter library, there is a method OptionMenu that takes
a variable number of strings as arguments.  These strings become
choices displayed on the menu:

OptionMenu(root, stringVar, 'First Choice', 'Second Choice')

I would like to configure an option menu based on the contents of
a list.  How do I call OptionMenu() using the strings in the list?
(The number of strings in the list is determined when the script
is run.)

Q2.

What do I have misconfigured if python can't find Tkinter?  I get an 
ImportError when I try to import Tkinter on my Linux box.

Thanks!

--Cliff





From vip333d@yahoo.com  Tue Dec 11 20:53:51 2001
From: vip333d@yahoo.com (vip333d@yahoo.com)
Date: Tue, 11 Dec 2001 12:53:51 -0800 (PST)
Subject: [Tutor] quick question
Message-ID: <20011211205351.83087.qmail@web12307.mail.yahoo.com>

dear tutor,
I started learning python threw the net. I downloaded
python 2.1.1 . I have one problem: I write my sripts
on a note-pad (windows 95 standard...). then, I save
it as *.py. when it finishes the script, it strait
closes the dialog box, and I cannot see a thing.
thanks,
number 637927

vip333d@yahoo.com

__________________________________________________
Do You Yahoo!?
Check out Yahoo! Shopping and Yahoo! Auctions for all of
your unique holiday gifts! Buy at http://shopping.yahoo.com
or bid at http://auctions.yahoo.com


From jrm@videotron.ca  Tue Dec 11 14:12:45 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Tue, 11 Dec 2001 16:12:45 +0200
Subject: [Tutor] quick question
References: <20011211205351.83087.qmail@web12307.mail.yahoo.com>
Message-ID: <000901c1824d$e7d875a0$0100c0a8@videotron.ca>

----- Original Message -----
From: <vip333d@yahoo.com>

> dear tutor,
> I started learning python threw the net. I downloaded
> python 2.1.1 . I have one problem: I write my sripts
> on a note-pad (windows 95 standard...). then, I save
> it as *.py. when it finishes the script, it strait
> closes the dialog box, and I cannot see a thing.
> thanks,
> number 637927
>
> vip333d@yahoo.com

    Dear you,

        I never used Notepad for Python, so I can't answer your question.
Anyway don't loose you time : I suggest that you don't use it either. In
"start/programs/Python2.1/IDLE(Python GUI)  you have IDLE, a true
IDE(Integrated Development Environment--if I'm not mistaking). Use that
instead : it has infinitely much more to offer and won't give you much
trouble.
        Read http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
first a very light intro. Then read the more involved doc on
http://www.python.org : look for IDLE on the left panel. Sorry that I can't
give you a more precise link but the site seem to be down at this moment.

    Jean M.





From israel@lith.com  Tue Dec 11 21:16:22 2001
From: israel@lith.com (Israel Evans)
Date: Tue, 11 Dec 2001 13:16:22 -0800
Subject: [Tutor] quick question
Message-ID: <AF020C5FC551DD43A4958A679EA16A15017B3E9D@abbott.lith.com>

Often, if you want your script window to stick around after it is done put a
raw_input() call at the end.  This will cause the window to stay up until
you hit a key.

I'd second the suggestion of using Idle, especially for learning python.
It's a great tool that will really help you understand the language.  Using
it you can interactively run and write you code at the same time.



~Israel~

-----Original Message-----
From: Jean Montambeault [mailto:jrm@videotron.ca] 
Sent: 11 December 2001 6:13 AM
To: tutor@python.org
Subject: Re: [Tutor] quick question


----- Original Message -----
From: <vip333d@yahoo.com>

> dear tutor,
> I started learning python threw the net. I downloaded
> python 2.1.1 . I have one problem: I write my sripts
> on a note-pad (windows 95 standard...). then, I save
> it as *.py. when it finishes the script, it strait
> closes the dialog box, and I cannot see a thing.
> thanks,
> number 637927
>
> vip333d@yahoo.com

    Dear you,

        I never used Notepad for Python, so I can't answer your question.
Anyway don't loose you time : I suggest that you don't use it either. In
"start/programs/Python2.1/IDLE(Python GUI)  you have IDLE, a true
IDE(Integrated Development Environment--if I'm not mistaking). Use that
instead : it has infinitely much more to offer and won't give you much
trouble.
        Read http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
first a very light intro. Then read the more involved doc on
http://www.python.org : look for IDLE on the left panel. Sorry that I can't
give you a more precise link but the site seem to be down at this moment.

    Jean M.




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


From jrm@videotron.ca  Tue Dec 11 14:28:44 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Tue, 11 Dec 2001 16:28:44 +0200
Subject: [Tutor] You're gridded for life.
Message-ID: <000f01c18250$23cfcca0$0100c0a8@videotron.ca>

    Remember my question about shortcuts to ".grid" ? Maybe not but look at
this :

Exemple1 : this doesn't work...
===================================
#! /usr/bin/env python

# Exemple1 for the tutor mailing list

from Tkinter import *

def here_I_am(event):
    print "Yes, that's me!"

fen=Tk()

tom_dee_lee_dum=Entry(fen).grid(row=0, column=0)
tom_dee_lee_dum.bind("<Return>", here_I_am)

#fen.mainloop() (commented out for running inside IDLE)

##Traceback (most recent call last):
##  File "C:/Python21/exemple1.pyw", line 13, in ?
##    tom_dee_lee_dum.bind("<Return>", here_I_am)
##AttributeError: 'None' object has no attribute 'bind'
===================================

Exemple2 : ...but this does

===================================
#! /usr/bin/env python

# Exemple1 for the tutor mailing list

from Tkinter import *

def here_I_am(event):
    print "Yes, that's me!"

fen=Tk()

tom_dee_lee_dum=Entry(fen)
tom_dee_lee_dum.grid(row=0, column=0)
tom_dee_lee_dum.bind("<Return>", here_I_am)

#fen.mainloop()
===================================
So my question : is the shortcut technique only good for the widgets that
aren't assigned to a variable ? This snag costed me two hours of my life and
some selected curses, these very graphical ; in no tutorial is "extreme
tolerance to frustration" ever mentionned among the qualities that make a
good programmer but it really should. The up side : it feels really good
when it stops. ;)
>From now on I'll stick to classical forms.

Jean M.




From dyoo@hkn.eecs.berkeley.edu  Tue Dec 11 22:20:31 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 11 Dec 2001 14:20:31 -0800 (PST)
Subject: [Tutor] You're gridded for life.  [OOP using __getattr__]
In-Reply-To: <000f01c18250$23cfcca0$0100c0a8@videotron.ca>
Message-ID: <Pine.LNX.4.21.0112111352090.4817-100000@hkn.eecs.berkeley.edu>

On Tue, 11 Dec 2001, Jean Montambeault wrote:

> tom_dee_lee_dum = Entry(fen).grid(row=0, column=0)

Yes, I remember now.  As you've discovered, the non-buggy version of
this is:

> tom_dee_lee_dum=Entry(fen)
> tom_dee_lee_dum.grid(row=0, column=0)
> tom_dee_lee_dum.bind("<Return>", here_I_am)

But what you wrote before, this "bug", seems to be a common one that
beginning Tkinter programmers do a lot!  Perhaps it might be nice to
actually allow some kind of shortcut like this.

We can write a "ShortcutEntry" class of Entry widgets with slightly
different behavior.  Here's an example that might be useful for you:

###
import Tkinter

class ShortcutEntry:
    """This is a small class that demonstrates how to customize an
    Entry widget without subclassing."""
    def __init__(self, *args, **kwargs):
        self.entry = Tkinter.Entry(*args, **kwargs)


    def pack(self, *args, **kwargs):
        self.entry.pack(*args, **kwargs)
        return self.entry


    def grid(self, *args, **kwargs):
        self.entry.grid(*args, **kwargs)
        return self.entry


    def __getattr__(self, name):
        """We delegate pretty much everything to our underlying
        self.entry."""
        return getattr(self.entry, name)
###


This class should allow us to do:

###
tom_dee_lee_dum = ShortcutEntry(fen).grid(row=0, column=0)
###

with the effect that we're looking for.


As a personal opinion, I think that the Tkinter widgets should do
something like this anyway, to make Tkinter programming more convenient.  
However, I get the feeling that the above code might upset a few people.  
*grin*  What do other people think about this?


> in no tutorial is "extreme tolerance to frustration" ever mentioned
> among the qualities that make a good programmer but it really should.

When things start getting too frustrating, start spilling the problem to
Tutor.  Let's help each other avoid frustration.


Best of wishes to you.



From highprimate@howlermonkey.net  Tue Dec 11 16:23:46 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Tue, 11 Dec 2001 11:23:46 -0500
Subject: [Tutor] test test
Message-ID: <200112111624.fBBGOP339684@ns.howlermonkey.net>

let's see if this doubles
let see if there's still trouble


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From dyoo@hkn.eecs.berkeley.edu  Tue Dec 11 23:04:23 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 11 Dec 2001 15:04:23 -0800 (PST)
Subject: [Tutor] quick question
In-Reply-To: <AF020C5FC551DD43A4958A679EA16A15017B3E9D@abbott.lith.com>
Message-ID: <Pine.LNX.4.21.0112111502090.6641-100000@hkn.eecs.berkeley.edu>

On Tue, 11 Dec 2001, Israel Evans wrote:

> Often, if you want your script window to stick around after it is done put a
> raw_input() call at the end.  This will cause the window to stay up until
> you hit a key.
> 
> I'd second the suggestion of using Idle, especially for learning python.
> It's a great tool that will really help you understand the language.  Using
> it you can interactively run and write you code at the same time.

Hi vip333d,

Also, you should already have IDLE installed: it comes bundled with Python
for your convenience.  If you visit:

    http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/

you'll see a page that shows some introductory use of IDLE.



From dradul@007mundo.com  Tue Dec 11 22:43:57 2001
From: dradul@007mundo.com (P. Alejandro Lopez-Valencia)
Date: Tue, 11 Dec 2001 17:43:57 -0500
Subject: [Tutor] .cgi or .py for Python CGIs
References: <5.1.0.14.0.20011211091442.00a978d0@mail45566.popserver.pop.net> <20011211181644.A9376@pino.selwerd.nl>
Message-ID: <001901c18297$564c5440$6a32a741@shangrila>

----- Original Message -----
From: "Remco Gerlich" <scarblac@pino.selwerd.nl>
To: "tutor-python.org" <tutor@python.org>
Sent: Tuesday, December 11, 2001 12:16 PM
Subject: Re: [Tutor] .cgi or .py for Python CGIs


> On  0, Frank Peavy <fpeavy@pop.net> wrote:
> > I have seen references to various CGI scripts and some have the .cgi
> > extension and some have a .py extension. Which is correct? Is there a
> > preferred method?
>
> Python doesn't care. It only needs .py when you import modules from
another
> module.
>
> There *might* be server settings so that it matters, like I can imagine
that
> on a Windows server the .py is needed to associate it with Python, but on
a
> Unix server it should never matter, extensions are irrelevant.
>
> So it's probably a matter of taste.
>
> --
> Remco Gerlich

Not exactly. As a rule web servers (as contrasted to the operating system
they run on), do use file extensions to identify CGI programs, particularly
if they are not in the CGI root directory (usually cgi-bin) but in some
other place in the web server virtual file system. Always think of a web
server as an independent operating system running within a virtual machine,
that has access to low level system calls (the operating system it runs on).

Namely, using apache as an example:

/cgi-bin (root CGI directory) -> You can have any extension or note, by
definition anything is executable, and therefore the security model implies
that only the administrator has access to this directory.

~/cgi-bin (user home CGI directory) -> By default you need the .cgi
extension to tell the web server the file is an executable. This can change
depending on the server administrator ideas of what he/she considers OK for
a luser, say, he writes his private CGIs with python, thus he adds .py to
the list of allowed CGI extensions (I know I do ;).

/foo/bar (some data directory in the virtual web server filesystem) -> Same
situation as the previous, yet he who allows this kind of file execution
should be given the choice to switch jobs to salesperson in an incense shop.




From dsh8290@rit.edu  Tue Dec 11 23:39:39 2001
From: dsh8290@rit.edu (dman)
Date: Tue, 11 Dec 2001 18:39:39 -0500
Subject: [Tutor] retrieving stock quotes
In-Reply-To: <Pine.GSO.4.21.0112102148190.28442-100000@isis.visi.com>; from wilson@visi.com on Mon, Dec 10, 2001 at 09:57:55PM -0600
References: <Pine.GSO.4.21.0112102133120.27812-100000@isis.visi.com> <Pine.GSO.4.21.0112102148190.28442-100000@isis.visi.com>
Message-ID: <20011211183938.A26257@harmony.cs.rit.edu>

On Mon, Dec 10, 2001 at 09:57:55PM -0600, Timothy Wilson wrote:
| On Mon, 10 Dec 2001, Timothy Wilson wrote:
| 
| > Does anyone know of an ftp site or Web site that has fairly current stock
| > quotes in an easily parsable format?
| 
| <lame self-reply>
| Very cool! I happened upon exactly what I needed. Go to
| http://finance.yahoo.com/ and enter a ticker symbol (RHAT, for

The only thing to beware of is it seems that yahoo likes to change the
HTML layout of the page rather often.  Depending on the nature of the
change and the nature of your parser, this may or may not have an
effect.

-D

-- 

A)bort, R)etry, D)o it right this time



From dsh8290@rit.edu  Tue Dec 11 23:43:36 2001
From: dsh8290@rit.edu (dman)
Date: Tue, 11 Dec 2001 18:43:36 -0500
Subject: [Tutor] You're gridded for life.
In-Reply-To: <000f01c18250$23cfcca0$0100c0a8@videotron.ca>; from jrm@videotron.ca on Tue, Dec 11, 2001 at 04:28:44PM +0200
References: <000f01c18250$23cfcca0$0100c0a8@videotron.ca>
Message-ID: <20011211184336.B26257@harmony.cs.rit.edu>

On Tue, Dec 11, 2001 at 04:28:44PM +0200, Jean Montambeault wrote:
|     Remember my question about shortcuts to ".grid" ? Maybe not but look at
| this :
...
| So my question : is the shortcut technique only good for the widgets that
| aren't assigned to a variable ?

It is more general than that.  Every function/method has a return
value of some sort.  If the function/method doesn't explicitly return
something, then it returns 'None' implicitly (so that if it is called
in a compound statement there is a value to use in the rest of the
statement).

In the one example, the object was used _only_ to invoke the grid()
method on, and never again.  The grid() method returns None, not the
object it was invoked on.  If you intend to ever use that object
again, you need to create it and grab a handle on it so that you can
use it again.  Thus the call to grid() must be separate from the
creation.

HTH,
-D

-- 

(E)ventually (M)alloc()s (A)ll (C)omputer (S)torage



From pythontutor@venix.com  Tue Dec 11 23:54:55 2001
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 11 Dec 2001 18:54:55 -0500
Subject: [Tutor] web site redirection to Python script
Message-ID: <3C169CCF.4080709@venix.com>

I wrote some python scripts for reporting survey results from an SQL server.
Now they would like these to scripts to be available from a web site.
Unfortunately, the ISP hosting the web site has not yet installed Python.
I have setup a RedHat Linux server with Python.  Now I need to set up a Perl(?)
script on the web site to forward report requests to my "Python Server" which
will process the requested data, create an HTML report, and send the HTML report
to the requestor.

PC/Browser >=reportRequest=> www.HowsYourHealth.org  >=reportRequest=> "PythonServer"

I need advice as to how the web server (Linux/Apache/Perl) can forward the request to
the "Python Server".  Or tell me there is a better way to do this.

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

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



From m_konermann@gmx.de  Wed Dec 12 00:08:02 2001
From: m_konermann@gmx.de (Marcus Konermann)
Date: Wed, 12 Dec 2001 01:08:02 +0100
Subject: [Tutor] Problems with enviroment variable under W2000 and VC6++
Message-ID: <3C169FE2.52B6EDC3@gmx.de>

--------------200D79DC9A57F5A5BD6F3E17
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 8bit

Hi @ All !

For now i tried a lot of things to tell SWIG where the lib directory is,
but after controlling by using the command "swig -swiglib"  every time
the output was " /usr/local/lib/swig1.3."
So to solve this problem the only solution for me was to copy the four
file´s (swig.swg, python.swg, common.swg, swig.exe) manually in the
working directory, but i don´t think that this was the right way. I also
tried to set the PATH to the lib directory under W2000 in the enviroment
variables, but nothing happend.

The second problem for me is to set the right enviroment variable for
python2.1 in the windows 2000 sytem. I tried to use PYTHONPATH,
PYTHON_INCLUDE and PYTHON_LIB (like described in the SWIG manual 1.3.9),
but nothing happend while compiling under VC6++. The Linker only says:
simanneal_wrap.cpp
C:\simanneal_wrap.cpp(179) : fatal error C1083: Include-Datei kann nicht
geoeffnet werden: 'Python.h': No such file or directory

Please, i need help
Greetings
Marcus

--------------200D79DC9A57F5A5BD6F3E17
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
Hi @ All !
<p>For now i tried a lot of things to tell SWIG where the lib directory
is, but after controlling by using the command "swig -swiglib"&nbsp; every
time the output was " /usr/local/lib/swig1.3."
<br>So to solve this problem the only solution for me was to copy the four
file&acute;s (swig.swg, python.swg, common.swg, swig.exe) manually in the
working directory, but i don&acute;t think that this was the right way.
I also tried to set the PATH to the lib directory under W2000 in the enviroment
variables, but nothing happend.
<p>The second problem for me is to set the right enviroment variable for
python2.1 in the windows 2000 sytem. I tried to use PYTHONPATH, PYTHON_INCLUDE
and PYTHON_LIB (like described in the SWIG manual 1.3.9), but nothing happend
while compiling under VC6++. The Linker only says:
<br><i>simanneal_wrap.cpp</i>
<br><i>C:\simanneal_wrap.cpp(179) : fatal error C1083: Include-Datei kann
nicht geoeffnet werden: 'Python.h': No such file or directory</i><i></i>
<p>Please, i need help
<br>Greetings
<br>Marcus</html>

--------------200D79DC9A57F5A5BD6F3E17--



From jens.jorgensen@tallan.com  Wed Dec 12 00:25:07 2001
From: jens.jorgensen@tallan.com (Jorgensen, Jens)
Date: Tue, 11 Dec 2001 18:25:07 -0600
Subject: [Tutor] Re: [python-win32] Problems with enviroment variable under W2000 and VC6++
References: <3C169FE2.52B6EDC3@gmx.de>
Message-ID: <3C16A3E3.5050809@tallan.com>

Marcus,

Is your C++ code quite large? I have to say I've created a number of 
Python extension modules and I've always just built them by hand. Also 
there is that gui generation tool that will create the code skeleton for 
you. It really is easy.

Marcus Konermann wrote:

> Hi @ All !
>
> For now i tried a lot of things to tell SWIG where the lib directory 
> is, but after controlling by using the command "swig -swiglib"  every 
> time the output was " /usr/local/lib/swig1.3."
> So to solve this problem the only solution for me was to copy the four 
> file´s (swig.swg, python.swg, common.swg, swig.exe) manually in the 
> working directory, but i don´t think that this was the right way. I 
> also tried to set the PATH to the lib directory under W2000 in the 
> enviroment variables, but nothing happend.
>
> The second problem for me is to set the right enviroment variable for 
> python2.1 in the windows 2000 sytem. I tried to use PYTHONPATH, 
> PYTHON_INCLUDE and PYTHON_LIB (like described in the SWIG manual 
> 1.3.9), but nothing happend while compiling under VC6++. The Linker 
> only says:
> /simanneal_wrap.cpp/
> /C:\simanneal_wrap.cpp(179) : fatal error C1083: Include-Datei kann 
> nicht geoeffnet werden: 'Python.h': No such file or directory/
>
> Please, i need help
> Greetings
> Marcus
>


-- 
Jens B. Jorgensen
jens.jorgensen@tallan.com




From wilson@visi.com  Wed Dec 12 01:18:13 2001
From: wilson@visi.com (Timothy Wilson)
Date: Tue, 11 Dec 2001 19:18:13 -0600 (CST)
Subject: [Tutor] retrieving stock quotes
In-Reply-To: <20011211183938.A26257@harmony.cs.rit.edu>
Message-ID: <Pine.GSO.4.21.0112111914530.27595-100000@isis.visi.com>

On Tue, 11 Dec 2001, dman wrote:

> On Mon, Dec 10, 2001 at 09:57:55PM -0600, Timothy Wilson wrote:
> | On Mon, 10 Dec 2001, Timothy Wilson wrote:
> | 
> | > Does anyone know of an ftp site or Web site that has fairly current stock
> | > quotes in an easily parsable format?
> | 
> | <lame self-reply>
> | Very cool! I happened upon exactly what I needed. Go to
> | http://finance.yahoo.com/ and enter a ticker symbol (RHAT, for
> 
> The only thing to beware of is it seems that yahoo likes to change the
> HTML layout of the page rather often.  Depending on the nature of the
> change and the nature of your parser, this may or may not have an
> effect.

That's why I'm retrieving the raw data in CSV form. For example:

http://finance.yahoo.com/d/quotes.csv?s=sgi&f=sl1d1t1c1ohgv&e=.csv

gets the raw data for SGI. That should be a lot less likely to change over
time.

-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 dsh8290@rit.edu  Wed Dec 12 02:05:09 2001
From: dsh8290@rit.edu (dman)
Date: Tue, 11 Dec 2001 21:05:09 -0500
Subject: [Tutor] web site redirection to Python script
In-Reply-To: <3C169CCF.4080709@venix.com>; from pythontutor@venix.com on Tue, Dec 11, 2001 at 06:54:55PM -0500
References: <3C169CCF.4080709@venix.com>
Message-ID: <20011211210509.A26587@harmony.cs.rit.edu>

On Tue, Dec 11, 2001 at 06:54:55PM -0500, Lloyd Kvam wrote:
| I wrote some python scripts for reporting survey results from an SQL
| server.  Now they would like these to scripts to be available from a
| web site.  Unfortunately, the ISP hosting the web site has not yet
| installed Python.  I have setup a RedHat Linux server with Python.
| Now I need to set up a Perl(?) script on the web site to forward
| report requests to my "Python Server" which will process the
| requested data, create an HTML report, and send the HTML report to
| the requestor.
 
| I need advice as to how the web server (Linux/Apache/Perl) can
| forward the request to the "Python Server".  Or tell me there is a
| better way to do this.


<HTML> 
    <HEAD>
        <META HTTP-EQUIV="REFRESH" CONTENT="3; URL=http://www.python.org">
    </HEAD>
    <BODY>
        The real data is at <a href="http://www.python.org">www.python.org</a>.
    </BODY>
</HTML>


(the key is in the "head" portion, and in browsers that support it)

-D

-- 

He who finds a wife finds what is good
and receives favor from the Lord.
        Proverbs 18:22



From dsh8290@rit.edu  Wed Dec 12 02:06:22 2001
From: dsh8290@rit.edu (dman)
Date: Tue, 11 Dec 2001 21:06:22 -0500
Subject: [Tutor] retrieving stock quotes
In-Reply-To: <Pine.GSO.4.21.0112111914530.27595-100000@isis.visi.com>; from wilson@visi.com on Tue, Dec 11, 2001 at 07:18:13PM -0600
References: <20011211183938.A26257@harmony.cs.rit.edu> <Pine.GSO.4.21.0112111914530.27595-100000@isis.visi.com>
Message-ID: <20011211210621.B26587@harmony.cs.rit.edu>

On Tue, Dec 11, 2001 at 07:18:13PM -0600, Timothy Wilson wrote:
| On Tue, 11 Dec 2001, dman wrote:
| > On Mon, Dec 10, 2001 at 09:57:55PM -0600, Timothy Wilson wrote:
| > | On Mon, 10 Dec 2001, Timothy Wilson wrote:
| > | > Does anyone know of an ftp site or Web site that has fairly
| > | > current stock quotes in an easily parsable format?
| > | 
| > | <lame self-reply>
| > | Very cool! I happened upon exactly what I needed. Go to
| > | http://finance.yahoo.com/ and enter a ticker symbol (RHAT, for
| > 
| > The only thing to beware of is it seems that yahoo likes to change the
| > HTML layout of the page rather often.  Depending on the nature of the
| > change and the nature of your parser, this may or may not have an
| > effect.
| 
| That's why I'm retrieving the raw data in CSV form. For example:

That should be better, I would expect.

-D

-- 

Stay away from a foolish man,
for you will not find knowledge on his lips.
        Proverbs 14:7



From dyoo@hkn.eecs.berkeley.edu  Wed Dec 12 02:06:35 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 11 Dec 2001 18:06:35 -0800 (PST)
Subject: [Tutor] web site redirection to Python script
In-Reply-To: <3C169CCF.4080709@venix.com>
Message-ID: <Pine.LNX.4.21.0112111621150.9523-100000@hkn.eecs.berkeley.edu>

On Tue, 11 Dec 2001, Lloyd Kvam wrote:

> I wrote some python scripts for reporting survey results from an SQL
> server. Now they would like these to scripts to be available from a
> web site. Unfortunately, the ISP hosting the web site has not yet
> installed Python. I have setup a RedHat Linux server with Python.  
> Now I need to set up a Perl(?) script on the web site to forward
> report requests to my "Python Server" which will process the requested
> data, create an HTML report, and send the HTML report to the
> requestor.
> 
> PC/Browser >=reportRequest=> www.HowsYourHealth.org >=reportRequest=>
> "PythonServer"

This sounds reasonable.  Should the PC/Browser be aware that they're
bouncing to the PythonServer page, or should it appear that everything's
coming from www.howsyourhealth.org?  If it's ok to do a simple redirect,
then you can have your script on www.howsyourhealth.org do something like:

###
#!/usr/bin/perl -w
print "Location: PythonServer\n\n"
###

This sends the user right off to your PythonServer.  Afterwards, since the
user is directly talking to PythonServer, things should be ok.

Diagramically, this looks sorta like this:

    PC/Browser ----> www.HowsYourHealth.org 
        ^            "Talk to PythonServer instead."
        |
        |
        |
        +----------> PythonServer



> I need advice as to how the web server (Linux/Apache/Perl) can forward
> the request to the "Python Server".  Or tell me there is a better way
> to do this.

But perhaps you might want to make this more transparent, so that the user
is never aware of PythonServer's existance; that is, maybe we want
something like this:

    PC/Browser <-----> www.HowsYourHealth.org <-----> PythonServer



From dyoo@hkn.eecs.berkeley.edu  Wed Dec 12 02:19:11 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 11 Dec 2001 18:19:11 -0800 (PST)
Subject: [Tutor]           [Why "replies" twice?]
In-Reply-To: <200112100446.fBA4kO327947@ns.howlermonkey.net>
Message-ID: <Pine.LNX.4.21.0112111808140.12671-100000@hkn.eecs.berkeley.edu>

On Sun, 9 Dec 2001, Kirk Bailey wrote:

> At 12/9/01 8:03:00 PM, you wrote:
> >Hi Kirk,
> >
> >
> Shaboom.
> 
> Why am I getting 2 copies of each of your posts?

Hi Kirk,

The first copy is because I'm replying to your post, and the second is
from the Tutor list itself broadcasting that reply to all the people
subscribed on Tutor.

This is the behavior that most people expect, because it works great with
email programs like Eudora or Outlook (or procmail on Unix systems).  
With these programs, people usually set things up so that
"tutor@python.org" mail goes into a Tutor mailbox separate from their
"Inbox".

Ideally, when someone responds to your message, the first copy will go
into your Inbox, while the second filters into your Tutor mailbox.

Hope that makes sense.  Good luck!



From deliberatus@my995internet.com  Wed Dec 12 04:55:12 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Tue, 11 Dec 2001 23:55:12 -0500
Subject: [Tutor] smtoplib script appears bogus
Message-ID: <3C16E330.DDA24046@my995internet.com>

This thing don't work. Beats me why, I copied it from the on line docs
for the language, but there ya go.
-----------------select aged bits---------------
     import smtplib
     import string

     def prompt(prompt):
         return raw_input(prompt).strip()

     fromaddr = prompt("From: ")
     toaddrs  = prompt("To: ").split()
     print "Enter message, end with ^D:"

     # Add the From: and To: headers at the start!
     msg = ("From: %s\r\nTo: %s\r\n\r\n"
            % (fromaddr, string.join(toaddrs, ", ")))	# probably word
wrapped.
     while 1:						# when all on one line, it still don't work right.
         try:
             line = raw_input()
         except EOFError:
             break
         if not line:
             break
         msg = msg + line

     print "Message length is " + `len(msg)`

     server = smtplib.SMTP('localhost')
     server.set_debuglevel(1)
     server.sendmail(fromaddr, toaddrs, msg)
     server.quit()
------------------------------------------------------
-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From chikitychina@home.com  Wed Dec 12 05:51:13 2001
From: chikitychina@home.com (Pablo Manzanera)
Date: Wed, 12 Dec 2001 00:51:13 -0500
Subject: [Tutor] Killing a windows process
Message-ID: <3C16F051.6200566@home.com>

Hey all,

	I have a simple(hopefully) question for you.  I'm just beginning with
Python, and I'm trying to write a script to manually uninstall a windows
program.  In order to delete a directory, I need to kill a process that
is running whenever the system is up.  I have seen os.kill() for Unix,
but is there a similar command for windows?  I would like it to
recognize the name of the process, but if that's not possible I can
probably work around it.  I am using ActivePython 2.1.1 in case you were
wondering.

Thanks in advance,

Pablo Manzanera



From deliberatus@my995internet.com  Wed Dec 12 06:13:19 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 01:13:19 -0500
Subject: [Tutor] slightly less maaningless drivel ensues
Message-ID: <3C16F57F.7EDC461D@my995internet.com>

HEY! This works ok! No horrors! I received the message it sent!


------------------------begin fresh bits--------------------------------
#!/usr/local/bin/python
                                # so the script is executable
import smtplib                  # import the smtp routines
import string                   # and string manipulation stuff

CRLF=("\r"+"\n")                        # we will be tagging CRLF onto
several things.
                                        # so this is handy.

def prompt(prompt):
        return string.strip(raw_input(prompt))  # prompt, get, strip,
return.


fromaddr = prompt("From: ")             # get the from address.
toaddrs  = prompt("To: ")               # get the to address.
subject = prompt("Subject: ")           # get the subject.

print "Enter message, end with ^D:"     # Add the From: and To: headers
at the start!

msg = "From: " + fromaddr + CRLF + "To: " + toaddrs + CRLF + "Subject: "
+ subject + CRLF +
 CRLF

while 1:
        try:
                line = raw_input()
        except EOFError:
                break
        if not line:
                break
        msg = msg + line + CRLF

print type(msg)

print "Message length is " , len(msg) , " bytes long."

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


ns# 
------------------------end limberger--------------------------

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Wed Dec 12 06:21:38 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 01:21:38 -0500
Subject: [Tutor] slightly updated version of same script
Message-ID: <3C16F772.771CD015@my995internet.com>

Here ya go. Took out the extra crof and the testing code with the type
statement.

Now that I can get this working, I need to go play with DIGESTING
incoming email and examining header information. Good thing I trapped a
few incoming letters into files in the server so I have data to feed the
script for testing.

Any and all, feel free to examine this and comment on anything you like.


-------------------burst along this line, scattering intestines
everyplace else---------------

#!/usr/local/bin/python
                                        # so the script is executable
import smtplib                          # import the smtp routines
import string                           # and string manipulation stuff

CRLF=("\r"+"\n")                        # we will be tagging CRLF onto
several things.
                                        # so this is handy to have
around.

def prompt(prompt):
        return string.strip(raw_input(prompt))  # prompt, get, strip,
return.


fromaddr = prompt("From: ")             # get the from address.
toaddrs  = prompt("To: ")               # get the to address.
subject = prompt("Subject: ")           # get the subject.

print "Enter message, end with ^D:"     # Add the From: and To: headers
at the start!

msg = "From: " + fromaddr + CRLF + "To: " + toaddrs + CRLF + "Subject: "
+ subject + CRLF

while 1:
        try:
                line = raw_input()
        except EOFError:
                break
        if not line:
                break
        msg = msg + line + CRLF


print "Message length is " , len(msg) , " bytes long."

server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
------------------------end---------------------------
 
-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Wed Dec 12 07:17:43 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 02:17:43 -0500
Subject: [Tutor] walking a list
Message-ID: <3C170497.2D5832E@my995internet.com>

Ok, let's walk through a list.

I created a file, testlist.txt, with several addresses in it.

did this:

f1=open('testlist.txt','r')
members = f1.readlines()
f1.close()
type(members)
>>>type<list>
>>>|

Sokay, now try to walk it in a for loop:

for i in members:
	print members[1]

Gets this error:

	
Traceback (most recent call last):
  File "<pyshell#119>", line 2, in ?
    print members[i]
TypeError: sequence index must be integer
>>>|


ok, how do I get it to walk through a loop, performing a block of code
for each item in the list?

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From Tron@submatrix.com  Wed Dec 12 07:28:20 2001
From: Tron@submatrix.com (Tron)
Date: Tue, 11 Dec 2001 23:28:20 -0800
Subject: [Tutor] Free SoCal LAN
References: <3C169CCF.4080709@venix.com>
Message-ID: <00e001c182de$92ea6530$6e01a8c0@praxis>

I dig free what about you guys?  Just wanted to let anyone know if they
wanted to take a break from coding or even share some knowledge.

    Sub Matrix is throwing a Lan Party December 28th through the 30th. Best
part of it the lan is it is totally free. We will have a ton of soda, food,
and the admission is waived for the whole weekend. I will be putting up a
sign up page on our web site Wednesday so you can register. If we are full
by next Wednesday I will be able to look into getting some prizes for a few
tournaments.

Location:Hat Lan www.hatlan.com
Price:Free
Soda/Food:Included
Opennings:70-80
Register:www.submatrix.com/lanparty
Contact:Tron@submatrix.com

-Tron



From dyoo@hkn.eecs.berkeley.edu  Wed Dec 12 07:38:41 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 11 Dec 2001 23:38:41 -0800 (PST)
Subject: [Tutor] smtoplib script appears bogus
In-Reply-To: <3C16E330.DDA24046@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112112332540.16665-100000@hkn.eecs.berkeley.edu>

On Tue, 11 Dec 2001, Kirk Bailey wrote:

> This thing don't work. Beats me why, I copied it from the on line docs
> for the language, but there ya go.

Hi Kirk,

Can you be more specific about "don't work"?  I don't mean to be flippant
or unserious in asking this.  When asking for help on buggy code, it's
very important to say what the bug is --- error messages are always a good
thing to mention.  This helps reduce our chasing after the wind.


The only wild guess I can make is that to check that your program's
indentation begins at the very left margin.  The code that you quoted
suggests that you've already indented your code by one level, which Python
thinks of as a SyntaxError --- at least at the beginning, code needs to
start of with zero indentation.

Good luck to you.

> -----------------select aged bits---------------
>      import smtplib
>      import string
> 
>      def prompt(prompt):
>          return raw_input(prompt).strip()
> 
>      fromaddr = prompt("From: ")
>      toaddrs  = prompt("To: ").split()
>      print "Enter message, end with ^D:"
> 
>      # Add the From: and To: headers at the start!
>      msg = ("From: %s\r\nTo: %s\r\n\r\n"
>             % (fromaddr, string.join(toaddrs, ", ")))	# probably word
> wrapped.
>      while 1:						# when all on one line, it still don't work right.
>          try:
>              line = raw_input()
>          except EOFError:
>              break
>          if not line:
>              break
>          msg = msg + line
> 
>      print "Message length is " + `len(msg)`
> 
>      server = smtplib.SMTP('localhost')
>      server.set_debuglevel(1)
>      server.sendmail(fromaddr, toaddrs, msg)
>      server.quit()
> ------------------------------------------------------



From dyoo@hkn.eecs.berkeley.edu  Wed Dec 12 07:44:20 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 11 Dec 2001 23:44:20 -0800 (PST)
Subject: [Tutor] walking a list
In-Reply-To: <3C170497.2D5832E@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112112339250.16665-100000@hkn.eecs.berkeley.edu>

On Wed, 12 Dec 2001, Kirk Bailey wrote:

> Sokay, now try to walk it in a for loop:
> 
> for i in members:
> 	print members[1]
> 
> Gets this error:
> 
> 	
> Traceback (most recent call last):
>   File "<pyshell#119>", line 2, in ?
>     print members[i]
> TypeError: sequence index must be integer

> ok, how do I get it to walk through a loop, performing a block of code
> for each item in the list?


In your loop above:

> for i in members:
> 	print members[1]

'i' isn't a number: it's one of the lines in your member's list.  Here's
an example with the interpreter that shows a little more about this:

###
>>> three_stooges = ['larry', 'curly', 'moe']
>>> for stooge in three_stooges:
...     print "nuk nuk", stooge
... 
nuk nuk larry
nuk nuk curly
nuk nuk moe
##

So this works.


In a 'for' loop,

    for <index_variable> in <some_sequence>

the index_variable will go over the elements in some_sequence.


Hope this helps!



From shalehperry@attbi.com  Wed Dec 12 07:39:45 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 11 Dec 2001 23:39:45 -0800 (PST)
Subject: [Tutor] walking a list
In-Reply-To: <3C170497.2D5832E@my995internet.com>
Message-ID: <XFMail.20011211233945.shalehperry@attbi.com>

> 
> Sokay, now try to walk it in a for loop:
> 
> for i in members:
>       print members[1]
> 
> Gets this error:
> 
>       
> Traceback (most recent call last):
>   File "<pyshell#119>", line 2, in ?
>     print members[i]
> TypeError: sequence index must be integer
>>>>|
> 
> 
> ok, how do I get it to walk through a loop, performing a block of code
> for each item in the list?
> 

>>> l = ['s', 't', 'r']
>>> for i in l:
...     print type(i)
... 
<type 'string'>
<type 'string'>
<type 'string'>

hope this makes shows the error of your ways.



From dyoo@hkn.eecs.berkeley.edu  Wed Dec 12 07:59:36 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 11 Dec 2001 23:59:36 -0800 (PST)
Subject: [Tutor] slightly updated version of same script [string formatting]
In-Reply-To: <3C16F772.771CD015@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112112345380.16665-100000@hkn.eecs.berkeley.edu>

On Wed, 12 Dec 2001, Kirk Bailey wrote:

> Here ya go. Took out the extra crof and the testing code with the type
> statement.
> 
> Now that I can get this working, I need to go play with DIGESTING
> incoming email and examining header information. Good thing I trapped a
> few incoming letters into files in the server so I have data to feed the
> script for testing.
> 
> Any and all, feel free to examine this and comment on anything you like.


One thing that might be good to point out is the thing you were wondering
about with CRLF:

> msg = "From: " + fromaddr + CRLF + "To: " + toaddrs + CRLF + "Subject: "
> + subject + CRLF


Python supports an interesting "string formatting" operation that makes
making 'msg' a little easier.  Here's an example of string formatting:


###
>>> template_message = """%s and %s     
... went down a %s  
... to fetch a %s."""      
>>> print template_message
%s and %s
went down a %s
to fetch a %s.
>>> msg1 = template_message % ('jack', 'jill', 'hill', 'bucket of water')
>>> print msg1
jack and jill
went down a hill
to fetch a bucket of water.
###

I've always thought of this as the "Madlibs" operator.  We can take a
string that has these '%s' placeholders, and plug in values.  msg1 is the
result.  Try it out; it's quite fun.


String formatting doesn't affect our template_message, so: we can use it
over and over:

###
>>> print template_message % ('bill', 'ted', 'phone booth', 'napoleon')
bill and ted
went down a phone booth
to fetch a napoleon.
###


Of course, it's good to see what happens if we give too many or too few
things to the formatting operator:

###
>>> print template_message % ('neo', 'trinity')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: not enough arguments for format string
>>> print template_message % ('neo', 'trinity', 'morpheus', 'cypher',
                              'switch', 'tank')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: not all arguments converted
###

so we can expect to see these kinds of error messages if we mishandle the
formatting operation a little.



We can use this formatting to make the msg construction a little less
messy:

###
msg_template = """From: %s
To: %s
Subject: %s
"""
msg = msg_template % (fromaddr, toaddrs, subject)
msg = msg.replace('\n', '\r\n')
###


The line right below the string formatting is a small trick to plug in
those pesky carriage returns, so that we don't clutter up the
msg_template.


Hope this helps!



From deliberatus@my995internet.com  Wed Dec 12 08:05:55 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 03:05:55 -0500
Subject: [Tutor] breakfast of champions
Message-ID: <3C170FE3.84A52B1C@my995internet.com>

cold pizzia.

OK, here is the latest state. Can find a subscriber if they are in
there, can send a message, wax your porcupine, and almost work. Gotta
digest them rfc822 headers still. Coming along. Found the definition for
find int he on line documenting. Makes sense really, although I would
have thought there would be a search method alredy in the language, but
hey, it works.

Also must add a loop to read the subscriber file and STRIP OFF the \n on
the end of each line, and append it to the list before searching it, as
it kills the search. Pity I cannot think of  way to do that on the fly
while loading with readlines. Any suggestions?


----------woohoo----------------------------------------
#!/usr/local/bin/python
# Tinylist module, Pitchtime unit.
# this handles receiving and sending out postings to a list.

import sys, re, string, rfc822, smtplib

localhost = 'howlermonkey.net'	# make sure you set this to the domain
YOU use!!!
						# next line declares the path to stuff. DEFINE IT
pathtostuff = '/www/www.howlermonkey.net/cgi-bin/'	# to the cgi-bin for
your web dir with
						# a trailing '/' as this example shows!
						# note this tells where to start looking.
						# everything is either here, or under this
						# point in '/lists' dir.
					
					
listname = sys.argv[1]			# we read a command line arguement to determine
the list name
						# Arguement 0 is the name of the script run, 1 is the
						# first arguement.
						# after that name in the command line, so if this were
						# program FOO,
						# that line would be "|/path/FOO listname"
						# and the arguement here would be 'listname'!
					
					
message = raw_input.lines()		# Variable 'message' is assigned the entire
message
						# which is piped to the program by the alias definition
						# such as:
						# foolist:"|/pathtoprogram/programname foolist"


						# now we must determine the sender and see if they are in
						# the subscriber file!
						# still got to learn more about how this thing handles
						# parsing the incoming message, but smtp and rfc822
						# are dep sorcery on this material.

from = message["From"]			# we must dig out the 'from: ' field and read
it's contents.
						# Note we already know who it is TO - 'listname' !
						# Remember, the mail ssytem fed it here with a command
						# line arguement, after sorting it out to a known identity,
						# so the list's defining alias contains that info.
def find(str, ch):
	index = 0				# initialize counter
	while index < len(str):		# define termination condition
		if str[index] == ch:	# yes/no decision - is it there or not?
			return index	# yes, return positive value
		index = index + 1		# no, keep looking
	return -1				# field exausted, so it's not there.


open a.file(pathtostuff + "/lists/" + listname, 'r')						
members = a.readlines()			# we build a list of all the members of the
email list
a.close()					# and close the file
						# then we look to see if that FROM exists in the membership.

if find(members, from):							# IF the sender is in the subscriber, 
		subject = '[' + listname + ']' + subject		# then acept the submission.
		Reply_to = listname + "@" + localhost		# this sets the reply-to field.
		X-Loop = "X-Loop: " + listname + "@" + localhost	# This breaks email
loops from form
		ftr = b.open(pathtostuff + "/lists/" + listname + ".footer",'r') #
read the footer
		footer = ftr.readlines()				# reads the footer into the variable
		ftr.close()							# close that file,
		message = message + footer				# and append it to the message. 
	else									# BUT IF THEY ARE NOT SUBSCRIBED...
		listnamemembers = from					# put their addres as the only recipient
		message = ""						# clear the mesage.
		From = "From: tinylist@" + localhost + \n 	# From:
tinylist@mydomain.foo !
		Subject = "Subject: Unauthorized posting to list" + listname + \n
		Reply_to = "Reply-to:postmaster@" + localhost + \n # no comments
possible now!
		X-Loop = "X-Loop: postmaster@" + localhost	# This breaks email loops
from forming
		message = """
		
		To whom it may concern;
		
		Sorry, but as you are not a current member of """ + listname + """, 
		you may not post to it. Your recent posting has been rejected and
destroyed.
		
		Feel free to contact the postmaster if there is any question.
		Any reply to this letter should go directly to the postmaster.
		
		You can also subscribe to this list if you like.
		
		Goodbye.
		
		"""
		
							# there cannot be comments in those line 							# above this one,
or they would be part 							# of the triplequoted string!
							# ok, if they are not a member, THEY GET THE REPLY 							# SHOWN
ABOVE MAILED TO THEM!

							# above is a blank line, DO NOT DELETE IT!
							# there is no endif or fi in python.
							# whitespace and tabulation therefore
							# is rather important here.
							# now we send whatever message is to go out to 
							# whatever is in the recipient tupple.

server = smtplib.SMTP('localhost')
# helo(localhost)				# open a connection to the smtp server, possibly
not needed
						# so it is commented out. If all else fails, use it.

server.connect()				# and log in to the thing as the identity this
script runs as.
for each in listnamemembers :		# for each address in the list
listnamemembers,
	server.sendmail(from_addr, to_addr, Subject, reply-to, to, X-Loop, msg)
#send a envlope!

server.quit()				# then close the connection.

	
						# make sure this script runs as a TRUSTED USER-
						# and NOT as root!!! Make sure that a
						# NON-priviliged user can run this script,
						# and make sure it is owned by that identity!
					
----------------------goodnightall---------------------------

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From jrm@videotron.ca  Wed Dec 12 01:09:44 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Wed, 12 Dec 2001 03:09:44 +0200
Subject: [Tutor] Is IDLE prone to memory losses ?
Message-ID: <000f01c182a9$af64fe80$0100c0a8@videotron.ca>

OK. If I run this I get the error message following:

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

#! /usr/bin/env python

from Tkinter import *

def move():
    "déplacement de la balle"
    global x1, y1, dx, dy, flag
    x1, y1= x1 + dx, y1 + dy
    for c in range[1,6]:
        if c==5:
            c=1
        elif c==1:
            can1.itemconfigure(oval1, fill="red")
        elif c==2:
            can1.itemconfigure(oval1, fill="yellow")
        elif c==3:
            can1.itemconfigure(oval1, fill="green")
        elif c==4:
            can1.itemconfigure(oval1, fill="blue")

    if x1 > 360:
        dx, dy = -17, 17

    if y1 > 360:
        dx, dy = -17, -17

    if x1 < 10:
        dx, dy = 17, -17

    if y1 < 10:
        dx, dy = 17, 17

    can1.coords(oval1, x1, y1, x1+30,  y1+30)
    if flag > 0:
        fen1.after(1, move)        # boucler après 50 millisecondes

def stop_it():
        "arrêt de l'animation"
        global flag
        flag=0

def start_it():
        "démarrage de l'animation"
        global flag
        flag = flag+1         # préférable à flag=1 :
        if flag == 1:           # voir explications dans le texte
            move()

####################PROGRAMME PRINCIPAL#####################

# les variables suivantes seront utilisées de manière globale :
x1, y1 = 200, 0         # coordonnées initiales
dx, dy = 17, 17          # "pas" du déplacement
flag=0                  # commutateur

# Création du widget principal ("patent") :

fen1=Tk()
fen1.title("Exercice d'animation avec Tkinter")
can1=Canvas(fen1, bg="dark gray", height=400, width=400)
can1.pack(side="left")
oval1=can1.create_oval(x1, y1, x1+30, y1+30, width=2, fill="blue")
bou1=Button(fen1, text="Quitter", command=fen1.quit)
bou1.pack(side="bottom")
bou2=Button(fen1, text="Démarrer", command=start_it)
bou2.pack()
bou3=Button(fen1, text="Arrêter", command=stop_it)
bou3.pack()
# Démarrage de l'observateur d'événements (boucle principale) :
#fen1.mainloop()

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

Traceback (most recent call last):
  File "C:\Python21\Lib\lib-tk\Tkinter.py", line 1285, in __call__
    return apply(self.func, args)
  File "C:/Python21/scripts_python/animation_automatique.pyw", line 47, in
start_it
    bou1=Button(fen1, text="Quitter", command=fen1.quit)
  File "C:/Python21/scripts_python/animation_automatique.pyw", line 9, in
move
    if x1 > 360:
TypeError: unsubscriptable object

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

It has no relationship to the (yes : saved) code but only to an earlier
version to wich I added some code. Now do you gang get the same behavior
from IDLE. I recently upgraded from Python 2.0 to 2.1 so I went from IDLE
0.6 to 0.8. Never noticed that behavior before ; did you ? If so what should
I do if anything ? This bug is inconsistent : most of the time, what I
change gets saved.

Jean M.





From dyoo@hkn.eecs.berkeley.edu  Wed Dec 12 08:10:20 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 12 Dec 2001 00:10:20 -0800 (PST)
Subject: [Tutor] intresting gibberish, this. Looks like perl on the rag...
In-Reply-To: <3C164654.6F9E16BE@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112120005520.16665-100000@hkn.eecs.berkeley.edu>

On Tue, 11 Dec 2001, Kirk Bailey wrote:

> Seems I cannoy simply append a CRLF into the end of a string or a list
> or anything else, I have to play intresting games to accomplish it.

###
>>> mystr = "Hello"
>>> mystr + "\r\n"
'Hello\r\n'
###

Is this what you mean?  You don't have to do everything in one line if its
esthetically ugly.



From dyoo@hkn.eecs.berkeley.edu  Wed Dec 12 08:15:43 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 12 Dec 2001 00:15:43 -0800 (PST)
Subject: [Tutor] Is IDLE prone to memory losses ?
In-Reply-To: <000f01c182a9$af64fe80$0100c0a8@videotron.ca>
Message-ID: <Pine.LNX.4.21.0112120011250.16665-100000@hkn.eecs.berkeley.edu>

On Wed, 12 Dec 2001, Jean Montambeault wrote:

> OK. If I run this I get the error message following:
>=20
> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
>=20
> #! /usr/bin/env python
>=20
> from Tkinter import *
>=20
> def move():
>     "d=E9placement de la balle"
>     global x1, y1, dx, dy, flag
>     x1, y1=3D x1 + dx, y1 + dy
>     for c in range[1,6]:
               ^^^^^^^^^^

There is something very suspicious about this line: I just tried this in
the interpreter, and:

###
>>> for c in range[1, 6]:
=2E..     print c
=2E..=20
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsubscriptable object
###


And this fits closely with the TypeError message that you were getting:

> TypeError: unsubscriptable object


I believe you meant to call the range() function instead:

###
>>> for c in range(1, 6):
=2E..     print c
=2E..=20
1
2
3
4
5
###

Be aware, though, that range(1, 6) goes from 1 to 6, but not including 6.


However, I don't know if this is the whole story, since your error message
still looked very strange to me.  Hmmm... Try to fix the subscripting
problem above, and see if that clears things up for you.


Best of wishes to you.




From deliberatus@my995internet.com  Wed Dec 12 08:18:16 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 03:18:16 -0500
Subject: [Tutor] gangstrip
Message-ID: <3C1712C8.AFF18FA9@my995internet.com>

Allright, EVERYBODY STRIP!

--------------------------------------------------------------
#!/usr/local/bin/python
# Tinylist module, Pitchtime unit.
# this handles receiving and sending out postings to a list.

import sys, re, string, rfc822, smtplib

localhost = 'howlermonkey.net'	# make sure you set this to the domain
YOU use!!!
						# next line declares the path to stuff. DEFINE IT
pathtostuff = '/www/www.howlermonkey.net/cgi-bin/'	# to the cgi-bin for
your web dir with
						# a trailing '/' as this example shows!
						# note this tells where to start looking.
						# everything is either here, or under this
						# point in '/lists' dir.
					
					
listname = sys.argv[1]			# we read a command line arguement to determine
the list name
						# Arguement 0 is the name of the script run, 1 is the
						# first arguement.
						# after that name in the command line, so if this were
						# program FOO,
						# that line would be "|/path/FOO listname"
						# and the arguement here would be 'listname'!
					
					
message = raw_input.lines()		# Variable 'message' is assigned the entire
message
						# which is piped to the program by the alias definition
						# such as:
						# foolist:"|/pathtoprogram/programname foolist"


						# now we must determine the sender and see if they are in
						# the subscriber file!
						# still got to learn more about how this thing handles
						# parsing the incoming message, but smtp and rfc822
						# are dep sorcery on this material.

from = message["From"]			# we must dig out the 'from: ' field and read
it's contents.
						# Note we already know who it is TO - 'listname' !
						# Remember, the mail ssytem fed it here with a command
						# line arguement, after sorting it out to a known identity,
						# so the list's defining alias contains that info.
def find(str, ch):
	index = 0				# initialize counter
	while index < len(str):		# define termination condition
		if str[index] == ch:	# yes/no decision - is it there or not?
			return index	# yes, return positive value
		index = index + 1		# no, keep looking
	return -1				# field exausted, so it's not there.

def gangstrip(str):			# ok, everybody STRIP! STR is a list variable
	index = 0				# We want to strip off all leading and
	while index<len(str)		# trailing whitespace characters
	str[index]=string.strip(str[index])	# in each element in the list.

open a.file(pathtostuff + "/lists/" + listname, 'r')						
members = a.readlines()			# we build a list of all the members of the
email list
a.close()					# and close the file
						# then we look to see if that FROM exists in the membership.

gangstrip(members)			# strip all leading and trailing whitespace
						# from each element in the list 'members'.

if find(members, from):							# IF the sender is in the subscriber, 
		subject = '[' + listname + ']' + subject		# then acept the submission.
		Reply_to = listname + "@" + localhost		# this sets the reply-to field.
		X-Loop = "X-Loop: " + listname + "@" + localhost	# This breaks email
loops from form
		ftr = b.open(pathtostuff + "/lists/" + listname + ".footer",'r') #
read the footer
		footer = ftr.readlines()				# reads the footer into the variable
		ftr.close()							# close that file,
		message = message + footer				# and append it to the message. 
	else									# BUT IF THEY ARE NOT SUBSCRIBED...
		listnamemembers = from					# put their addres as the only recipient
		message = ""						# clear the mesage.
		From = "From: tinylist@" + localhost + \n 	# From:
tinylist@mydomain.foo !
		Subject = "Subject: Unauthorized posting to list" + listname + \n
		Reply_to = "Reply-to:postmaster@" + localhost + \n # no comments
possible now!
		X-Loop = "X-Loop: postmaster@" + localhost	# This breaks email loops
from forming
		message = """
		
		To whom it may concern;
		
		Sorry, but as you are not a current member of """ + listname + """, 
		you may not post to it. Your recent posting has been rejected and
destroyed.
		
		Feel free to contact the postmaster if there is any question.
		Any reply to this letter should go directly to the postmaster.
		
		You can also subscribe to this list if you like.
		
		Goodbye.
		
		"""
		
							# there cannot be comments in those line 							# above this one,
or they would be part 							# of the triplequoted string!
							# ok, if they are not a member, THEY GET THE REPLY 							# SHOWN
ABOVE MAILED TO THEM!

							# above is a blank line, DO NOT DELETE IT!
							# there is no endif or fi in python.
							# whitespace and tabulation therefore
							# is rather important here.
							# now we send whatever message is to go out to 
							# whatever is in the recipient tupple.

server = smtplib.SMTP('localhost')
# helo(localhost)				# open a connection to the smtp server, possibly
not needed
						# so it is commented out. If all else fails, use it.

server.connect()				# and log in to the thing as the identity this
script runs as.
for each in listnamemembers :		# for each address in the list
listnamemembers,
	server.sendmail(from_addr, to_addr, Subject, reply-to, to, X-Loop, msg)
#send a envlope!

server.quit()				# then close the connection.

	
						# make sure this script runs as a TRUSTED USER-
						# and NOT as root!!! Make sure that a
						# NON-priviliged user can run this script,
						# and make sure it is owned by that identity!
					
--------------you can get dressed now----------------------
-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Wed Dec 12 08:20:51 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 03:20:51 -0500
Subject: [Tutor] intresting gibberish, this. Looks like perl on the rag...
References: <Pine.LNX.4.21.0112120005520.16665-100000@hkn.eecs.berkeley.edu>
Message-ID: <3C171363.CCACB943@my995internet.com>

I got it licked. 

This project is coming along rather pleasantly, I still have hairs left
to pull out.

Now to grok rfc822, but that's tommrow's grovel...

any introductory lectures on rfc822 would be well received.


Danny Yoo wrote:
> 
> On Tue, 11 Dec 2001, Kirk Bailey wrote:
> 
> > Seems I cannoy simply append a CRLF into the end of a string or a list
> > or anything else, I have to play intresting games to accomplish it.
> 
> ###
> >>> mystr = "Hello"
> >>> mystr + "\r\n"
> 'Hello\r\n'
> ###
> 
> Is this what you mean?  You don't have to do everything in one line if its
> esthetically ugly.

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Wed Dec 12 08:22:35 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 03:22:35 -0500
Subject: [Tutor] Free SoCal LAN
References: <3C169CCF.4080709@venix.com> <00e001c182de$92ea6530$6e01a8c0@praxis>
Message-ID: <3C1713CB.5C211B85@my995internet.com>

Hot DAMN! where?

Tron wrote:
> 
> I dig free what about you guys?  Just wanted to let anyone know if they
> wanted to take a break from coding or even share some knowledge.
> 
>     Sub Matrix is throwing a Lan Party December 28th through the 30th. Best
> part of it the lan is it is totally free. We will have a ton of soda, food,
> and the admission is waived for the whole weekend. I will be putting up a
> sign up page on our web site Wednesday so you can register. If we are full
> by next Wednesday I will be able to look into getting some prizes for a few
> tournaments.
> 
> Location:Hat Lan www.hatlan.com
> Price:Free
> Soda/Food:Included
> Opennings:70-80
> Register:www.submatrix.com/lanparty
> Contact:Tron@submatrix.com
> 
> -Tron
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From dyoo@hkn.eecs.berkeley.edu  Wed Dec 12 08:32:46 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 12 Dec 2001 00:32:46 -0800 (PST)
Subject: [Tutor] breakfast of champions [pydoc/overcommenting?/functions]
In-Reply-To: <3C170FE3.84A52B1C@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112120016100.16665-100000@hkn.eecs.berkeley.edu>

On Wed, 12 Dec 2001, Kirk Bailey wrote:

> cold pizzia.

Don't stay up too late.  *grin* I'm jealous; I have to wake up earlier
tomorrow.  Eat some veggies too.


> digest them rfc822 headers still. Coming along. Found the definition for
> find int he on line documenting. Makes sense really, although I would
> have thought there would be a search method alredy in the language, but
> hey, it works.

There is something of a search method in the 'pydoc' module.  After
importing the pydoc module, try typing:

###
pydoc.help('string')
###

from an interpreter, and you should see a bunch of help.


In fact, strings already have a find() function:

###
>>> pydoc.help('string.find')
Help on function find in string:

find(s, *args)
    find(s, sub [,start [,end]]) -> in
    
    Return the lowest index in s where substring sub is found,
    such that sub is contained within s[start,end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.
###

so you can just use it: you don't have to define it again.



> Also must add a loop to read the subscriber file and STRIP OFF the \n
> on the end of each line, and append it to the list before searching
> it, as it kills the search. Pity I cannot think of way to do that on
> the fly while loading with readlines. Any suggestions?

You'll like this one: you can use a string.replace() to remove '\n's from
a string that you're reading.  For example:

###
>>> s = 'this is a string\n\nwith newlines\n'    
>>> import string
>>> string.replace(s, '\n', '')
'this is a stringwith newlines'
###




It's my personal opinion that your code has way too many comments.  
*grin* I think that things like:


> localhost = 'howlermonkey.net' # make sure you set this to the domain
                                 # YOU use!!!


are fine, but that:


> listname = sys.argv[1]	# we read a command line arguement to
                                # determine the list name
				# Arguement 0 is the name of
				# the script run, 1 is the
				# first arguement.
				# after that name in the command line,
				# so if this were program FOO,
				# that line would be "|/path/FOO listname"
				# and the arguement here would be 'listname'!

and examples like that are overkill.  These are just an opinion though, so
don't take me too seriously on this.


You have a large portion of code that begins here:


> 		subject = '[' + listname + ']' + subject		# then acept the submission.
> 		Reply_to = listname + "@" + localhost		# this sets the reply-to field.
[... code cut]


that may be a prime candidate for a function --- it could be something
that constructsMessage() or something to that effect.



From deliberatus@my995internet.com  Wed Dec 12 08:33:45 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 03:33:45 -0500
Subject: [Tutor] tinylist project
References: <3C169CCF.4080709@venix.com> <00e001c182de$92ea6530$6e01a8c0@praxis> <3C1713CB.5C211B85@my995internet.com>
Message-ID: <3C171669.45E9DD47@my995internet.com>

ok, this is coming along.

I am now moving into refresh mode, cause I'm pooped. Thank you one and
all for helpful suggestions, and when it is done, I want to give all of
you credit who contribuited to the effort.

When the post time module is done, next is management, mail and web.

Then comes the fun part, DYNAMIC FOOTER CONTENT.

AIIIEEEEEE.......

Can you say ssi for email?


From glingl@aon.at  Wed Dec 12 08:46:53 2001
From: glingl@aon.at (Gregor Lingl)
Date: Wed, 12 Dec 2001 09:46:53 +0100
Subject: [Tutor] Is IDLE prone to memory losses ?
References: <Pine.LNX.4.21.0112120011250.16665-100000@hkn.eecs.berkeley.edu>
Message-ID: <010301c182e9$8c5becb0$1664a8c0@mega>

----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "Jean Montambeault" <jrm@videotron.ca>
Cc: <tutor@python.org>
Sent: Wednesday, December 12, 2001 9:15 AM
Subject: Re: [Tutor] Is IDLE prone to memory losses ?


On Wed, 12 Dec 2001, Jean Montambeault wrote:

> OK. If I run this I get the error message following:
>
> ====================================
>
> #! /usr/bin/env python
>
> from Tkinter import *
>
> def move():
>     "déplacement de la balle"
>     global x1, y1, dx, dy, flag
>     x1, y1= x1 + dx, y1 + dy
>     for c in range[1,6]:
               ^^^^^^^^^^

There is something very suspicious about this line: I just tried this in
the interpreter, and:

###
>>> for c in range[1, 6]:
...     print c
...
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsubscriptable object
###


And this fits closely with the TypeError message that you were getting:

> TypeError: unsubscriptable object

.... since your error message
still looked very strange to me.  Hmmm... Try to fix the subscripting
problem above, and see if that clears things up for you.

I think this is the whole story. The error-message means - in my opinion -
that range is not a subscriptable object:

>>> type(range)
<type 'builtin_function_or_method'>
>>>

subscription means getting acces to an element of some compund data object
via an index,
as is possible for strings, lists etc. This is of course not possible for a
built-in functin as range()
(but this is what you tried by range[])

See also: http://www.python.org/doc/current/ref/assignment.html

hope that "clears things up"
Gregor




From deliberatus@my995internet.com  Wed Dec 12 09:03:36 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 04:03:36 -0500
Subject: [Tutor] string.find is odd
References: <Pine.LNX.4.21.0112120011250.16665-100000@hkn.eecs.berkeley.edu> <010301c182e9$8c5becb0$1664a8c0@mega>
Message-ID: <3C171D68.A7B7236C@my995internet.com>

Messing with string.find;
much confused, the process I wrote worked, dhis is barking. LOOK:

>>> members
['I', 'You', 'He', 'She', 'It', 'We', 'you', 'They']
>>> string.find("it",members)
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in ?
    string.find("it",members)
  File "C:\PYTHON21\lib\string.py", line 171, in find
    return s.find(*args)
TypeError: expected a character buffer object
>>> string.find(members,"It")
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in ?
    string.find(members,"It")
  File "C:\PYTHON21\lib\string.py", line 171, in find
    return s.find(*args)
AttributeError: find
>>>|

ok, I want to searh through a list, and return a non negative value
(='TRUE') if the search object is found.
The searched list is called 'Members'.
The search object is a string variable named 'From'.
arg...

Good night.


From kalle@gnupung.net  Wed Dec 12 09:31:33 2001
From: kalle@gnupung.net (Kalle Svensson)
Date: Wed, 12 Dec 2001 10:31:33 +0100
Subject: [Tutor] string.find is odd
In-Reply-To: <3C171D68.A7B7236C@my995internet.com>
References: <Pine.LNX.4.21.0112120011250.16665-100000@hkn.eecs.berkeley.edu> <010301c182e9$8c5becb0$1664a8c0@mega> <3C171D68.A7B7236C@my995internet.com>
Message-ID: <20011212103133.B7672@proton.lysator.liu.se>

[Kirk Bailey]

> ok, I want to searh through a list, and return a non negative value
> (='TRUE') if the search object is found.
> The searched list is called 'Members'.
> The search object is a string variable named 'From'.
> arg...

>>> members
['I', 'You', 'He', 'She', 'It', 'We', 'you', 'They']
>>> "It" in members
1
>>> "it" in members
0
>>> "frobitous".find("it") # this is how the .find method works.
4
>>> "frobitous".find("It")
-1

> Good night.

Good morning,
  Kalle
-- 
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]


From alan.gauld@bt.com  Wed Dec 12 10:40:08 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 12 Dec 2001 10:40:08 -0000
Subject: [Tutor] Pythonwin strangeness
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C19B@mbtlipnt02.btlabs.bt.co.uk>

Its been a while since I used the Pythonwin IDE but when 
I tried to start it it now gives me this error:

 File "<string>", line 1, in ?
exceptions.ImportError: No module named framework.startup

And refuses to start.

Now it definitely used to work but not now, so presumably 
its something I've done, but what?

BTW it's BeOpen Python 2.0 with win32all-134
- Just checked and thats the wrong version, looks like 
I forgot to upgrade winall when I did Python 2.0!

OK upgraded to win32all-138 but still get exactly the same.

Any ideas folks?

Alan G


From alan.gauld@bt.com  Wed Dec 12 12:21:05 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 12 Dec 2001 12:21:05 -0000
Subject: [Tutor] .cgi or .py for Python CGIs
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1A2@mbtlipnt02.btlabs.bt.co.uk>

> On  0, Frank Peavy <fpeavy@pop.net> wrote:
> > I have seen references to various CGI scripts and some have 
> > the .cgi extension and some have a .py extension. Which is correct? 

It depends on the Web server in use.

Normally if CGI programs are all stored under a cgi-bin folder then 
the .py extention is used but if the server has been set to execute 
any program ending .cgi regardless of location then .cgi must be used.

In the latter case the program to execute is usually referenced in 
the first line of the .cgi file using something very like the Unix 
hash-bang trick.

Apache and Xitami are the two web servers I know best and they both 
do either form of setup on both Windows and Unixd platforms.


Alan g.


From alan.gauld@bt.com  Wed Dec 12 12:38:52 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 12 Dec 2001 12:38:52 -0000
Subject: [Tutor] You're gridded for life.
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1A3@mbtlipnt02.btlabs.bt.co.uk>

> tom_dee_lee_dum=Entry(fen).grid(row=0, column=0)
> tom_dee_lee_dum.bind("<Return>", here_I_am)

As I pointed out in my earlier post the grid() method 
returns None

Thus if you want to keep a reference to the widget you have 
to create it and then pack() or grid() it.

> tom_dee_lee_dum=Entry(fen)
> tom_dee_lee_dum.grid(row=0, column=0)
> tom_dee_lee_dum.bind("<Return>", here_I_am)

Just like that....

> So my question : is the shortcut technique only good for the 
> widgets that aren't assigned to a variable

Yes.

> This snag costed me two hours of my life 

Hmm, I did point it out last week in my original response...

The Tkinter introduction also majkes the point explicitly
http://www.pythonware.com/library/tkinter/introduction/

in section 3 "More on widget references"

I recommend Tkinter beginners go through this tutor.


> some selected curses, these very graphical ; in no tutorial 
> is "extreme tolerance to frustration" ever mentionned among 
> the qualities that make a good programmer but it really should. 

Actually I do mention that in my book :-)

Alan G.


From lsloan@umich.edu  Wed Dec 12 12:49:33 2001
From: lsloan@umich.edu (Lance E Sloan)
Date: Wed, 12 Dec 2001 07:49:33 -0500
Subject: [Tutor] .cgi or .py for Python CGIs
In-Reply-To: Your message of "Tue, 11 Dec 2001 09:16:19 PST."
 <5.1.0.14.0.20011211091442.00a978d0@mail45566.popserver.pop.net>
Message-ID: <200112121249.HAA05824@birds.us.itd.umich.edu>

Frank Peavy wrote:
> I have seen references to various CGI scripts and some have the .cgi 
> extension and some have a .py extension. Which is correct? Is there a 
> preferred method?

As others have said, it usually depends on the webserver.  Here at
U-Michigan, we prefer to use no extension at all.  We use only Apache
servers on Sun Solaris machines and we don't allow average users to
write their own CGIs.  (Well, they can write them, but we won't run
them.)  For each "site" we create, they have their own cgi-bin and
cgi-ssl directories and the server is configured to run anything in
those directories.

--
Lance E Sloan
Web Services, Univ. of Michigan: Full-service Web and database design,
development, and hosting.  Specializing in Python & Perl CGIs.
http://websvcs.itd.umich.edu/ - "Putting U on the Web"


From alan.gauld@bt.com  Wed Dec 12 13:38:48 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 12 Dec 2001 13:38:48 -0000
Subject: [Tutor] smtoplib script appears bogus
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1A4@mbtlipnt02.btlabs.bt.co.uk>

> This thing don't work. Beats me why, I copied it from the on line docs
> for the language, but there ya go.

Kirk,

It would help a lot if you gave more info about what exactly happens. 
It "don't work" could mean it doesn't run, or it runs but produces no 
output, or it runs and the output is not what you expect.

Is there an error message? If so cut n paste it into the message.
If its bad output explain what you get and what you expect.

Just saying it doesn't work leaves the readers with an awful 
lot of work to do! Likely they just will not bother....

Alan g.




From scott@zenplex.com  Wed Dec 12 14:56:21 2001
From: scott@zenplex.com (Scott Comboni)
Date: 12 Dec 2001 09:56:21 -0500
Subject: [Tutor] Loggin info to syslog?
Message-ID: <1008168986.1685.22.camel@scoot.zenplex.com>

Is there a simple way to log info to syslog?   
Scott





From kalle@gnupung.net  Wed Dec 12 16:54:16 2001
From: kalle@gnupung.net (Kalle Svensson)
Date: Wed, 12 Dec 2001 17:54:16 +0100
Subject: [Tutor] Loggin info to syslog?
In-Reply-To: <1008168986.1685.22.camel@scoot.zenplex.com>
References: <1008168986.1685.22.camel@scoot.zenplex.com>
Message-ID: <20011212175416.C10409@proton.lysator.liu.se>

[Scott Comboni]
> Is there a simple way to log info to syslog?   

Yes, use the syslog module.  Check out
http://www.python.org/doc/current/lib/module-syslog.html

Peace,
  Kalle
-- 
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]


From jrm@videotron.ca  Wed Dec 12 09:59:24 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Wed, 12 Dec 2001 11:59:24 +0200
Subject: [Tutor] Is IDLE prone to memory losses ?
References: <Pine.LNX.4.21.0112120011250.16665-100000@hkn.eecs.berkeley.edu>
Message-ID: <004201c182f3$add89280$0100c0a8@videotron.ca>

----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "Jean Montambeault" <jrm@videotron.ca>

>However, I don't know if this is the whole story, since your error message
>still looked very strange to me.  Hmmm... Try to fix the subscripting
>problem above, and see if that clears things up for you.

That is the point : instead of telling me about the real mistake I made it
says that :
    "if x1 >360:"  is on line 9,  where it actually was _before_ I made the
change, but isn't anymore, far from it. Now, if I close the editing window
and reopen it, run the script, I'll get an error message just like the one
you got and that makes sense.
    Maybe I should have used correct code instead : I tought that the
inconsistency in the error message was showing the problem more clearly, my
mistake.

Jean M.



From sgeorge@vianetworks.co.uk  Wed Dec 12 12:06:29 2001
From: sgeorge@vianetworks.co.uk (Steve George)
Date: 12 Dec 2001 12:06:29 +0000
Subject: [Tutor] sys.path..... - PATH, one more time...
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C182@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C182@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <1008158790.816.10.camel@laptop>

Hi,

It is a way of altering your sys.path without having to use a
PYTHONPATH.  So for example if I had some packages in
/home/steve/pymodules I could add them to my python startup by forming a
file in /usr/lib/python1.5/site-packages called something like
mysite.pth  in the file I would just list the directory location for my
modules.

Here's the formal explanation:
http://www.python.org/doc/current/lib/module-site.html

Daryl Harms and Kenneth McDonald provide an explanation of the options
here:
http://www.wdvl.com/Authoring/Languages/Python/Quick/python2_2.html

Cheers,

Steve

On Fri, 2001-12-07 at 09:35, alan.gauld@bt.com wrote:
> > There's also the .pth extension in Windows.  You can list
> > directories there which you want 'import xxx' to search/find.
> 
> What's this then? Its new to me. 
> Can you expand Kirby?
> 
> Alan G.
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor




From lkvam@venix.com  Wed Dec 12 14:19:59 2001
From: lkvam@venix.com (Lloyd Kvam)
Date: Wed, 12 Dec 2001 09:19:59 -0500
Subject: [Tutor] web site redirection to Python script
References: <Pine.LNX.4.21.0112111621150.9523-100000@hkn.eecs.berkeley.edu>
Message-ID: <3C17678F.1020702@venix.com>

Danny Yoo wrote:

> On Tue, 11 Dec 2001, Lloyd Kvam wrote:
> 
> 
>>I wrote some python scripts for reporting survey results from an SQL
>> ...
> ...



> But perhaps you might want to make this more transparent, so that the user
> is never aware of PythonServer's existance; that is, maybe we want
> something like this:
> 
>     PC/Browser <-----> www.HowsYourHealth.org <-----> PythonServer
> 

Keeping the PythonServer hidden in the background would make everyone happier.  BUT
getting this working is the top priority.  We're giving up on waiting for the ISP
to install Python.  I will start with the Perl redirect and see how far I get.

Google searches turn up rfc2616 and lots of cache and proxy references which is why
I tried looking for help here. Thanks.

-- 
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  Wed Dec 12 17:21:46 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 12 Dec 2001 17:21:46 -0000
Subject: [Tutor] Is IDLE prone to memory losses ?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1AB@mbtlipnt02.btlabs.bt.co.uk>

> That is the point : instead of telling me about the real 
> mistake I made it
> says that :
>     "if x1 >360:"  is on line 9,  where it actually was 
> _before_ I made the change, but isn't anymore, far from it. 


> Now, if I close the editing window and reopen it, run the script, 
> I'll get an error message just like the one
> you got and that makes sense.

I wonder....

Are you by any chance running your script by importing it into 
the interactive window in IDLE?

If so the changes you make in the editor won't show up until 
you reload() the module. That might explain the behaviour you see.

Just a guess.

If I'm right be aware that reload has some quirks to watch out 
for, in particular it only works if you do:

import foo

not if you do:

from foo import *

Also if you remove a definiton from a loaded module and reload 
the old definition will probably still be there!

I usually find it easier (ie safer!) to create the module with 
a stanza like:

if __name__ = "__Main__":
   # test the program here

at the end. 
That way I run it from IDLE using the CTRL-F5 key and there are 
no import artifacts left over

OTOH If you are already doing that then I don't know whats 
happened.

Alan g.


From jrm@videotron.ca  Wed Dec 12 10:34:23 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Wed, 12 Dec 2001 12:34:23 +0200
Subject: [Tutor] You're gridded for life.
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1A3@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <004a01c182f8$90deb7e0$0100c0a8@videotron.ca>

----- Original Message -----
From: <alan.gauld@bt.com>

>
> As I pointed out in my earlier post the grid() method
> returns None
>
Sorry, I guess that I did not understand all the implications of what you
said back then. Somebody like me, with no prior computer science education,
doesn't simply "read" docs : I have to litterally plow through it, trying to
comprehend whatever is fortunately in my grasp but mostly trying to remember
dozens of concepts that are still gibberish because they haven't been
properly introduced yet with the hope that it will all make sense when I'll
know more. After just a few introductory tutorials like yours, "Thinking
like a computer scientist" and other good ones my shell is still quite soft
and I'll need quite a lot of coding experience to avoid such obvious
mistakes.
    I'm not worried though : as a cabinetmaker of years I've seen too many
bright young persons land fresh from their three years college education
(here we have college before university) who, to their surprise, have quite
a few years to go before being able to calmly cruise through the trade like
old wolves like me are doing.
    I'll do better next time.

P.S. Thanks for returning my cat, although shaving him to look like a lion
was a bad joke.

;)

Jean M.



From jeff@ccvcorp.com  Wed Dec 12 17:51:17 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed, 12 Dec 2001 09:51:17 -0800
Subject: [Tutor] Is IDLE prone to memory losses ?
References: <E16E4hK-0008PN-00@mail.python.org>
Message-ID: <3C179915.D3B9E581@ccvcorp.com>

"Jean Montambeault" <jrm@videotron.ca> wrote:

> It has no relationship to the (yes : saved) code but only to an earlier
> version to wich I added some code. Now do you gang get the same behavior
> from IDLE. I recently upgraded from Python 2.0 to 2.1 so I went from IDLE
> 0.6 to 0.8. Never noticed that behavior before ; did you ? If so what should
> I do if anything ? This bug is inconsistent : most of the time, what I
> change gets saved.

This happens to me periodically in PythonWin as well, so it may not be a specific IDLE bug, or it may be something that was borrowed from PythonWin during the upgrade from
0.6 to 0.8  ;)

Anyhow, I think that it's a matter of display only.  I've noticed that when I search for the line number that the traceback gives me, I find the error there, but it's *not*
the line that's displayed.  For instance, I counted nine lines from the start of your file, and that's where the "for c in range[1,6]:" line was.  I do not know why IDLE is
displaying the wrong text for that line, though.  I suspect that it's keeping a copy of an old version in memory, and displaying from that, but this is just a wild guess.
Hm, if we pulled out that whole for-loop, then line 9 should be the following "if x1 > 360:" test, which is what the traceback shows... that seems to fit my theory, anyhow.
;)  Did you just add that whole loop, then save & run it and got that error?

Perhaps this should be reported as a bug in IDLE?

Jeff Shannon
Technician/Programmer
Credit International




From jrm@videotron.ca  Wed Dec 12 10:48:54 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Wed, 12 Dec 2001 12:48:54 +0200
Subject: [Tutor] Is IDLE prone to memory losses ?
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1AB@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <005201c182fa$984247c0$0100c0a8@videotron.ca>

----- Original Message -----
From: <alan.gauld@bt.com>

> Are you by any chance running your script by importing it into
> the interactive window in IDLE?

No, the editing window : most of the time I make my changes, save and run
(ctrl+f5) without experiencing any problem of the sort.

>
> If so the changes you make in the editor won't show up until
> you reload() the module. That might explain the behaviour you see.
> If I'm right be aware that reload has some quirks to watch out
> for, in particular it only works if you do:
>
> import foo
>
> not if you do:
>
> from foo import *
>
> Also if you remove a definiton from a loaded module and reload
> the old definition will probably still be there!
>
> I usually find it easier (ie safer!) to create the module with
> a stanza like:
>
> if __name__ = "__Main__":
>    # test the program here
>
> at the end.
> That way I run it from IDLE using the CTRL-F5 key and there are
> no import artifacts left over
>
> OTOH If you are already doing that then I don't know whats
> happened.
>
> Alan g.

    That make two of us except that my ignorance is compounded by the fact
that I just don't have a clue about what you all said there. I'll save  it
and come back to it once I'll speak that language.

    Don't stop trying though Alan !

    Thanks. I'm going back to do some basic education now.

    Jean M





From jrm@videotron.ca  Wed Dec 12 11:00:30 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Wed, 12 Dec 2001 13:00:30 +0200
Subject: [Tutor] Is IDLE prone to memory losses ?
References: <E16E4hK-0008PN-00@mail.python.org> <3C179915.D3B9E581@ccvcorp.com>
Message-ID: <006e01c182fc$36fcef40$0100c0a8@videotron.ca>

----- Original Message -----
From: "Jeff Shannon" <jeff@ccvcorp.com>
>
> This happens to me periodically in PythonWin as well, so it may not be a
specific IDLE bug, or it may be something that was borrowed from PythonWin
during the upgrade from
> 0.6 to 0.8  ;)

> the line that's displayed.  For instance, I counted nine lines from the
start of your file, and that's where the "for c in range[1,6]:" line was.  I
do not know why IDLE is
> displaying the wrong text for that line, though.  I suspect that it's
keeping a copy of an old version in memory, and displaying from that, but
this is just a wild guess.

    There : already finding someone that can repeat the experience helps a
lot. I can work around a bug while I can't around a mistake that I'd make
without being aware that I do.

> ;)  Did you just add that whole loop, then save & run it and got that
error?

    Yes. Things get adjusted when I close the editing window I was using and
then reopen it.

>
> Perhaps this should be reported as a bug in IDLE?

    To do the right thing... hmmmmm...

>
> Jeff Shannon

    Thank you Jeff Shannon : it helped a lot.

Jean M.




From Bruce.Lee-Shanok@cognos.com  Wed Dec 12 18:29:14 2001
From: Bruce.Lee-Shanok@cognos.com (Lee-Shanok, Bruce)
Date: Wed, 12 Dec 2001 13:29:14 -0500
Subject: [Tutor] Python threads vs C threads
Message-ID: <FB15E670DA55D51185350008C786514A0140EB68@sottexch1.cognos.com>

I am currently running into a small problem regarding network access calls
and threading.

Basically, I've wrapped a library whose interface closely resembles Berkeley
socket interface such that the calls can be made from within Python.

Now, I have already written a client and server for this interface in C.
What I've done is created a main thread that runs an Accept call, and upon
completion of an Accept call starts another thread send/receive thread and
immediately loops around to call accept again. So:

while (1)
{
	accept(&connection, socket);
	// make new thread
	srthread = new srthread(connection);
	srthread->start();	
}

The send/receive thread does just that, sends and receives on that given
connection, while the main thread sits on the accept call waiting for any
new incoming connections.

My problem is that coding this in Python doesn't work, presumably because of
this cooperative threading stuff.. since the Accept is actually a call
outside of Python, what I have is the creation of an sr thread, followed by
the program halting after the second accept (since there is no second
connection incoming)..

Is there any way to circumvent this? Maybe by tricking Python into treating
my Accept call as something that can be interrupted? Or is there a
particular "Python" way to perform this? The issue here is that I need to
use this particular library, so using any existing functionality within
Python that supports sockets isn't an option.

Thanks,
Bruce

This message may contain privileged and/or confidential information.  If you
have received this e-mail in error or are not the intended recipient, you
may not use, copy, disseminate, or distribute it; do not open any
attachments, delete it immediately from your system and notify the sender by
e-mail promptly that you have done so.  Thank You.


From dsh8290@rit.edu  Wed Dec 12 18:52:06 2001
From: dsh8290@rit.edu (dman)
Date: Wed, 12 Dec 2001 13:52:06 -0500
Subject: [Tutor] web site redirection to Python script
In-Reply-To: <3C17678F.1020702@venix.com>; from lkvam@venix.com on Wed, Dec 12, 2001 at 09:19:59AM -0500
References: <Pine.LNX.4.21.0112111621150.9523-100000@hkn.eecs.berkeley.edu> <3C17678F.1020702@venix.com>
Message-ID: <20011212135206.A28573@harmony.cs.rit.edu>

On Wed, Dec 12, 2001 at 09:19:59AM -0500, Lloyd Kvam wrote:
| Danny Yoo wrote:
| 
| > But perhaps you might want to make this more transparent, so that the user
| > is never aware of PythonServer's existance; that is, maybe we want
| > something like this:
| > 
| >     PC/Browser <-----> www.HowsYourHealth.org <-----> PythonServer
| > 
| 
| Keeping the PythonServer hidden in the background would make
| everyone happier. 

In python-pseudocode, I imagine that the following would work

import urllib
f = urllib.open( "http://the_real_server.com/path_to_cgi.py?" +
                    "rebuild the form submission URL" )
print f.read()
f.close()


I don't know enough perl to know how to do this in perl.

-D

-- 

Failure is not an option.  It is bundled with the software.



From deliberatus@my995internet.com  Wed Dec 12 18:51:27 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 13:51:27 -0500
Subject: [Tutor] smtoplib script appears bogus
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1A4@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3C17A72F.B9C563E1@my995internet.com>

I got it working, posted results last night, complete listing of the
program that works perfect.



alan.gauld@bt.com wrote:
> 
> > This thing don't work. Beats me why, I copied it from the on line docs
> > for the language, but there ya go.
> 
> Kirk,
> 
> It would help a lot if you gave more info about what exactly happens.
> It "don't work" could mean it doesn't run, or it runs but produces no
> output, or it runs and the output is not what you expect.
> 
> Is there an error message? If so cut n paste it into the message.
> If its bad output explain what you get and what you expect.
> 
> Just saying it doesn't work leaves the readers with an awful
> lot of work to do! Likely they just will not bother....
> 
> Alan g.
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Wed Dec 12 19:19:50 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 14:19:50 -0500
Subject: [Tutor] further bibbling regarding list management
Message-ID: <3C17ADD6.4CE9548F@my995internet.com>

ok, newest state of the artless:
---------------------*beware wordwrap!*----------------------
#!/usr/local/bin/python
# Tinylist module, Pitchtime unit.
# this handles receiving and sending out postings to a list.

import sys, re, string, rfc822, smtplib

localhost = 'howlermonkey.net'	# make sure you set this to the domain
YOU use!!!
						# next line declares the path to stuff. DEFINE IT
pathtostuff = '/www/www.howlermonkey.net/cgi-bin/'	# to the cgi-bin for
your web dir with
						# a trailing '/' as this example shows!
						# note this tells where to start looking.
						# everything is either here, or under this
						# point in '/lists' dir.
					
					
listname = sys.argv[1]			# we read a command line arguement to determine
the list name
						# Arguement 0 is the name of the script run, 1 is the
						# first arguement.
						# after that name in the command line, so if this were
						# program FOO,
						# that line would be "|/path/FOO listname"
						# and the arguement here would be 'listname'!
					
					
message = raw_input.lines()		# Variable 'message' is assigned the entire
message
						# which is piped to the program by the alias definition
						# such as:
						# foolist:"|/pathtoprogram/programname foolist"


						# now we must determine the sender and see if they are in
						# the subscriber file!
						# still got to learn more about how this thing handles
						# parsing the incoming message, but smtp and rfc822
						# are dep sorcery on this material.

from = message["From"]			# we must dig out the 'from: ' field and read
it's contents.
						# Note we already know who it is TO - 'listname' !
						# Remember, the mail ssytem fed it here with a command
						# line arguement, after sorting it out to a known identity,
						# so the list's defining alias contains that info.

def gangstrip(str):			# ok, everybody STRIP! STR is a list variable
	index = 0				# We want to strip off all leading and
	while index<len(str)		# trailing whitespace characters
	str[index]=string.strip(str[index])	# in each element in the list.

open a.file(pathtostuff + "/lists/" + listname, 'r')						
members = a.readlines()			# we build a list of all the members of the
email list
a.close()					# and close the file
						# then we look to see if that FROM exists in the membership.

gangstrip(members)			# strip all leading and trailing whitespace
						# from each element in the list 'members'.

if from in members :			# IF the sender is in the subscriber, 
		subject = '[' + listname + ']' + subject		# then acept the submission.
		Reply_to = listname + "@" + localhost		# this sets the reply-to field.
		X-Loop = "X-Loop: " + listname + "@" + localhost	# This breaks email
loops from form
		ftr = b.open(pathtostuff + "/lists/" + listname + ".footer",'r') #
read the footer
		footer = ftr.readlines()				# reads the footer into the variable
		ftr.close()							# close that file,
		message = message + footer				# and append it to the message. 
	else									# BUT IF THEY ARE NOT SUBSCRIBED...
		listnamemembers = from					# put their addres as the only recipient
		message = ""						# clear the mesage.
		From = "From: tinylist@" + localhost + \n 	# From:
tinylist@mydomain.foo !
		Subject = "Subject: Unauthorized posting to list" + listname + \n
		Reply_to = "Reply-to:postmaster@" + localhost + \n # no comments
possible now!
		X-Loop = "X-Loop: postmaster@" + localhost	# This breaks email loops
from forming
		message = """
		
		To whom it may concern;
		
		Sorry, but as you are not a current member of """ + listname + """, 
		you may not post to it. Your recent posting has been rejected and
destroyed.
		
		Feel free to contact the postmaster if there is any question.
		Any reply to this letter should go directly to the postmaster.
		
		You can also subscribe to this list if you like.
		
		Goodbye.
		
		"""
		
							# there cannot be comments in those line 							# above this one,
or they would be part 							# of the triplequoted string!
							# ok, if they are not a member, THEY GET THE REPLY 							# SHOWN
ABOVE MAILED TO THEM!

							# above is a blank line, DO NOT DELETE IT!
							# there is no endif or fi in python.
							# whitespace and tabulation therefore
							# is rather important here.
							# now we send whatever message is to go out to 
							# whatever is in the recipient tupple.

server = smtplib.SMTP('localhost')
# helo(localhost)				# open a connection to the smtp server, possibly
not needed
						# so it is commented out. If all else fails, use it.

server.connect()				# and log in to the thing as the identity this
script runs as.
for each in listnamemembers :		# for each address in the list
listnamemembers,
	server.sendmail(from_addr, to_addr, Subject, reply-to, to, X-Loop, msg)
#send a envlope!

server.quit()				# then close the connection.

	
						# make sure this script runs as a TRUSTED USER-
						# and NOT as root!!! Make sure that a
						# NON-priviliged user can run this script,
						# and make sure it is owned by that identity!
					
--------------------------end of bibble----------------------------
-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Wed Dec 12 19:53:24 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 12 Dec 2001 14:53:24 -0500
Subject: R: [Tutor] further bibbling regarding list management
References: <3C17ADD6.4CE9548F@my995internet.com>
Message-ID: <3C17B5B4.2C4B1FD4@my995internet.com>

ok, I changed the line
> for each in listnamemembers :		# for each address in the list
to:
for to_addr in listnamemembers :	# for each address in the list

so it is reading the value for each member into the to_addr variable so
it will have it right for sending.
 Now, to get my skull screwed into rfc822 -actually, get rfc822 screwed
into my skull. This may prove scary, better get ready...

Carbide Bit- check
Impact drill-  check.

Gentleman jack - GLUG...


-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From glingl@aon.at  Wed Dec 12 19:56:20 2001
From: glingl@aon.at (Gregor Lingl)
Date: Wed, 12 Dec 2001 20:56:20 +0100
Subject: [Tutor] Is IDLE ... sorry !
References: <Pine.LNX.4.21.0112120011250.16665-100000@hkn.eecs.berkeley.edu> <010301c182e9$8c5becb0$1664a8c0@mega>
Message-ID: <003501c18347$1232a470$1664a8c0@mega>

 
> There is something very suspicious about this line: 
.....

> And this fits closely with the TypeError message that you were getting:
> 
> > TypeError: unsubscriptable object
> 
> .... since your error message
                ^^^^^^^^^^^^^^  

Sorry, misunderstood this! Despite of leaving just home
early in the morning in a hurry I shoud have read the 
original posting - 
Gregor L.

> still looked very strange to me.  Hmmm... Try to fix the subscripting
> problem above, and see if that clears things up for you.
> 




From wsf@fultondesigns.co.uk  Wed Dec 12 20:35:14 2001
From: wsf@fultondesigns.co.uk (William S Fulton)
Date: Wed, 12 Dec 2001 20:35:14 -0000
Subject: [Tutor] Re: [Swig] Problems with enviroment variable under W2000 and VC6++
References: <3C169FE2.52B6EDC3@gmx.de>
Message-ID: <006301c18352$43abe420$0b00a8c0@leopard>

No no no :) Copying the .swg files around is not correct. Assuming you have
swig 1.3.9, swig.exe is usually put into the root directory of the main
swig-1.3.9 directory,  ie in the same directory as README, INSTALL etc. Set
the SWIG_LIB environment variable to .\Lib. Why don't you use one of the
Visual C++ example files as a basis to what you want to do? Everything is
set up, except as the Windows.html file says to set the PYTHON_INCLUDE and
PYTHON_LIB environment variables.

Cheers
William
----- Original Message -----
From: Marcus Konermann
To: mailto:python-win32@python.org ; swig@cs.uchicago.edu ; tutor@python.org
Sent: Wednesday, December 12, 2001 12:08 AM
Subject: [Swig] Problems with enviroment variable under W2000 and VC6++


Hi @ All !
For now i tried a lot of things to tell SWIG where the lib directory is, but
after controlling by using the command "swig -swiglib"  every time the
output was " /usr/local/lib/swig1.3."
So to solve this problem the only solution for me was to copy the four
file´s (swig.swg, python.swg, common.swg, swig.exe) manually in the working
directory, but i don´t think that this was the right way. I also tried to
set the PATH to the lib directory under W2000 in the enviroment variables,
but nothing happend.
The second problem for me is to set the right enviroment variable for
python2.1 in the windows 2000 sytem. I tried to use PYTHONPATH,
PYTHON_INCLUDE and PYTHON_LIB (like described in the SWIG manual 1.3.9), but
nothing happend while compiling under VC6++. The Linker only says:
simanneal_wrap.cpp
C:\simanneal_wrap.cpp(179) : fatal error C1083: Include-Datei kann nicht
geoeffnet werden: 'Python.h': No such file or directory
Please, i need help
Greetings
Marcus



From Abhiram Singh Kushwah" <abhiramkushwah@rediffmail.com  Thu Dec 13 05:32:48 2001
From: Abhiram Singh Kushwah" <abhiramkushwah@rediffmail.com (Abhiram Singh Kushwah)
Date: 13 Dec 2001 05:32:48 -0000
Subject: [Tutor] How to attach file with mail
Message-ID: <20011213053248.7812.qmail@mailFA2.rediffmail.com>

Hi all,=0D=0A	How to attach a file with this code?=0D=0A=0D=0A> #!/usr/loca=
l/bin/python=0D=0A>                                 # so the script is =0D=
=0A> executable=0D=0A> import smtplib                  # import the smtp =
=0D=0A> routines=0D=0A> import string                   # and string =0D=0A=
> manipulation stuff=0D=0A> =0D=0A> CRLF=3D("\r"+"\n")                     =
   # we will be =0D=0A> tagging CRLF onto=0D=0A> several things.=0D=0A>    =
                                     # so this is =0D=0A> handy.=0D=0A> =0D=
=0A> def prompt(prompt):=0D=0A>         return string.strip(raw_input(promp=
t))  # =0D=0A> prompt, get, strip,=0D=0A> return.=0D=0A> =0D=0A> =0D=0A> fr=
omaddr =3D prompt("From: ")             # get the from =0D=0A> address.=0D=
=0A> toaddrs  =3D prompt("To: ")               # get the to =0D=0A> address=
.=0D=0A> subject =3D prompt("Subject: ")           # get the =0D=0A> subjec=
t.=0D=0A> =0D=0A> print "Enter message, end with ^D:"     # Add the From: =
=0D=0A> and To: headers=0D=0A> at the start!=0D=0A> =0D=0A> msg =3D "From: =
" + fromaddr + CRLF + "To: " + toaddrs + =0D=0A> CRLF + "Subject: "=0D=0A> =
+ subject + CRLF +=0D=0A>  CRLF=0D=0A> =0D=0A> while 1:=0D=0A>         try:=
=0D=0A>                 line =3D raw_input()=0D=0A>         except EOFError=
:=0D=0A>                 break=0D=0A>         if not line:=0D=0A>          =
       break=0D=0A>         msg =3D msg + line + CRLF=0D=0A> =0D=0A> print =
type(msg)=0D=0A> =0D=0A> print "Message length is " , len(msg) , " bytes lo=
ng."=0D=0A> =0D=0A> server =3D smtplib.SMTP('localhost')=0D=0A> server.set_=
debuglevel(1)=0D=0A> server.sendmail(fromaddr, toaddrs, msg)=0D=0A> server.=
quit()=0D=0A>  =0A


From deliberatus@my995internet.com  Thu Dec 13 06:47:47 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Thu, 13 Dec 2001 01:47:47 -0500
Subject: [Tutor] missing post
Message-ID: <3C184F13.6F1E0F9B@my995internet.com>

ok, where did that last post go to?

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Thu Dec 13 07:03:14 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Thu, 13 Dec 2001 02:03:14 -0500
Subject: [Tutor] How to attach file with mail
References: <20011213053248.7812.qmail@mailFA2.rediffmail.com>
Message-ID: <3C1852B2.70CE7C2C@my995internet.com>

The project thus far does not handle mime m ultipart attachments- most
list servers do not. The footwe would mess it up. IF you want to pass an
attachment, do not use a footer on that list. I will have to include a
few lines to see if the footer files exist, and to skip that part of
code if they do not. Such a list would simply pass on the main protion
of the submuission, with the in line attachment sitting right there.

Would you like to look at a short letter with a short attachment?


ns# list testfile
Listing of file testfile in directory:/www/www.howlermonkey.net/cgi-bin
--------------begin listing of file 'testfile'-----------
From: Kirk Bailey <deliberatus@my995internet.com>
Organization: Silas Dent Memorial Cabal of ERIS Esoteric and hot dog
boiling society 
 so there.
X-Mailer: Mozilla 4.74 [en] (Win98; U)
X-Accept-Language: en
MIME-Version: 1.0
To: testcode@howlermonkey.net
Subject: test
Content-Type: multipart/mixed;
 boundary="------------C63C5C0E80A93D974E28BCA5"

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

test
-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end
      My Sites:
      http://www.howlermonkey.net/ - free REAL email! list service soon!
      http://www.sacredelectron.org/ - Rants! Spleenvents!
      http://www.minorfish.org/ - The list server for some of us!

Message of the week:
R5L9W SDPQW UVN7V RUBWB I6HFP WVCUT VWRVL
W7812 LVH8V JBVK2 3CEJB TO8P3 FHFHG H7BFM
QID68 6DN6F 6M486 YQNCF JECQP 86CNP 86CTT
JIQPF ZPVGV DLFST DBUDI UIFNC BTUBS ETBOE
BTTGV DLUIF NSFBM IBSE!
--------------C63C5C0E80A93D974E28BCA5
Content-Type: text/html; charset=us-ascii;
 name="boo.html"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="boo.html"

<!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 name="Author" content="Kirk Bailey">
   <meta name="GENERATOR" content="Mozilla/4.74 [en] (Win98; U)
[Netscape]">
   <title>composertest</title>
</head>
<body>
<font color="#FFCC00">this is a test</font><font color="#330033">
and is only a test<u> but should not be taken literally, this is not a
school.</u></font>
<br><font color="#330033"><u>worse, it is not all important</u> and is
not really important.</font>
<br><font color="#330033"></font>&nbsp;
</body>
</html>

--------------C63C5C0E80A93D974E28BCA5--
------------------end of listing---------------------


ns# 

Abhiram Singh Kushwah wrote:
> 
> Hi all,
>         How to attach a file with this code?
> 
> > #!/usr/local/bin/python
> >                                 # so the script is
> > executable
> > import smtplib                  # import the smtp
> > routines
> > import string                   # and string
> > manipulation stuff
> >
> > CRLF=("\r"+"\n")                        # we will be
> > tagging CRLF onto
> > several things.
> >                                         # so this is
> > handy.
> >
> > def prompt(prompt):
> >         return string.strip(raw_input(prompt))  #
> > prompt, get, strip,
> > return.
> >
> >
> > fromaddr = prompt("From: ")             # get the from
> > address.
> > toaddrs  = prompt("To: ")               # get the to
> > address.
> > subject = prompt("Subject: ")           # get the
> > subject.
> >
> > print "Enter message, end with ^D:"     # Add the From:
> > and To: headers
> > at the start!
> >
> > msg = "From: " + fromaddr + CRLF + "To: " + toaddrs +
> > CRLF + "Subject: "
> > + subject + CRLF +
> >  CRLF
> >
> > while 1:
> >         try:
> >                 line = raw_input()
> >         except EOFError:
> >                 break
> >         if not line:
> >                 break
> >         msg = msg + line + CRLF
> >
> > print type(msg)
> >
> > print "Message length is " , len(msg) , " bytes long."
> >
> > server = smtplib.SMTP('localhost')
> > server.set_debuglevel(1)
> > server.sendmail(fromaddr, toaddrs, msg)
> > server.quit()
> >
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Thu Dec 13 07:04:54 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Thu, 13 Dec 2001 02:04:54 -0500
Subject: [Tutor] CLASS bash crashing my skull
Message-ID: <3C185316.D6C4BD7E@my995internet.com>

ok, I am in up to my eyes now, get me a scottpack.

I am reading the module rfc822 and reading the tutoral on classes and I
am going snowbling.

Anyone here good on either or both, this would be a good time to speak
up.

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Thu Dec 13 07:25:56 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Thu, 13 Dec 2001 02:25:56 -0500
Subject: [Tutor] Amazing
Message-ID: <3C185804.19E5C4A5@my995internet.com>

there is nothing I can find for a function or process or ANYTHING to
determine if a file exists in a specified place. Something like
exist(filename) really could be useful, but I cannot find any such!

Possibly I am looking in the wrong place?

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From ak@silmarill.org  Thu Dec 13 07:31:20 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Thu, 13 Dec 2001 02:31:20 -0500
Subject: [Tutor] Amazing
In-Reply-To: <3C185804.19E5C4A5@my995internet.com>
References: <3C185804.19E5C4A5@my995internet.com>
Message-ID: <20011213023120.A2698@sill.silmarill.org>

On Thu, Dec 13, 2001 at 02:25:56AM -0500, Kirk Bailey wrote:
> there is nothing I can find for a function or process or ANYTHING to
> determine if a file exists in a specified place. Something like
> exist(filename) really could be useful, but I cannot find any such!
> 
> Possibly I am looking in the wrong place?

os.path.exists

> 
> -- 
> Respectfully,
>              -Kirk D Bailey (C)2001
>               Addme! icq #27840081
> end
> 
> 
> Within the sweep of his sword, Each man is an Ubar.
> 
> http://www.howlermonkey.net/
> http://www.sacredelectron.org/
> 
> _______________________________________________
> 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 Blake.Garretson@dana.com  Thu Dec 13 17:57:40 2001
From: Blake.Garretson@dana.com (Blake.Garretson@dana.com)
Date: Thu, 13 Dec 2001 12:57:40 -0500
Subject: [Tutor] Re: Tutor digest, Vol 1 #1268 - 7 msgs
Message-ID: <OF4A87C1EB.A6B398EC-ON85256B21.0061A293@dana.com>

>From: Kirk Bailey <deliberatus@my995internet.com>
>Subject: [Tutor] Amazing
>
>there is nothing I can find for a function or process or ANYTHING to
>determine if a file exists in a specified place. Something like
>exist(filename) really could be useful, but I cannot find any such!

I prefer to use the os.access() function.  It gives you more information
than os.path.exists() because it will tell you if it exists AND has certain
file permissions.  You just give it the filename and a permissions flag.

The valid permission flags are:

F_OK: existance flag
R_OK: readability flag
W_OK: writability flag
X_OK: executable flag

For instance:

###
>>>import os
>>>os.access("Filename.txt",R_OK)
1
###

This tells me that the file exists AND I have the permission to read it.
Likewise, this tells me that it exists and I can write to the file:

###
>>>import os
>>>os.access("Filename.txt",W_OK)
1
###

Hope this helps,
Blake Garretson




From deliberatus@my995internet.com  Thu Dec 13 17:56:47 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Thu, 13 Dec 2001 12:56:47 -0500
Subject: [Tutor] Amazing
References: <3C185804.19E5C4A5@my995internet.com> <20011213023120.A2698@sill.silmarill.org>
Message-ID: <3C18EBDF.71EC5E83@my995internet.com>

ok, that worked, thanks.


Andrei Kulakov wrote:
> 
> On Thu, Dec 13, 2001 at 02:25:56AM -0500, Kirk Bailey wrote:
> > there is nothing I can find for a function or process or ANYTHING to
> > determine if a file exists in a specified place. Something like
> > exist(filename) really could be useful, but I cannot find any such!
> >
> > Possibly I am looking in the wrong place?
> 
> os.path.exists
> 
> >
> > --
> > Respectfully,
> >              -Kirk D Bailey (C)2001
> >               Addme! icq #27840081
> > end
> >
> >
> > Within the sweep of his sword, Each man is an Ubar.
> >
> > http://www.howlermonkey.net/
> > http://www.sacredelectron.org/
> >
> > _______________________________________________
> > 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
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Thu Dec 13 18:01:04 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Thu, 13 Dec 2001 13:01:04 -0500
Subject: [Tutor] latest state of the fart
Message-ID: <3C18ECE0.2AFB62B6@my995internet.com>

Ok, this is the latest state of the art snapshot of the tinylist script.

Note that now the thing OPTIONALLY reads in the footer and random files
IF they exist, and ignores that feature if they do not.
This can be a useful feature, simply turning on and off functions by the
presence or absence of a file.

BUT I STILL NEED SOMEONE TO ADVISE ME RE rfc822 module!

-------------------------fresh dingleberries--------------------------
#!/usr/local/bin/python
# Tinylist module, Pitchtime unit.
# this handles receiving and sending out postings to a list.

import sys, re, string, rfc822, smtplib, os.path

localhost = 'howlermonkey.net'		# make sure you set this to the domain
YOU use!!!
							# next line declares the path to stuff. DEFINE IT
pathtostuff = '/www/www.howlermonkey.net/cgi-bin/'	# to the cgi-bin for
your web dir with
							# a trailing '/' as this example shows!
							# note this tells where to start looking.
							# everything is either here, or under this
							# point in '/lists' dir.
					
					
listname = sys.argv[1]				# we read a command line arguement to
determine the list name
							# Arguement 0 is the name of the script run, 1 is the
							# first arguement.
							# after that name in the command line, so if this were
							# program FOO,
							# that line would be "|/path/FOO listname"
							# and the arguement here would be 'listname'!
					
					
message = raw_input.lines()			# Variable 'message' is assigned the
entire message
							# which is piped to the program by the alias definition
							# such as:
							# foolist:"|/pathtoprogram/programname foolist"


							# now we must determine the sender and see if they are in
							# the subscriber file!
							# still got to learn more about how this thing handles
							# parsing the incoming message, but smtp and rfc822
							# are deep sorcery on this material.

from = message["From"]				# we must dig out the 'from: ' field and read
it's contents.
							# Note we already know who it is TO - 'listname' !
							# Remember, the mail ssytem fed it here with a command
							# line arguement, after sorting it out to a known identity,
							# so the list's defining alias contains that info.

def gangstrip(str):				# ok, everybody STRIP! STR is a list variable
	index = 0					# We want to strip off all leading and
	while index<len(str)			# trailing whitespace characters
	str[index]=string.strip(str[index])	# in each element in the list.

open a.file(pathtostuff + "/lists/" + listname, 'r')						
members = a.readlines()				# we build a list of all the members of the
email list
a.close()						# and close the file
							# then we look to see if that FROM exists in the membership.

gangstrip(members)				# strip all leading and trailing whitespace
							# from each element in the list 'members'.

if from in members :				# IF the sender is in the subscriber file, 
		subject = '[' + listname + ']' + subject			# then acept the
submission.
		Reply_to = listname + "@" + localhost			# this sets the reply-to
field.
		X-Loop = "X-Loop: " + listname + "@" + localhost	# This breaks email
loops from forming
		
		if os.path.exists("./lists/"+listname):			#if there is a footer file,
read it!
			ftr = b.open(pathtostuff + "/lists/" + listname + ".footer",'r') #
read the footer file
			footer = ftr.readlines()				# reads the footer into the variable
			ftr.close()							# close that file,
			message = message + footer + CRLF			# and append it to the message. 

		if os.path.exists("./lists/"+listname+".random"):
			f1=open("./lists/"+listname+".random",'r')	# Open the random footer
rotation
			randomline=gangstrip(f1.readlines())	# load the contents of the
rotation
			f1.close()						#and close the file
			message = message + randomline + CRLF	# add the random element to the
footer.
			
	else									# BUT IF THEY ARE NOT SUBSCRIBED...
		listnamemembers = from					# put their addres as the only recipient
		message = ""						# clear the mesage.
		From = "From: tinylist@" + localhost + \n 	# From:
tinylist@mydomain.foo !
		Subject = "Subject: Unauthorized posting to list" + listname + \n
		Reply_to = "Reply-to:postmaster@" + localhost + \n # no comments
possible now!
		X-Loop = "X-Loop: postmaster@" + localhost	# This breaks email loops
from forming
		message = """
		
		To whom it may concern;
		
		Sorry, but as you are not a current member of """ + listname + """, 
		you may not post to it. Your recent posting has been rejected and
destroyed.
		
		Feel free to contact the postmaster if there is any question.
		Any reply to this letter should go directly to the postmaster.
		
		You can also subscribe to this list if you like.
		
		Goodbye.
		
		"""

							# ABOVE IS 1 BLANK LINE, DO NOT DELETE IT!
							# there cannot be comments in those line 							# 							# above
this one, or they would be part
							# of the triplequoted string!
							# ok, if they are not a member, THEY GET 
							# THE REPLY SHOWN ABOVE MAILED TO THEM! 
							# (Maybe we could read a stock answer from a file?)
							# there is no endif or fi in python.
							# whitespace and tabulation therefore
							# is rather important here.
							# now we send whatever message is to go out to 
							# whatever is in the recipient tupple.

server = smtplib.SMTP('localhost')	# setup for a smtp run.
# helo(localhost)				# open a connection to the smtp server, possibly
not needed
						# so it is commented out. If all else fails, use it.
server.connect()				# and log in to the thing as the identity this
script runs as.
						#
for to_addr in listnamemembers :	# for each address in the list
listnamemembers,
	server.sendmail(from_addr, to_addr, Subject, reply-to, to, X-Loop, msg)
# send a envlope and msg!

server.quit()				# then close the connection.

						# make sure this script runs as a TRUSTED USER-
						# and NOT as root!!! Make sure that a
						# NON-priviliged user can run this script,
						# and make sure it is owned by that identity!
						# this list is devloped by THE OLD FART and a fine bunch of
						# dingleberrys at www.tinylist.org where you can hop on the
						# bandwagon at your convience.
						# We have lists there, which onlyu seems right somehow.
						# tinylist-users - discussion for all aspects of using tinylist;
somewhat technical.
						# tinylist-chat - for all intrested in tl, lists, python, email: a
broad charter! 
						# tinylist-devlopers - discussion of new versions, features,
bugchasing.
						# evil-humnor - sick, raunchy, crusty, cynical, depraved, deprived
humor? OVER HERE!
						#
-----------------------------------end of
mousedroppings---------------------------------



-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From alan.gauld@bt.com  Thu Dec 13 18:04:00 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 13 Dec 2001 18:04:00 -0000
Subject: [Tutor] Amazing
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1B8@mbtlipnt02.btlabs.bt.co.uk>

> determine if a file exists in a specified place. Something like
> exist(filename) really could be useful, but I cannot find any such!

try:

os.path.exists(path)

Hiding it inside the path submodule is kind of sneaky I know...

Alan g.


From alan.gauld@bt.com  Thu Dec 13 18:05:32 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 13 Dec 2001 18:05:32 -0000
Subject: [Tutor] How to attach file with mail
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1B9@mbtlipnt02.btlabs.bt.co.uk>

> Hi all,
> 	How to attach a file with this code?

Not with this code specifically but ISTR that there exiosts 
a mime module(or set of?).

That might help.

Alan G.



From deliberatus@my995internet.com  Thu Dec 13 18:23:24 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Thu, 13 Dec 2001 13:23:24 -0500
Subject: [Tutor] custom module
Message-ID: <3C18F21C.9969E8DE@my995internet.com>

For a future version, I will simply copy the code for the functions used
to a new module, tinylist.py, and not have to burden the system with
loading functions not used in each of those libraries. My only concern
is the user having the cajones and savvy to add a new custom module to
their python installation. This would load up faster, take up less
system memory, and MIGHT run just a tad fster- esp if I then have it
save a copy of the compiled library (tinylistlib.pyc) na they also
install THAT. But this is starting to get well beyond what some users
will beel secure with doing.

Who wrote that?

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From highprimate@howlermonkey.net  Thu Dec 13 06:21:44 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Thu, 13 Dec 2001 1:21:44 -0500
Subject: [Tutor] class envy
Message-ID: <200112130623.fBD6NaS09187@ns.howlermonkey.net>

ok, now I know I am in up to my eyes, some one get me a snorkel. This novice is finally in WAY over his head.

I am reading the official online python tutoral about classes, and I am totally lost. I mean I am SNOWBLIND. 
If you gave me a clue I would spread it on toast, I need SEVERAL clues, superglue, a serious skulldrill, and 
BIG RED STRAPS to hold it on with.

rfc822 is a pretty understandable document, and I understand email fine. But the module rfc822 is leaving me 
going -huh?- and CLASS and classes leave me without a clue.
I need to grok parsing the incoming message to extract the data contained there. 

A alias feeds an incoming message to the program on the standard input, and is readable several ways, simplest 
being raw_input() and friends. The list name we know from reading the command line arguement.





OK, this is what exists thus far. It's 90% done now, even will read a random footer appendment
(A slogan, witty saying, quote, or text advertisement from a flat text file) to the footer of the message.


--------------rare fresh bits follow---------------------
#!/usr/local/bin/python
# Tinylist module, Pitchtime unit.
# this handles receiving and sending out postings to a list.

import sys, re, string, rfc822, smtplib

localhost = 'howlermonkey.net'	# make sure you set this to the domain YOU use!!!
						# next line declares the path to stuff. DEFINE IT
pathtostuff = '/www/www.howlermonkey.net/cgi-bin/'	# to the cgi-bin for your web dir with
						# a trailing '/' as this example shows!
						# note this tells where to start looking.
						# everything is either here, or under this
						# point in '/lists' dir.
					
					
listname = sys.argv[1]			# we read a command line arguement to determine the list name
						# Arguement 0 is the name of the script run, 1 is the
						# first arguement.
						# after that name in the command line, so if this were
						# program FOO,
						# that line would be "|/path/FOO listname"
						# and the arguement here would be 'listname'!
					
					
message = raw_input.lines()		# Variable 'message' is assigned the entire message
						# which is piped to the program by the alias definition
						# such as:
						# foolist:"|/pathtoprogram/programname foolist"


						# now we must determine the sender and see if they are in
						# the subscriber file!
						# still got to learn more about how this thing handles
						# parsing the incoming message, but smtp and rfc822
						# are dep sorcery on this material.

from = message["From"]			# we must dig out the 'from: ' field and read it's contents.
						# Note we already know who it is TO - 'listname' !
						# Remember, the mail ssytem fed it here with a command
						# line arguement, after sorting it out to a known identity,
						# so the list's defining alias contains that info.

def gangstrip(str):			# ok, everybody STRIP! STR is a list variable
	index = 0				# We want to strip off all leading and
	while index<len(str)		# trailing whitespace characters
	str[index]=string.strip(str[index])	# in each element in the list.

open a.file(pathtostuff + "/lists/" + listname, 'r')						
members = a.readlines()			# we build a list of all the members of the email list
a.close()					# and close the file
						# then we look to see if that FROM exists in the membership.

gangstrip(members)			# strip all leading and trailing whitespace
						# from each element in the list 'members'.

if from in members :			# IF the sender is in the subscriber file, 
		subject = '[' + listname + ']' + subject		# then acept the submission.
		Reply_to = listname + "@" + localhost		# this sets the reply-to field.
		X-Loop = "X-Loop: " + listname + "@" + localhost	# This breaks email loops from forming
		ftr = b.open(pathtostuff + "/lists/" + listname + ".footer",'r') # read the footer file
		footer = ftr.readlines()				# reads the footer into the variable
		ftr.close()							# close that file,
		message = message + footer + CRLF			# and append it to the message. 
		f1=open(path/lists/listname,'r')			# Open the footer rotation
		randomline=gangstrip(f1.readlines())		# load the contents of the rotation
		message = message + randomline + CRLF		# add the random element to the footer.
	else									# BUT IF THEY ARE NOT SUBSCRIBED...
		listnamemembers = from					# put their addres as the only recipient
		message = ""						# clear the mesage.
		From = "From: tinylist@" + localhost + \n 	# From: tinylist@mydomain.foo !
		Subject = "Subject: Unauthorized posting to list" + listname + \n
		Reply_to = "Reply-to:postmaster@" + localhost + \n # no comments possible now!
		X-Loop = "X-Loop: postmaster@" + localhost	# This breaks email loops from forming
		message = """
		
		To whom it may concern;
		
		Sorry, but as you are not a current member of """ + listname + """, 
		you may not post to it. Your recent posting has been rejected and destroyed.
		
		Feel free to contact the postmaster if there is any question.
		Any reply to this letter should go directly to the postmaster.
		
		You can also subscribe to this list if you like.
		
		Goodbye.
		
		"""

							# ABOVE IS 1 BLANK LINE, DO NOT DELETE IT!
							# there cannot be comments in those line 
							# 							# above this one, or they would be 
part
							# of the triplequoted string!
							# ok, if they are not a member, THEY GET 
							# THE REPLY SHOWN ABOVE MAILED TO THEM! 
							# (Maybe we could read a stock answer from a file?)
							# there is no endif or fi in python.
							# whitespace and tabulation therefore
							# is rather important here.
							# now we send whatever message is to go out to 
							# whatever is in the recipient tupple.

server = smtplib.SMTP('localhost')	# setup for a smtp run.
# helo(localhost)				# open a connection to the smtp server, possibly not needed
						# so it is commented out. If all else fails, use it.
server.connect()				# and log in to the thing as the identity this script runs as.
						#
for to_addr in listnamemembers :		# for each address in the list listnamemembers,
	server.sendmail(from_addr, to_addr, Subject, reply-to, to, X-Loop, msg)	# send a envlope and msg!

server.quit()				# then close the connection.

	
						# make sure this script runs as a TRUSTED USER-
						# and NOT as root!!! Make sure that a
						# NON-priviliged user can run this script,
						# and make sure it is owned by that identity!
					
-------------end of line---------------------------------------


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From shalehperry@attbi.com  Thu Dec 13 20:19:36 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Thu, 13 Dec 2001 12:19:36 -0800 (PST)
Subject: [Tutor] class envy
In-Reply-To: <200112130623.fBD6NaS09187@ns.howlermonkey.net>
Message-ID: <XFMail.20011213121936.shalehperry@attbi.com>

Is 80 chars per line really that much to ask

enough-of-the-line-noise-ly yours


From glingl@aon.at  Thu Dec 13 20:22:07 2001
From: glingl@aon.at (Gregor Lingl)
Date: Thu, 13 Dec 2001 21:22:07 +0100
Subject: [Tutor] class envy
References: <200112130623.fBD6NaS09187@ns.howlermonkey.net>
Message-ID: <000901c18413$d68303c0$1664a8c0@mega>

Thanks for this rare kind of second order poetry ...

> ...and rfc822
> # are dep sorcery on this material.
>
> from = message["From"] # we must dig out the 'from: ' field and read it's
contents.
> # Note we already know who it is TO - 'listname' !
> # Remember, the mail ssytem fed it here with a command

But here a caveat!  A poet may use from deliberately as hie likes,
but not so a  programmer. at least under Python circumstances.

A syntax-coloring editor would highlight this problem immediately ...

Have a nice and/or fruitful evening
Gregor



From inkedmn@gmx.net  Thu Dec 13 21:12:57 2001
From: inkedmn@gmx.net (Brett Kelly)
Date: Thu, 13 Dec 2001 22:12:57 +0100 (MET)
Subject: [Tutor] Iterating over a list for a certain character...
Message-ID: <24414.1008277977@www44.gmx.net>

ok, i have read a file into a list of strings, and i need to copy out all of
the strings that contain a certain character, sort them, and print them.

how would i do that?

Thanks!
Brett

-- 
Sent through GMX FreeMail - http://www.gmx.net



From shalehperry@attbi.com  Thu Dec 13 22:55:26 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Thu, 13 Dec 2001 14:55:26 -0800 (PST)
Subject: [Tutor] Iterating over a list for a certain character...
In-Reply-To: <24414.1008277977@www44.gmx.net>
Message-ID: <XFMail.20011213145526.shalehperry@attbi.com>

On 13-Dec-2001 Brett Kelly wrote:
> ok, i have read a file into a list of strings, and i need to copy out all of
> the strings that contain a certain character, sort them, and print them.
> 
> how would i do that?
> 

take a look at:

>>> c = 's'
>>> c in 'streets'
1



From glingl@aon.at  Thu Dec 13 23:28:04 2001
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 14 Dec 2001 00:28:04 +0100
Subject: [Tutor] Iterating over a list for a certain character...
References: <XFMail.20011213145526.shalehperry@attbi.com>
Message-ID: <017701c1842d$d09a9170$1664a8c0@mega>

----- Original Message -----
From: "Sean 'Shaleh' Perry" <shalehperry@attbi.com>
To: "Brett Kelly" <inkedmn@gmx.net>
Cc: <tutor@python.org>
Sent: Thursday, December 13, 2001 11:55 PM
Subject: Re: [Tutor] Iterating over a list for a certain character...


>
> On 13-Dec-2001 Brett Kelly wrote:
> > ok, i have read a file into a list of strings, and i need to copy out
all of
> > the strings that contain a certain character, sort them, and print them.
> >
> > how would i do that?
> >
>
> take a look at:
>
> >>> c = 's'
> >>> c in 'streets'
> 1

.. or try - somewhat more sophisticated:

>>> l = ['bim', 'bam', 'schrumm']
>>> filter(lambda x: 'i' in x, l)
['bim']
>>> filter(lambda x: 'b' in x, l)
['bim', 'bam']
>>> filter(lambda x: 'm' in x, l)
['bim', 'bam', 'schrumm']
>>>

so you can make up the following definition:

>>> def wordswith(char, lst):
...  return filter(lambda x, c = char : c in x, lst)
...
>>> wordswith('i',l)
['bim']
>>> wordswith('c',l)
['schrumm']
>>> wordswith('m',l)
['bim', 'bam', 'schrumm']
>>>


who knows a more elegant way?

Gregor



From glingl@aon.at  Thu Dec 13 23:42:31 2001
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 14 Dec 2001 00:42:31 +0100
Subject: [Tutor] Iterating over a list for a certain character...
References: <XFMail.20011213145526.shalehperry@attbi.com>
Message-ID: <017b01c1842f$d53e16f0$1664a8c0@mega>

> > 
> 
> take a look at:
> 
> >>> c = 's'
> >>> c in 'streets'
> 1
> 
> 
P.S.:

In Python 2.2 the following also  will work:

>>> l = ['bim','bam','schrumm']
>>> def wordswith(c,l):
    return filter(lambda x: c in x, l)

>>> wordswith('b',l)
['bim', 'bam']
>>> 

.. due to 'nested_scopes' in action

---------------------------------------------------

Alternately you may use (already since Python 2.0 ?)

>>> [word for word in l if 'b' in word]
['bim', 'bam']
>>> 

and consequently

>>> def wordswith(c,lst):
...  return [word for word in lst if c in word]
... 
>>> wordswith('m',l)
['bim', 'bam', 'schrumm']
>>> wordswith('b',l)
['bim', 'bam']
>>>  ww('x',l)
[]
>>> 

Gregor





From deliberatus@my995internet.com  Fri Dec 14 05:24:42 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Fri, 14 Dec 2001 00:24:42 -0500
Subject: [Tutor] replyto now optional
Message-ID: <3C198D1A.46B67331@my995internet.com>

ok, I read the page about reply-to, and I see there are good arguements
for not doing this.

I also know there are people who want to anyway. So, I made it optional

		if os.path.exists("./lists/" +listname +".replyto"):	# IF this file
exists,
			Reply_to = listname + "@" + localhost		# this sets the optional
reply-to field.




In the lists directory, if the file listname.replyto exists, it will set
the header
Reply-to: listname@domainname

and if the file is NOT there, it will not.

Good enough?

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Fri Dec 14 06:40:05 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Fri, 14 Dec 2001 01:40:05 -0500
Subject: [Tutor] startled
Message-ID: <3C199EC5.EDE6E6E6@my995internet.com>

Reviewing the accumulated debreis and layered writings of this list over
the last 2 weeks, I am startled to see how far I have come in learning a
new language part time from reading websites, and discussing in this
list. I started thinking about this when I wrote the post mentioning
taking definitions specific for the tinylist application, gathering them
together, and placing them into a module for it.

I must pay tribute to a friendly and very supportive populace on the
list, and salute you all for it; I also must declare this is at least in
part to the amazingly more acessable nature of this language over perl-
or just about anything else you may care to mention.

It, and this group, are simply amazing.


-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From karthikg@aztec.soft.net  Fri Dec 14 11:31:56 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Fri, 14 Dec 2001 17:01:56 +0530
Subject: [Tutor] want to implement Workflow engine using python
In-Reply-To: <017b01c1842f$d53e16f0$1664a8c0@mega>
Message-ID: <NEBBJNMDEKBIBCMCNMBDIELECLAA.karthikg@aztec.soft.net>

hi all,

I want to do a full fledged project to come to grips with this language.
Though i have managed to learn the features, i realize i w'd be in a better
position
if i do a project.

Can someone point to some good sites which w'd help me to devise a work flow
engine.
I dont' want to provide any great features , simple ones do

Any tips? what all i might have to use in addition to core python?
Database for sure...xml?

thanks for the help,
karthik.





From alan.gauld@bt.com  Fri Dec 14 11:26:24 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 14 Dec 2001 11:26:24 -0000
Subject: [Tutor] Iterating over a list for a certain character...
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1BB@mbtlipnt02.btlabs.bt.co.uk>

> ok, i have read a file into a list of strings, and i need to 
> copy out all of the strings that contain a certain 
> character, 

Try the string.find() function or if its more complex the re.search()
function.

> sort them, 

list.sort()

You can provide your own comparison function too.


> and print them.

print

However there is a module designed to make this kind 
of thing easier, its called:

fileinput

And allows you to do:

import fileinput
for line in fileinput.input():
    process(line)

So it handles all the file opening etc. It also allows 
you to process multiple files as if they were one big 
one. Which might help you...

Finally you might like to read my file handling topic
on my web tutor

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


From kalle@gnupung.net  Fri Dec 14 11:50:31 2001
From: kalle@gnupung.net (Kalle Svensson)
Date: Fri, 14 Dec 2001 12:50:31 +0100
Subject: [Tutor] Iterating over a list for a certain character...
In-Reply-To: <24414.1008277977@www44.gmx.net>
References: <24414.1008277977@www44.gmx.net>
Message-ID: <20011214125031.B10589@proton.lysator.liu.se>

[Brett Kelly]
> ok, i have read a file into a list of strings, and i need to copy out all of
> the strings that contain a certain character, sort them, and print them.

To read a file to a list of strings, check out the readlines and xreadlines
methods of file objects.
http://www.python.org/doc/current/lib/bltin-file-objects.html

To see if a character is in a string, use the in statement:

>>> "r" in "bar"
1
>>> "r" in "foo"
0

If you want to check for more complex things than characters, like strings or
regular expressions, check out string methods (especially find) and the re
module.
http://www.python.org/doc/current/lib/string-methods.html
http://www.python.org/doc/current/lib/module-re.html

Sorting is done with the list method sort.  More info:
http://www.python.org/doc/current/lib/typesseq-mutable.html

Looping can be done with for loops or, quite elegantly, with list
comprehensions:

>>> words = ["omph", "foo", "fum"]
>>> matches = [w for w in words if "o" in w]
>>> matches
['omph', 'foo']
>>> matches.sort()
>>> matches
['foo', 'omph']

Peace,
  Kalle
-- 
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]


From karthikg@aztec.soft.net  Fri Dec 14 13:35:42 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Fri, 14 Dec 2001 19:05:42 +0530
Subject: [Tutor] What is the problem in this import?? Newbie
In-Reply-To: <017b01c1842f$d53e16f0$1664a8c0@mega>
Message-ID: <NEBBJNMDEKBIBCMCNMBDCELHCLAA.karthikg@aztec.soft.net>

hi all,

os: windows nt

i installed
qt2.3.0 from trolltech.com

then i installed pyqt from thekompany website and i get the error i have
pasted below.

I found that libqtc.pyd is present in the

d:\\python21\dlls folder.

sys.path has an entry for that. Still it failed why??

>>> from qt import *
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "d:\python21\lib\qt.py", line 44, in ?
    import libqtc
ImportError: DLL load failed: The specified module could not be found.
>>> import sys
>>> sys.path
['', 'd:\\python21\\pythonwin', 'd:\\python21\\win32',
'd:\\python21\\win32\\lib', 'd:\\py
thon21', 'd:\\python21\\dlls', 'd:\\python21\\lib',
'd:\\python21\\lib\\plat-win', 'd:\\py
thon21\\lib\\lib-tk']
>>>


thanks in advance,
karthik



From boud@valdyas.org  Fri Dec 14 13:40:15 2001
From: boud@valdyas.org (Boudewijn Rempt)
Date: Fri, 14 Dec 2001 14:40:15 +0100 (CET)
Subject: [Tutor] What is the problem in this import?? Newbie
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDCELHCLAA.karthikg@aztec.soft.net>
Message-ID: <Pine.LNX.4.33.0112141435001.4184-100000@calcifer.valdyas.org>

On Fri, 14 Dec 2001, karthik Guru wrote:

> hi all,
>
> os: windows nt
>
> i installed
> qt2.3.0 from trolltech.com
>
> then i installed pyqt from thekompany website and i get the error i have
> pasted below.
>
> I found that libqtc.pyd is present in the
>

I think that that you forgot to install qt itself - I think
it's not packaged with PyQt, but that you must get it from
Trolltech:
  ftp://ftp.trolltech.com/qt/non-commercial/QtWin230-NonCommercial.exe

This requirement isn't particular clearly stated on the TheKompany
website, I notice... Anyway, if you need more help, you might be
interested in the PyKDE mailing list, which can be found at:

   http://mats.gmd.de/mailman/listinfo/pykde

Have fun, and let me know how you're doing!

-- 
Boudewijn Rempt  | http://www.valdyas.org



From karthikg@aztec.soft.net  Fri Dec 14 14:02:21 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Fri, 14 Dec 2001 19:32:21 +0530
Subject: [Tutor] What is the problem in this import?? Newbie
In-Reply-To: <Pine.LNX.4.33.0112141435001.4184-100000@calcifer.valdyas.org>
Message-ID: <NEBBJNMDEKBIBCMCNMBDAELICLAA.karthikg@aztec.soft.net>

thanks! But i actually installed qt from exactly the same place you have
mentioned.
(Though the website does'nt mention this, your book does :-))
is there anything else i need to do.

it is under d:\\qt

there is an environment variable

QTDIR which points to d:\\qt.

do i need to do some other tweaking??

thanks
karthik.



-----Original Message-----
From: Boudewijn Rempt [mailto:boud@valdyas.org]
Sent: Friday, December 14, 2001 7:10 PM
To: karthik Guru
Cc: tutor@python.org
Subject: Re: [Tutor] What is the problem in this import?? Newbie


On Fri, 14 Dec 2001, karthik Guru wrote:

> hi all,
>
> os: windows nt
>
> i installed
> qt2.3.0 from trolltech.com
>
> then i installed pyqt from thekompany website and i get the error i have
> pasted below.
>
> I found that libqtc.pyd is present in the
>

I think that that you forgot to install qt itself - I think
it's not packaged with PyQt, but that you must get it from
Trolltech:
  ftp://ftp.trolltech.com/qt/non-commercial/QtWin230-NonCommercial.exe

This requirement isn't particular clearly stated on the TheKompany
website, I notice... Anyway, if you need more help, you might be
interested in the PyKDE mailing list, which can be found at:

   http://mats.gmd.de/mailman/listinfo/pykde

Have fun, and let me know how you're doing!

--
Boudewijn Rempt  | http://www.valdyas.org



From boud@valdyas.org  Fri Dec 14 18:02:05 2001
From: boud@valdyas.org (Boudewijn Rempt)
Date: Fri, 14 Dec 2001 19:02:05 +0100 (CET)
Subject: [Tutor] What is the problem in this import?? Newbie
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDAELICLAA.karthikg@aztec.soft.net>
Message-ID: <Pine.LNX.4.33.0112141900460.6349-100000@calcifer.valdyas.org>

On Fri, 14 Dec 2001, karthik Guru wrote:

> thanks! But i actually installed qt from exactly the same place you have
> mentioned.
> (Though the website does'nt mention this, your book does :-))
> is there anything else i need to do.
>
> it is under d:\\qt
>
> there is an environment variable
>
> QTDIR which points to d:\\qt.
>
> do i need to do some other tweaking??
>

 I think it would be best to ask this question on the PyKDE mailing
 list, too. I haven't got access to a Windows computer at the moment
 (needed the partition, I'm afraid), so I can't test it at the moment.
 When I tried it out, I didn't have any problems.

Boudewijn Rempt  | http://www.valdyas.org



From deliberatus@my995internet.com  Fri Dec 14 18:08:37 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Fri, 14 Dec 2001 13:08:37 -0500
Subject: [Tutor] replyto now optional
References: <EHEPLGFHKAPDEDKIBONMKECACCAA.bwinton@tor.dhs.org> <3C1A3752.87D48017@my995internet.com>
Message-ID: <3C1A4025.58A505C5@my995internet.com>


> 
> Blake Winton wrote:
> >
> > > ok, I read the page about reply-to, and I see there are good arguements
> > > for not doing this.
> > > I also know there are people who want to anyway. So, I made it optional
> >
> > That's almost always a good thing.  :)  (I like options.)
> >
> > > In the lists directory, if the file listname.replyto exists, it will set
> > > the header
> > > Reply-to: listname@domainname
> > > and if the file is NOT there, it will not.
> > > Good enough?
> >
> > That's kind of an odd way to do it.
> 
 OK, so I'm odd, shoot me.
 
 *BANG*
 
 Actually, I did it this way for several reasons:
 1. it was easy to implement without changing all the rest of the
program
    for sake of one feature.
 2. I have used this sort of thing with other applications and itwas
easy
    to work with.
 3. in a future version, I can place CONTENT in the file, and define an
    alternate replyto address, such as the list owner.
 
> > Why don't you have a configuration file?
> 
 First version of the program, and I am nerw to python, so doiing it
this
 was was simpler. In a future version, I will look into using a config
 file, along with some other remarkably mind numbing features and
 misfeatures.
 
 > Call it "listname.config", and then you could read it in, and exec
it,
 > and it could set variables in a Pythonic manner.
 
 Right. And a backup global config file just in case?

 i.e. listname.config could contain:
 >
 > replyto = true
 >
 > to set the replyto to listname@domain, or:
 >
 > replyto = "other-listname@other-domain"
 >
 > if they wanted to reply to a different list...
 > Or anything else they wanted.  Just a thought.
 >
 And a good one.
> 
> > Myself, I prefer XML files for configuration.
> > <listConfig>
> >   <welcomeMessage>
> >     Yo, all!  Welcome to my new list!
> >
> >     Have fun!
> >     Your friendly neighbourhood list-admin.
> >   </welcomeMessage>
> >   <replyTo>other-listname@other-domain</replyTo>
> > </listConfig>
> >
> > But that's just me, and XML processing is definately
> > harder than the other options.  More interesting, in
> > a way, but harder.  More useful, too, but harder.
> >
 Regretfully, I have not studied xml. HTML, ssi, but not xml.
 
 Gotta do that after I finish rotohammering python through the calcium.
 And groking tar/gz. and snorting rfc822.py. And earning a living. and
 tending a sickly wife, 30 birds(parrots)...
 
 > In the mean time, I'm looking forward to seeing what
 > your program turns into.  Have you compared it with
 > the earlier versions?  Might be amusing...
> 
 What earlier versions?
 Oh, the gaget as it grew to this? Not really.
 Inspired by several other MLM's, notably majordomo (majorcomplexity)
and
 minorfish. Regretfully
 Until I come up with it's first working complete incarnation, it's
still
 on the workbench.
 
 Already, I am scraping together ideas and roughing out code for the
 membership web manager. When that is done, I borrow some code from it,
 some from TLposttime, and smash them together into TLemail.py, the
email
 command processer module. Then write a doc, and smash it all together
 into a zip file (and a tarball if I ever learn how to properly use
 tar/gz- any tutorals out there gang?) and stick it on a website -
 www.tinylist.org. Gotta register the name.
 
 A man's reach should exceed his grasp.
 
> >
> > Later,
> > Blake.
> 
> --
> Respectfully,
>              -Kirk D Bailey (C)2001
>               Addme! icq #27840081
> end
> 
> Within the sweep of his sword, Each man is an Ubar.
> 
> http://www.howlermonkey.net/
> http://www.sacredelectron.org/

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From vip333d@yahoo.com  Fri Dec 14 19:49:15 2001
From: vip333d@yahoo.com (vip333d@yahoo.com)
Date: Fri, 14 Dec 2001 11:49:15 -0800 (PST)
Subject: [Tutor] some questions - from a complete newbie
Message-ID: <20011214194915.52681.qmail@web12302.mail.yahoo.com>

dear Tutor!
I'm a newbie, and there are some things that I want to
do with python, that aren't in the basic web tutorials
I have read. My OS is win95. I:
a) cannot execute the os.access(c:\.....) or the
os.path.exists. the arrow points on the "c". I tried
it without the c:\ and the arrow pointed on the "s" of
"my documents.
b) I'd like some strings that open other windows
files, documents and web pages etc.
c) I'd be happy to get a list of orders that get me
parts of web pages, for example the headlines of the
NYTimes.
d) It would be great to get a list of web-oriented
orders, but if it's too much to ask - it's too much to
ask.

thank you very very much!
vip333d@yahoo.com

(by the way: Python is a great language!)

__________________________________________________
Do You Yahoo!?
Check out Yahoo! Shopping and Yahoo! Auctions for all of
your unique holiday gifts! Buy at http://shopping.yahoo.com
or bid at http://auctions.yahoo.com


From pythontutor@venix.com  Fri Dec 14 19:59:32 2001
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri, 14 Dec 2001 14:59:32 -0500
Subject: [Tutor] some questions - from a complete newbie
References: <20011214194915.52681.qmail@web12302.mail.yahoo.com>
Message-ID: <3C1A5A24.406@venix.com>

For point a:

try "c:\\my documents\\test.txt"
(the back slash is the escape character for specials so you need two to get one)
or use "raw strings" which exclude specials
r"c:\my documents\test.txt"

vip333d@yahoo.com wrote:

> dear Tutor!
> I'm a newbie, and there are some things that I want to
> do with python, that aren't in the basic web tutorials
> I have read. My OS is win95. I:
> a) cannot execute the os.access(c:\.....) or the
> os.path.exists. the arrow points on the "c". I tried
> it without the c:\ and the arrow pointed on the "s" of
> "my documents.
> b) I'd like some strings that open other windows
> files, documents and web pages etc.
> c) I'd be happy to get a list of orders that get me
> parts of web pages, for example the headlines of the
> NYTimes.
> d) It would be great to get a list of web-oriented
> orders, but if it's too much to ask - it's too much to
> ask.
> 
> thank you very very much!
> vip333d@yahoo.com
> 
> (by the way: Python is a great language!)
> 
> __________________________________________________
> Do You Yahoo!?
> Check out Yahoo! Shopping and Yahoo! Auctions for all of
> your unique holiday gifts! Buy at http://shopping.yahoo.com
> or bid at http://auctions.yahoo.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 dyoo@hkn.eecs.berkeley.edu  Fri Dec 14 21:52:44 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 14 Dec 2001 13:52:44 -0800 (PST)
Subject: [Tutor] some questions - from a complete newbie
In-Reply-To: <20011214194915.52681.qmail@web12302.mail.yahoo.com>
Message-ID: <Pine.LNX.4.21.0112141155120.14128-100000@hkn.eecs.berkeley.edu>

On Fri, 14 Dec 2001 vip333d@yahoo.com wrote:

> I'm a newbie, and there are some things that I want to
> do with python, that aren't in the basic web tutorials
> I have read. My OS is win95. I:
> a) cannot execute the os.access(c:\.....) or the
> os.path.exists. the arrow points on the "c". I tried
> it without the c:\ and the arrow pointed on the "s" of
> "my documents.

Can you show us the error message in more detail?  Usually, the error
underneath shows where Python starts getting confused, but the message
itself is also an important debugging tool.

As a wild guess, I'm guessing that you're trying:

    os.access(c:\foobar.txt)


Python allows things like:

###
>>> def square(x): return x * x
... 
>>> square(square(square(10)))
100000000
###

That is, we can call functions within functions --- we can call commands
within commands.  One consequence about this is that Python will assume
that something like "c:\foobar.txt" looks like a command that should be
executed.  To get it to not try to execute "c:\foobar.txt", we have to
quote it:

    os.access("c:\\foobar.txt")

Quoting in Python is somewhat analogous to quoting in a human language: we
use quotes to make sure no one tries to interpret them as our own words.  
Same principle.



> b) I'd like some strings that open other windows files, documents and
> web pages etc.

Not quite sure about this one.  There's a module called "webbrowser":

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

that will automatically get either IE or Netscape to open an url that you
give it, so that might be useful.  I haven't played with it too much yet.



> c) I'd be happy to get a list of orders that get me parts of web
> pages, for example the headlines of the NYTimes.

This is possible --- many websites support a protocol called RSS:

    http://www.purplepages.ie/rss/

and I'm very sure that there are Python modules out there that can handle
RSS.



> d) It would be great to get a list of web-oriented orders, but if it's
> too much to ask - it's too much to ask.

You might be interested in Useless Python:

    http://www.lowerstandard.com/python/

There should be some scripts there that demonstrate CGI programming.


Good luck to you!



From deliberatus@my995internet.com  Sat Dec 15 04:59:11 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Fri, 14 Dec 2001 23:59:11 -0500
Subject: [Tutor] class and objects and such
Message-ID: <3C1AD89F.1C28AAED@my995internet.com>

ok, I am reading the following:

http://www.ibiblio.org/obp/thinkCSpy/chap12.htm

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

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

http://python.sourceforge.net/devel-docs/lib/module-multifile.html


Clear as mud. It seems to be a dissertation on what is the shape of a
mole of oxygen.

No specific size, shape, or even function, a class defines the general
properties of a entire family opf object,s and you then create specific
objects with refinement of the definition of the general properties, and
special bellial bells, whistles, and GONGS for that indivigual item.

OK so far?

arg. how do I use this? ReadREadReadReadRead...

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From shalehperry@attbi.com  Sat Dec 15 05:45:44 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 14 Dec 2001 21:45:44 -0800 (PST)
Subject: [Tutor] class and objects and such
In-Reply-To: <3C1AD89F.1C28AAED@my995internet.com>
Message-ID: <XFMail.20011214214544.shalehperry@attbi.com>

> 
> No specific size, shape, or even function, a class defines the general
> properties of a entire family opf object,s and you then create specific
> objects with refinement of the definition of the general properties, and
> special bellial bells, whistles, and GONGS for that indivigual item.
> 
> OK so far?
> 
> arg. how do I use this? ReadREadReadReadRead...
> 

You are attacking the probem too hard.

OO is just about creating nouns and giving them the ability to act.  Almost
like creating little robots.  It takes some practice.  After you make a few bad
designs you realize what works.

A common example is a geometry one.

In C (pascal, etc) if you wanted to draw a shape you had to call a function
like 'draw_square(sq)'.  If you wanted a triangle you had to call triangle
functions.  Each time what you were doing and what you were doing it with were
tied together.  If you suddenly needed trapezoids you had to go and find
trapezoid functions and change you code.  OO ties the verbs to the nouns. 
'draw_square' becames 'square.draw'.  This way you can have all of the shapes
knowing how to draw themselves and the code does not care what shape it is.

You may be thinking this is a little esoteric.  So let's come back to a
concrete example you use every day in python.  When you do 'for i in thing' you
are using the power of OO.  The 'in' operator works by calling the
__getitem__() member of thing.  So as long as thing supports __getitem__ you
can loop over it easily.


From jrm@videotron.ca  Sat Dec 15 00:22:45 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Sat, 15 Dec 2001 02:22:45 +0200
Subject: [Tutor] Hummm...dubious behavior.
Message-ID: <000701c184fe$9f1074e0$0100c0a8@videotron.ca>

    Felt ready for Guido's idea of a tutorial, tryed the examples, tryed
some variations, can't help it and here's something curious :

>>> tax=17.5/100
>>> price=3.50
>>> price*tax
0.61249999999999993
>>> price+_
4.1124999999999998
>>> round(_,2)
4.1100000000000003    # in this case : trailing zeros and an error
>>> ui=3.5555
>>> price*ui
12.44425
>>> round(_,2)
12.44                               # here the expectec behavior
>>> tax*ui
0.62221249999999995
>>> round(_,2)
0.62                                 # here just as well

Obviously my question is what caused the difference in behavior, when must I
expect it or best how to avoid it since, really, I can't imagine a use for
the "long" version.

Thanks gang.

Jean M.




From i812@iname.com  Sat Dec 15 07:38:25 2001
From: i812@iname.com (Rob McGee)
Date: Sat, 15 Dec 2001 01:38:25 -0600
Subject: [Tutor] class Clowning: saving references to other instances
Message-ID: <20011215013825.C3310@hal>

Okay, here's what I have: a class of objects placed on a grid referenced
with X, Y coordinates. Need an example? Here:

{code}
from string import uppercase    # letters A to Z

class Clown:
  def __init__(self, location, index, gridSize=16, uppercase=uppercase):
    self.location = location    # an integer, unique
    self.index = index          # also unique integer
    self.name = uppercase[index]  # uppercase letter, also unique
    self.coord = divmod(location, gridSize) # X, Y tuple
  def __str__(self):
    return self.name
  ... and so on

import random

def makeClowns(numClowns=16, gridSize=16):
  gridAvail = range(gridSize**2)  # default grid of 256
  clowns = []
  for index in range(numClowns):
    # select a random number from gridAvail and remove it from the list
    location = gridAvail.pop(random.randrange(len(gridAvail)))
    clown = Clown(location, index)  # create instance
    clowns.append(clown)        # save it in a list
  return clowns                 # return list of Clowns

clowns = makeClowns()
{/code}

(Those of you who remember my prior posts may notice that I've taken
some of your suggestions. :)

*** the problem ***
There are other methods, including one which calculates the distance
from one Clown instance to another. The distance(self, other) method
uses "exec" to store the distance values in self.(other.name) and in
other.(self.name) (such as "self.A" and "other.Z" for the distance
between the instances named A and Z.) Because it's tied to the way I'm
storing these instances, I don't like the way it works -- if I change
how the data is stored I'll also have to change the class method.

The reason why I'm doing this is just to save a little redundant
processing. The distance() method checks for the existance of the self.A
(or other such attribute) before calculating, and returns that if it
exists. It's all on a pretty small scale (note the default gridSize
value) so it probably doesn't matter much if I were to let it redo the
calculations every time. The distance calculation is not very intense,
probably: just your basic Pythagorean theorem:
{code}
    diffX = abs(self.coord[0] - other.coord[0]) # difference in X coord.
    diffY = abs(self.coord[1] - other.coord[1]) # difference in Y coord.
    distance = ((diffX ** 2) + (diffY ** 2)) ** 0.5
{/code}

One solution would be to put the "exec" code in a function rather than
in the class method, but the class distance() method would still have to
rely on eval() -- and thus on the external data structure! -- to
retrieve the value. Am I right?

Maybe rather than storing all the distances as separate attributes, I
should maintain them all in a single self.distances list:
    [(B, 5.0), (C, 1.414), (D, 7.6645), ...]
Then the distance(self, other) method filters self.distances for
"x[0] == str(other)". If found, return x[1], otherwise calculate the
distance and store it...
    self.distances.append((other.name, distance))
    other.distances.append((self.name, distance))
Simple, no "exec" statement to write nor eval() function to read the
values, and everything's done cleanly within the class methods.

Have I figured out my own solution?!? :) ("Operator, you can forget
about this call ... There's no one there I really wanted to talk
to!" :)[1] Anyway, comments would be appreciated, whether they're other
ideas or confirmation that I'm on the right track.

Really, I figured that out while I was writing this message. It sure
does some good to get away from IDLE every now and then. :)

    Rob - /dev/rob0

[1] from an old Jim Croce song, "Operator", appx. 1971 (?)


From myuen@ucalgary.ca  Sat Dec 15 08:36:35 2001
From: myuen@ucalgary.ca (Mike Yuen)
Date: Sat, 15 Dec 2001 01:36:35 -0700 (MST)
Subject: [Tutor] Log analyzer
Message-ID: <Pine.A41.4.10.10112150128030.70516-100000@acs2.acs.ucalgary.ca>

I'm trying to make a little log analyzer for myself and the problem is, I
want to split each line which initially looks like:

FWIN,2001/09/14,01:44:53 -6:00GMT,24.68.251.251:137,24.53.33.12:137,UDP

I used the split function and got:
'FWIN,2001/09/14,01:44:53', '-6:00', 'GMT,<bunch of numbers here>'

I want each sections boundries to be BETWEEN the commas.  So, for example:
FWIN is one section
2001/09/14 is another
01:44:53 -6:00GMT is yet another.

* Note: each sections size will vary in size.

I know I can take a another pass over the line but i've got literally
1000's of lines to process and taking 2 passes over each line really slows
things done.  So, is  there an efficient way to split the lines?






From dyoo@hkn.eecs.berkeley.edu  Sat Dec 15 08:48:15 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 15 Dec 2001 00:48:15 -0800 (PST)
Subject: [Tutor] Log analyzer
In-Reply-To: <Pine.A41.4.10.10112150128030.70516-100000@acs2.acs.ucalgary.ca>
Message-ID: <Pine.LNX.4.21.0112150044330.32514-100000@hkn.eecs.berkeley.edu>

On Sat, 15 Dec 2001, Mike Yuen wrote:

> I'm trying to make a little log analyzer for myself and the problem is, I
> want to split each line which initially looks like:
> 
> FWIN,2001/09/14,01:44:53 -6:00GMT,24.68.251.251:137,24.53.33.12:137,UDP
> 
> I used the split function and got:
> 'FWIN,2001/09/14,01:44:53', '-6:00', 'GMT,<bunch of numbers here>'
> 
> I want each sections boundries to be BETWEEN the commas.  So, for example:
> FWIN is one section
> 2001/09/14 is another
> 01:44:53 -6:00GMT is yet another.
> 
> * Note: each sections size will vary in size.
> 
> I know I can take a another pass over the line but i've got literally
> 1000's of lines to process and taking 2 passes over each line really slows
> things done.  So, is  there an efficient way to split the lines?

Sounds like you want to split along the commas.  The default that split()
uses is whitespace, because it's a "common case" that people run into all
the time.  However, split() can take in an optional "delimiter" parameter.  
Take a look:

###
>>> string.split('supercalifragilisticexpialidocious', 'i')
['supercal', 'frag', 'l', 'st', 'cexp', 'al', 'doc', 'ous']
###


Good luck!



From dyoo@hkn.eecs.berkeley.edu  Sat Dec 15 09:03:10 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 15 Dec 2001 01:03:10 -0800 (PST)
Subject: [Tutor] class and objects and such  [Robot wars!]
In-Reply-To: <XFMail.20011214214544.shalehperry@attbi.com>
Message-ID: <Pine.LNX.4.21.0112150054300.32514-100000@hkn.eecs.berkeley.edu>

On Fri, 14 Dec 2001, Sean 'Shaleh' Perry wrote:

> > No specific size, shape, or even function, a class defines the general
> > properties of a entire family opf object,s and you then create specific
> > objects with refinement of the definition of the general properties, and
> > special bellial bells, whistles, and GONGS for that indivigual item.
> > 
> > OK so far?
> > 
> > arg. how do I use this? ReadREadReadReadRead...
> > 
> 
> You are attacking the probem too hard.
> 
> OO is just about creating nouns and giving them the ability to act.  
> Almost like creating little robots.


Hmmm... as a random note, I do remember reading about how people
introduced object oriented programming through simulating robots in an
arena:

    http://www.geocities.com/TimesSquare/6120/robots/index.html
    http://www.pythonpros.com/gstein/bots.html
    http://www.lysator.liu.se/realtimebattle/



From lonetwin@yahoo.com  Sat Dec 15 09:20:51 2001
From: lonetwin@yahoo.com (lonetwin)
Date: Sat, 15 Dec 2001 01:20:51 -0800 (PST)
Subject: [Tutor] Log analyzer
In-Reply-To: <Pine.A41.4.10.10112150128030.70516-100000@acs2.acs.ucalgary.ca>
Message-ID: <20011215092051.97398.qmail@web20703.mail.yahoo.com>

Hi Mike,
    The split function takes an optional 'sep' argument which defaults to a
whitespace character. My usual way of doing things like this is:

fl = [ s.strip() for s in open(filename).readlines() ]
for line in fl:
    print line.split(',')

Remember tho' that if you are using a python version < 2.0 (i think ??) you'd
have to do something like:

fl=[]
for s in open(filename).readlines()
    fl.append(s.strip())
import string
for line in fl:
    string.split(line, ',')

hope that helps

--- Mike Yuen <myuen@ucalgary.ca> wrote:
> I'm trying to make a little log analyzer for myself and the problem is, I
> want to split each line which initially looks like:
> 
> FWIN,2001/09/14,01:44:53 -6:00GMT,24.68.251.251:137,24.53.33.12:137,UDP
> 
> I used the split function and got:
> 'FWIN,2001/09/14,01:44:53', '-6:00', 'GMT,<bunch of numbers here>'
> 
> I want each sections boundries to be BETWEEN the commas.  So, for example:
> FWIN is one section
> 2001/09/14 is another
> 01:44:53 -6:00GMT is yet another.
> 
> * Note: each sections size will vary in size.
> 
> I know I can take a another pass over the line but i've got literally
> 1000's of lines to process and taking 2 passes over each line really slows
> things done.  So, is  there an efficient way to split the lines?


__________________________________________________
Do You Yahoo!?
Check out Yahoo! Shopping and Yahoo! Auctions for all of
your unique holiday gifts! Buy at http://shopping.yahoo.com
or bid at http://auctions.yahoo.com


From vip333d@yahoo.com  Sat Dec 15 14:46:33 2001
From: vip333d@yahoo.com (vip333d@yahoo.com)
Date: Sat, 15 Dec 2001 06:46:33 -0800 (PST)
Subject: [Tutor] (no subject)
Message-ID: <20011215144633.60226.qmail@web12308.mail.yahoo.com>

os: win95
I've read the answers to my questions - but none of
them work!
a) when I type in python - os.access('c:\...')- it
points on the ")" and says "invalid tolken" when I
write: os.access(c:\\...) - it points on the ":" and
says:
"syntax error: invalid syntax"
b) i've tried an order that was in
"www.python.org/doc/lib...": open_new(www...), and it
said: "name error: open_new is not defined"

thank you very much!
vip333d@yahoo.com

__________________________________________________
Do You Yahoo!?
Check out Yahoo! Shopping and Yahoo! Auctions for all of
your unique holiday gifts! Buy at http://shopping.yahoo.com
or bid at http://auctions.yahoo.com


From lumbricus@gmx.net  Sat Dec 15 16:16:50 2001
From: lumbricus@gmx.net (Joerg Woelke)
Date: Sat, 15 Dec 2001 17:16:50 +0100
Subject: [Tutor] (no subject)
In-Reply-To: <20011215144633.60226.qmail@web12308.mail.yahoo.com>; from vip333d@yahoo.com on Sat, Dec 15, 2001 at 06:46:33AM -0800
References: <20011215144633.60226.qmail@web12308.mail.yahoo.com>
Message-ID: <20011215171650.A3256@Laplace.localdomain>

On Sat, Dec 15, 2001 at 06:46:33AM -0800, vip333d@yahoo.com wrote:
> os: win95
> I've read the answers to my questions - but none of
> them work!
> a) when I type in python - os.access('c:\...')- it
> points on the ")" and says "invalid tolken" when I
> write: os.access(c:\\...) - it points on the ":" and

How about 'os.access("c:\\...")'?

> says:
> "syntax error: invalid syntax"

because colons have a special meaning.

> b) i've tried an order that was in
> "www.python.org/doc/lib...": open_new(www...), and it
> said: "name error: open_new is not defined"
> 
> thank you very much!
> vip333d@yahoo.com
> 

HTH, HAND and Greetings
J"o!

-- 
I hate it when my foot falls asleep during the day cause that means
it's going to be up all night.
		-- Steven Wright


From karthikg@aztec.soft.net  Sat Dec 15 16:32:35 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Sat, 15 Dec 2001 22:02:35 +0530
Subject: [Tutor] apply help  (newbie)
In-Reply-To: <20011215144633.60226.qmail@web12308.mail.yahoo.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDCEMBCLAA.karthikg@aztec.soft.net>

import sys
from qt import *


class Button(QPushButton):
	def __init__(self,*args):
		#QPushButton.__init__(self,args)		##### This does not work
		apply(QPushButton.__init__,(self,)+args)  ##### But this works
		self.setText("hello")
		
class MainWindow(QMainWindow):
	def __init__(self,*args):
		#QMainWindow.__init__(self,args)
		apply(QMainWindow.__init__,(self,)+args)
		self.button = Button(self)
		self.setCentralWidget(self.button)
		self.button.show()                                              
    
if __name__ == '__main__':
	args = sys.argv
	app=QApplication(args)                                 
	win= MainWindow()
	win.show()
	app.exec_loop()                                            


can someone tell me as to what is the difference between these 2 calls:

		QPushButton.__init__(self,args)		...1
		apply(QPushButton.__init__,(self,)+args)  ...2


thnx in advance,
karthik.
        


From jrm@videotron.ca  Sat Dec 15 09:31:01 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Sat, 15 Dec 2001 11:31:01 +0200
Subject: [Tutor] (no subject)
References: <20011215144633.60226.qmail@web12308.mail.yahoo.com>
Message-ID: <000d01c1854b$36a1cf60$0100c0a8@videotron.ca>

----- Original Message ----- 
From: <vip333d@yahoo.com>
To: <tutor@python.org>
Sent: Saturday, December 15, 2001 4:46 PM
Subject: [Tutor] (no subject)


> when I
> write: os.access(c:\\...) - it points on the ":" and

You just forgot to put the quotes this time, that'all.

Should have been : 
    os.access("c:\\.........\\..........) etc...
or
    os.access(r"c:\..........\.......)etc...

Try it and let us know.

Jean M.



From shalehperry@attbi.com  Sat Dec 15 16:37:13 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sat, 15 Dec 2001 08:37:13 -0800 (PST)
Subject: [Tutor] apply help  (newbie)
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDCEMBCLAA.karthikg@aztec.soft.net>
Message-ID: <XFMail.20011215083713.shalehperry@attbi.com>

> 
> can someone tell me as to what is the difference between these 2 calls:
> 
>               QPushButton.__init__(self,args)         ...1

args is a tuple containing the options passed to Button.__init__ QPushButton
does not take a tuple as its arguments I suspect

>               apply(QPushButton.__init__,(self,)+args)  ...2

passes a tuple (self, args) to QPushButton.__init__ via apply which turns the
arg tuple into the arguments QPushButton is expecting.  In python 2.1 and newer
you can call 

QPushButton.__init__(self, *args) # pass argument tuple through to function.

In 1.x you have only apply() to use.


From karthikg@aztec.soft.net  Sat Dec 15 17:30:32 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Sat, 15 Dec 2001 23:00:32 +0530
Subject: [Tutor] apply help  (newbie)
In-Reply-To: <XFMail.20011215083713.shalehperry@attbi.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDAEMCCLAA.karthikg@aztec.soft.net>

thanks for the explanation.
This is what i understood..please correct me if i'm wrong.

i did a

print type(*args) => turned out to be an instance of something
print type(args) => a tuple as expected.

so when i say ,

QPushButton.__init__(self,args)    # i'm passing the tuple directly rather
than the instance *args

so it failed as QPushButton does not take a tuple but instead requires
that instance (*args) in this case.

>>> def func(*args):
...     for arg in args:
...             print arg
...
>>>
>>> def call(*args):
...     func(args)
...
>>> call(1,2,3,4)
(1, 2, 3, 4)
>>> def call(*args):
...     func(*args)
...
>>> call(1,2,3,4)
1
2
3
4
>>> def call(*args):
...     apply(func,args)
...
>>> call(1,2,3,4)
1
2
3
4
>>> def call(*args):
...     apply(func,*args)
...
>>> call(1,2,3,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in call
TypeError: apply() takes at most 3 arguments (5 given)
>>>

*args is instance of which class?
why do i get a type error in the end when i try passing that instance to
func?
it's saying am passing 5 arguments when in reality am passing only one (ie
*args) ?

thanks ,
karthik.


-----Original Message-----
From: Sean Perry [mailto:shaleh@one.local]On Behalf Of Sean 'Shaleh'
Perry
Sent: Saturday, December 15, 2001 10:07 PM
To: karthik Guru
Cc: tutor@python.org
Subject: Re: [Tutor] apply help (newbie)


>
> can someone tell me as to what is the difference between these 2 calls:
>
>               QPushButton.__init__(self,args)         ...1

args is a tuple containing the options passed to Button.__init__ QPushButton
does not take a tuple as its arguments I suspect

>               apply(QPushButton.__init__,(self,)+args)  ...2

passes a tuple (self, args) to QPushButton.__init__ via apply which turns
the
arg tuple into the arguments QPushButton is expecting.  In python 2.1 and
newer
you can call

QPushButton.__init__(self, *args) # pass argument tuple through to function.

In 1.x you have only apply() to use.



From shalehperry@attbi.com  Sat Dec 15 17:19:42 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sat, 15 Dec 2001 09:19:42 -0800 (PST)
Subject: [Tutor] apply help  (newbie)
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDAEMCCLAA.karthikg@aztec.soft.net>
Message-ID: <XFMail.20011215091942.shalehperry@attbi.com>

>>> def call(func, *args):
...     print type(*args)
...     apply(func, args)
... 
>>> def foo(a,b,c):
...     print a, b, c
... 
>>> call(foo, 1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in call
TypeError: type() takes exactly 1 argument (3 given)

*args is python magic for 'expand me in place'.


From shalehperry@attbi.com  Sat Dec 15 17:24:56 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sat, 15 Dec 2001 09:24:56 -0800 (PST)
Subject: [Tutor] apply help  (newbie)
In-Reply-To: <XFMail.20011215091942.shalehperry@attbi.com>
Message-ID: <XFMail.20011215092456.shalehperry@attbi.com>

On 15-Dec-2001 Sean 'Shaleh' Perry wrote:
>>>> def call(func, *args):
> ...     print type(*args)
> ...     apply(func, args)
> ... 
>>>> def foo(a,b,c):
> ...     print a, b, c
> ... 
>>>> call(foo, 1, 2, 3)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 2, in call
> TypeError: type() takes exactly 1 argument (3 given)
> 
> *args is python magic for 'expand me in place'.
> 


>>> def call(func, *args, **kwargs):
...     print len(args)
...     print len(kwargs)
...     apply(func, args, kwargs)
... 
>>> call(foo, a=1, c=3, b=2)
0
3
1 2 3

Just wanted to show you the keyword args syntax while we were discussing nifty
ways to call functions.


From karthikg@aztec.soft.net  Sat Dec 15 17:49:36 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Sat, 15 Dec 2001 23:19:36 +0530
Subject: [Tutor] apply help  (newbie)
In-Reply-To: <XFMail.20011215092456.shalehperry@attbi.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDKEMCCLAA.karthikg@aztec.soft.net>

great! thanks for the explanations:
> 
> *args is python magic for 'expand me in place'.
> 
this statement cleared my doubts!

karthik.






From james2dope@yahoo.com  Sat Dec 15 17:55:52 2001
From: james2dope@yahoo.com (james middendorff)
Date: Sat, 15 Dec 2001 09:55:52 -0800 (PST)
Subject: [Tutor] off the subject
Message-ID: <20011215175552.67794.qmail@web13903.mail.yahoo.com>

I just wanted to tell everyone of something that I saw
today. Now I can finally get rid of Win9x, because you
can play windows games like The Sims and Diablo2 on
linux boxes! Using software called WineX frin www.transgaming.com!

=====
"I would kill everyone in this room
    for a drop of sweet beer."
     ----Homer Simpson----

__________________________________________________
Do You Yahoo!?
Check out Yahoo! Shopping and Yahoo! Auctions for all of
your unique holiday gifts! Buy at http://shopping.yahoo.com
or bid at http://auctions.yahoo.com


From deliberatus@my995internet.com  Sat Dec 15 19:00:29 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sat, 15 Dec 2001 14:00:29 -0500
Subject: [Tutor] class and objects and such
References: <XFMail.20011215090649.shalehperry@attbi.com>
Message-ID: <3C1B9DCD.1D9D8038@my995internet.com>

Ok, first, do you like to be addressed as Sean, Shaleh, Mr Perry, or
something REALLY silly?

Second, I have taken your gentle repremand to heart regarding line
length. Here is a somewhat updated posting of the latest edition of the
script, WITH SHORTER LINES.

Sean 'Shaleh' Perry wrote:
> 
> On 15-Dec-2001 Kirk Bailey wrote:
> > Antacid pills?
> 
> because you do not honour the tradition of !80! chars per line.  Which is why
> wordwrap is an issue.
> 
> The common commenting style is a block of comments and then a block of code.
> If a comment is required on this line it is usually a simple, short blurb.
> 
> ## This is the setup for my cool function.
> ## Preconditions: we have an open file
> ## Postconditions: message will be a dictionary containing the rfc822 parsed
> ## contents of the file
> def myfunc(file):
>         ....
>         ....
>         message = Message(file) # feed the whole file to rfc822's Message class
>         ....
>         ....
> 
> > Well, at least it is liberally commented. BEWARE WORDWRAP! it is
> > attached.
> >
> 
> Ok, let's start simply.  Have you read the top of rfc822.py?  Which also
> appears a rfc822.__doc__.
> 
> If so, could you point out where in your code you are having problems?  More
> than happy to help, just need a starting point.

0--------1---------2---------3---------4---------5---------6---------7----------8---------9
#!/usr/local/bin/python
# Tinylist MLM Pitchtime module.
# COPYRIGHT 2002 Kirk D Bailey
# And made available under the GNU GPL.
###################################################################################
# You should have received a copy of the GNU General Public
License               #
# along with this program; if not, write to the Free
Software                     #
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
USA.     #
# Also, the GNU GPL may be viewed online at
http://www.gnu.org/licenses/gpl.html  #
###################################################################################
#
#   "The tyrant's foe, the people's friend, a free press." -Dr Benjamin
Franklin.
#
##################################################################
# Python can be studied and aquired at http://www.python.org/ !!!
##################################################################
#
# This module only handles receiving and sending out postings to a list.
# management of membership is handled by the favored command module
# - TLwebcommand, TLemailcommand, or both.
#
# we now import some functions from assorted libraries.

import sys, re, string, rfc822, smtplib, os.path

# someday we will collect each needed function
# and create a module just of those and distribute it
# with tinylist.

# make sure you set this to YOUR domain!
localhost = 'mydomain.foo'

# next line declares the path to stuff. DEFINE IT for *YOUR* server!
path = '/www/www.howlermonkey.net/cgi-bin'
# to the cgi-bin for your web dir,
# with no trailing '/'!
# note this tells TL where to start looking.
# everything is either here, or under this
# point in '/lists/' dir, mostly in '/lists/'.
					
# we read a command line arguement to determine the list name
listname = sys.argv[1]
# Arguement 0 is the name of the script run, 1 is the
# first arguement after that name in the command line,
# so this tells us the name of the email identity being addressed-
listname!

					
# variable 'incoming' receives the entire incoming message
# which is piped to the script on <stdin> which this reads by the alias
# such as:
#         foolist:"|/pathtoprogram/programname foolist"
incoming = raw_input.lines()




# this block will contain the rfc822 decoding code when we get it
finished.
# Using rfc822.py, we digest the message and make parts available to the
program.
message = rfc822.message(incoming)
pass
pass
pass
# end of dummycode. Hereafter we act as if it is decoded.
# The information is in the dictionary 'message', each item keyed with
the header's
# name. The BODY of that dictionary is in the string 'msg'. So are any
attachments.

from = message.getAddr("From")	# we must dig out the 'from: ' field
contents
# Note we already know who it is TO - 'listname' !
# Remember, the mail ssytem fed it here with a command
# line arguement, after sorting it out to a known identity,
# so the list's defining alias contains that info.

Strip whitespace chars off every element in the list passed to this
function.
def gangstrip(str):					# ok, everybody STRIP!
	index = 0						# initiate counter=0
	while index<len(str)				# define loopp terination
		str[index]=string.strip(str[index])	# and strip each element.
		index=index+1				# increase the index pointer

# ok, let's read that membership file. it is named (listname) with no
name extension.
open a.file(path + "/lists/" + listname, 'r')						
members = a.readlines()					# read all of it in.
a.close()							# and close the file

# then we look to see if that FROM exists in the membership.
# clean it up;
gangstrip(members)	# strip all leading and trailing whitespace
				# from each element in the list 'members'.

# then we look to see if the sender is a member of the list:
if from in members :	# IF the sender is in the subscriber file, 
	subject = '[' + listname + ']' + subject	# then accept the submission.
	if os.path.exists(path + "/lists/" +listname +".replyto"):	
		Reply_to = "Reply-to: " + listname + "@" + localhost + CRLF # set the
optional
	else:			# Reply-to: field.
		Reply_to = ""	# if not, this string
				# is NULL.

	X-Loop = "X-Loop: " + listname + "@" + localhost	# This breaks email 
								# loops from forming

	if os.path.exists(path + "/lists/" + listname + ".footer"):	# if there
is a 
									# footer, read it!
		ftr = open(path + "/lists/" + listname + ".footer",'r')	# read the
footer
									# file
		footer = ftr.readlines()				# into 'ftr'
									# 
		ftr.close()						# close that file,
		msg = msg + footer + CRLF				# and append it to 
									# the message. 

	if os.path.exists(path + "/lists/"+listname+".random"):	# if this list
has a random 
								# rotation file,
		f1=open("./lists/"+listname+".random",'r')	# Open the random footer
								# rotation file
		randomline=gangstrip(f1.readlines())		# load the contents of the
								# rotation
		f1.close()					# then close the file
		msg = msg + randomline + CRLF			# and add the random element 								#
to the footer.
			
# this end processing for an acceptable posting. Next block handles
process for REJECTED postings.
			
else								# BUT IF THEY ARE NOT
								# SUBSCRIBED...
	listnamemembers = from					# put poster addres as the
								# recipient in list
								# 'listnamemembers'
	msg = ""						# and clear the mesage.
	From = "From: tinylist@" + localhost + \n 		#
From:tinylist@mydomain.foo!
	Subject = "Subject: Unauthorized posting to list: " + listname + \n #
Set subject
	Reply_to = "Reply-to: postmaster@" + localhost + \n 	# replys go to the
Postmaster
	X-Loop = "X-Loop: postmaster@" + localhost		# This breaks email
loops 								# from forming
	msg = """
		
		To whom it may concern;
		
		Sorry, but as you are not a current member of """ + listname + """, 
		you may not post to it. Your recent posting has been rejected and
destroyed.
		
		Feel free to contact the postmaster if there is any question.
		Any reply to this letter should go directly to the postmaster.
		
		You can also subscribe to this list if you like.
		
		Goodbye.
		
		"""

# ABOVE IS 1 BLANK LINE, DO NOT DELETE IT!
# BTW, that was the end of the ELSE clause from way above.
# there cannot be comments in those line  				
# above this one, or they would be part
# of the triplequoted string!
# ok, if they are not a member, THEY GET 
# THE REPLY SHOWN ABOVE MAILED TO THEM! 
# (Maybe we could read a stock answer from a file?)
# there is no endif or fi in python.
# whitespace and tabulation therefore
# is rather important here.

# now we send whatever message is to go out to 
# whatever is in the recipient list.
server = smtplib.SMTP('localhost')	# setup for a smtp run.
# helo(localhost)			# open a connection to the smtp server,
					# possibly not needed
					# so it is commented out. If all else fails, use it.
server.connect()			# and log in to the thing
					# as the identity this script runs as.
for to in listnamemembers :		# for each address in the list
listnamemembers,
	server.sendmail(from, to, Subject, reply-to, X-Loop, msg)	# send
envlope and msg!
									# don't delete this line!
server.quit()								# then close the connection.

# make sure this script runs as a TRUSTED USER-
# and NOT as root!!! You set that up in the Sendmail
# Config file (sendmail.cf).
# Make sure that a NON-priviliged user OWNS
# this script, and that it runs as that identity!
#
# this list is devloped by THE OLD FART and a fine bunch of
# dingleberrys at www.tinylist.org where you can hop on the
# bandwagon at your convience.
#
# We have lists there, which only seems right somehow.
# they are:
# tinylist-users - discussion for all aspects of using 
#                  tinylist; somewhat technical.
# tinylist-chat - for all intrested in tl, lists, python,
#                 email: a broad charter! 
# tinylist-devlopers - discussion of new versions, features, 
#                      and bugchasing.
# evil-humnor - sick, raunchy, crusty, cynical, depraved, 
#               deprived humor? OVER HERE!
# Fnord.
------------------------------end compressed
bits------------------------------

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From tim.one@home.com  Sat Dec 15 20:34:06 2001
From: tim.one@home.com (Tim Peters)
Date: Sat, 15 Dec 2001 15:34:06 -0500
Subject: [Tutor] Hummm...dubious behavior.
In-Reply-To: <000701c184fe$9f1074e0$0100c0a8@videotron.ca>
Message-ID: <LNBBLJKPBEHFEDALKOLCGEHKMNAA.tim.one@home.com>

[Jean Montambeault]
>     Felt ready for Guido's idea of a tutorial, tryed the examples, tryed
> some variations, can't help it and here's something curious :
>
> >>> tax=17.5/100
> >>> price=3.50
> >>> price*tax
> 0.61249999999999993
> >>> price+_
> 4.1124999999999998
> >>> round(_,2)
> 4.1100000000000003    # in this case : trailing zeros and an error
> >>> ui=3.5555
> >>> price*ui
> 12.44425
> >>> round(_,2)
> 12.44                               # here the expectec behavior
> >>> tax*ui
> 0.62221249999999995
> >>> round(_,2)
> 0.62                                 # here just as well
>
> Obviously my question is what caused the difference in behavior,
> when must I expect it or best how to avoid it since, really, I can't
> imagine a use for the "long" version.

This kind of stuff is explained in a new (for Python 2.2) Tutorial appendix.
You can read it now here:

    http://python.sourceforge.net/devel-docs/tut/node14.html

Python 2.2 final should be released next Friday.

This example in the tutorial has also been changed, but in a devious way, to
use numbers that happen to display in a prettier way:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
>>>



From karthikg@aztec.soft.net  Sat Dec 15 18:59:13 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Sun, 16 Dec 2001 00:29:13 +0530
Subject: [Tutor] why BaseClass.__init__ needs to be called explicitly?
In-Reply-To: <000d01c1854b$36a1cf60$0100c0a8@videotron.ca>
Message-ID: <NEBBJNMDEKBIBCMCNMBDMEMDCLAA.karthikg@aztec.soft.net>

1. I was just wondering why does'nt python call the base class constructor
automatically like in java? I noticed that it does provided i don't've a
__init__() in the derived class.
why do i need to make an explict call. I noticed that even perl asks us to
do this explicitly.
Is there any specific reaosn behind this...something to do with scripting
languages?

is __init__ also treated as a normal method and since we override it in
derived class , it does 'nt call the base implementation automatically?

2. do we have a search facility on tutor/python-list sites? i c'd'nt find
one.

thanks,
karthik.











From jrm@videotron.ca  Sat Dec 15 14:10:28 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Sat, 15 Dec 2001 16:10:28 +0200
Subject: [Tutor] Hummm...dubious behavior.
References: <LNBBLJKPBEHFEDALKOLCGEHKMNAA.tim.one@home.com>
Message-ID: <000501c18572$400c5300$0100c0a8@videotron.ca>

----- Original Message -----
From: "Tim Peters" <tim.one@home.com>
>
> This example in the tutorial has also been changed, but in a devious way,
to
> use numbers that happen to display in a prettier way:

    Yah! It's going to give a bad name to the concept of deviance ;)

>
> >>> tax = 12.5 / 100
> >>> price = 100.50
> >>> price * tax
> 12.5625
> >>> price + _
> 113.0625
> >>> round(_, 2)
> 113.06
> >>>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



From dyoo@hkn.eecs.berkeley.edu  Sat Dec 15 21:51:36 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 15 Dec 2001 13:51:36 -0800 (PST)
Subject: [Tutor] (no subject)
In-Reply-To: <20011215144633.60226.qmail@web12308.mail.yahoo.com>
Message-ID: <Pine.LNX.4.21.0112151325260.10908-100000@hkn.eecs.berkeley.edu>

On Sat, 15 Dec 2001 vip333d@yahoo.com wrote:

> a) when I type in python - os.access('c:\...')- it points on the ")"
> and says "invalid tolken"

Can you show us the error message verbatim?  You don't have to paraphrase
the few lines of error messages.  When we're catching bugs like this, we
really do need to see everything that Python's saying, even if it looks
ugly.  Think of it as detective work.  *grin*

Don't feel bad by cutting and pasting error messages: we don't mind
looking at them.


For example, if we had done something like this:

##
>>> os.access(c:\hello.world)
###


It becomes very useful if we can see the error in its context:

###
>>> os.access(c:\hello.world)
  File "<stdin>", line 1
    os.access(c:\hello.world)
               ^
SyntaxError: invalid syntax
###


For your bug, I can imagine a few things that might cause a "Token" error
like that:

###
>>> os.access("c:\index.html\"))
  File "<stdin>", line 1
    os.access("c:\index.html\"))
                               ^
SyntaxError: invalid token
###

but I really don't feel comfortable guessing things, just because what I'm
imagining can be pretty wild and wide off the mark.  *grin*



Also, try not to use '...' when you're showing us what you're doing: we
really need to see exactly what you're passing into os.access().


This is particularly important with os.access(), because it takes two
arguments:

###
>>> os.access.__doc__
'access(path, mode) -> 1 if granted, 0 otherwise\nTest for access to a
file.'
>>> os.access(".bash_profile")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: access() takes exactly 2 arguments (1 given)
###

and if we try calling it with just 1, Python corrects us by saying that we
need to give it 2 arguments.


Here's an example call to os.access():

###
>>> os.access(".bash_profile", os.F_OK)
1
>>> os.access("the_princess_and_the_pea", os.F_OK)
0
###


The documentation here shows the modes you can use with os.access to test
certain things (like existance, readibility, writability, or
executability):

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




> b) i've tried an order that was in
> "www.python.org/doc/lib...": open_new(www...), and it
> said: "name error: open_new is not defined"

I see that you're using the webbrowser.open_new() function in:

    http://www.python.org/doc/lib/module-webbrowser.html#l2h-2158

When we're using module functions like webbrowser.open_new(), we need to
say something like this:

###
>>> webbrowser.open_new("http://python.org")
###


If we see something like this when running the above:

###
>>> webbrowser.open_new("http://python.org")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'webbrowser' is not defined
###

it just means that we need to tell Python in advance to prepare the
webbrowser module for us, by using an 'import' command:

###
>>> import webbrowser
>>> webbrowser.open_new("http://python.org")
###


We can do searches on Tutor from Activestate's search site:

    http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor



Good luck to you, and please feel free to ask questions.



From jrm@videotron.ca  Sat Dec 15 16:16:51 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Sat, 15 Dec 2001 18:16:51 +0200
Subject: [Tutor] (no subject)
Message-ID: <000901c18583$e80164e0$0100c0a8@videotron.ca>

----- Original Message -----
From: "Jean Montambeault" <jrm@videotron.ca>
To: <vip333d@yahoo.com>; <tutor@python.org>

    Hmmmmm! I had a little time on my hands and tried this :
>>> os.access(r"c:\essai.py", os.R_OK)
1
>>> os.access(r"c:\essai.py", os.W_OK)
1

and it works, as you can see,  but:

>>> os.access("c:\essai.py", os.W_OK)
1
>>> os.access("c:\essasdafis.py", os.W_OK)
0
>>>

works too so the os module takes care of the backslash problem as it seems.
It wouldn't work for :
rich=open("c:\my file\ my beautiful file", "w")
you must use the "r" or "\\" with open() there.
That way I assumed that it would be the same for "os.access()"
and now I'm consumed by shame. :o(

This said, since it all works fine here, cut and paste your messages as
Danny suggested : the solution can't be very far.

    Jean M.




From wilson@visi.com  Sat Dec 15 23:25:18 2001
From: wilson@visi.com (Timothy Wilson)
Date: Sat, 15 Dec 2001 17:25:18 -0600 (CST)
Subject: [Tutor] Useless (not interesting) little script
Message-ID: <Pine.GSO.4.21.0112151715560.16392-100000@isis.visi.com>

Hi everyone,

Here's something that I whipped up this afternoon. I've always found it
interesting to look for dates that combine to form little arithmetic
expressions. For example, Jan. 2, 2002 is one because 1 x 2 = '02. Likewise,
Feb. 2, 2004 (2 + 2 = '04) and Dec. 2, 2006 (12 / 2 = '06) also work.

Interestingly, I don't think it's necessary to consider leap years in this
script. I can't think of any combination of 2 and 29 that would make a year
this is a leap year. I put it in anyway because the extra check makes no
observable difference in execution speed (for a 1,000 years or so anyway).

Rob, feel free to add this to Useless Python. (I think it qualifies. :-)

Try to guess how many such dates exist in the next millenium and then run
the program. My guess wasn't very close. :-)

-Tim

#!/usr/bin/env python
#
# calmath.py by Tim Wilson <wilson@visi.com>
# This program looks for dates that fit into a simple arithmetic expression.
# The dates are expressed in the typical American format of 
# <Month> <Day>, <Year>
#
# Some matching dates would include:
#     Jan. 2, 2003   (1 + 2 = 3)
#     Oct. 3, 2007   (10 - 3 = 7)
#     Apr. 10, 2040  (4 x 10 = 40)
#     Aug. 2, 2004   (8 / 2 = 4)
#
# The program correctly takes leap years into account, but I don't think
it's
# actually necessary. I can't think of any combination of 2 and 29 that
would
# be a leap year.

def isLeap(year):
    if year % 400 == 0:
        return 1
    elif year % 10 == 0:
        return 0
    elif year % 4 == 0:
        return 1
    else:
        return 0

def calmath(startYear, endYear):
    datesFound = 0
    monthNames = {1:'Jan.', 2:'Feb.', 3:'Mar.', 4:'April', 5:'May',
6:'June',
                 7:'July', 8:'Aug.', 9:'Sept.', 10:'Oct.', 11:'Nov.',
12:'Dec.'}
    daysInMonths = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30,
                    10:31, 11:30, 12:31}
    for year in range(startYear, endYear+1):
        yr = int(str(year)[-2:])
        if isLeap(year): daysInMonths[2] = 29
        else: daysInMonths[2] = 28
        for month in range(1, 13):
            for day in range(1, daysInMonths[month]+1):
                if month+day == yr:
                    datesFound += 1
                    print "%s %s, %s (%s + %s = '%s)" % \
                    (monthNames[month], day, year, month, day,
str(year)[-2:])
                if month-day == yr:
                    datesFound += 1
                    print "%s %s, %s (%s - %s = '%s)" % \
                    (monthNames[month], day, year, month, day,
str(year)[-2:])
                if month*day == yr:
                    datesFound += 1
                    print "%s %s, %s (%s * %s = '%s)" % \
                    (monthNames[month], day, year, month, day,
str(year)[-2:])
                if float(month)/day == yr:
                    datesFound += 1
                    print "%s %s, %s (%s / %s = '%s)" % \
                    (monthNames[month], day, year, month, day,
str(year)[-2:])
    if datesFound == 0:
        print "\nNo dates found."
    elif datesFound == 1:
        print "\nFound one date between Jan. 1, %s and Dec. 31, %s." % \
        (startYear, endYear)
    else:
        print "\n%s dates found between Jan. 1, %s and Dec. 31, %s." % \
        (datesFound, startYear, endYear)

def main():
    startYear = raw_input("Starting year: ")
    endYear = raw_input("Ending year: ")
    if endYear == '': endYear = startYear # Search one year by hitting <CR>
    calmath(int(startYear), int(endYear))
    
if __name__ == '__main__':
    main()

--
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 deliberatus@my995internet.com  Sun Dec 16 01:40:40 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sat, 15 Dec 2001 20:40:40 -0500
Subject: [Tutor] TinyList post time module update.
Message-ID: <3C1BFB98.69DF9953@my995internet.com>

Here is the latest spasam.

Anyone want to subscribe to a list for this project?

mailto:minorfish@howlermonkey.net?Subject=subscribe%20listtalk

=================================================================================================================
#!/usr/local/bin/python
# Tinylist MLM Pitchtime module.
# COPYRIGHT 2002 Kirk D Bailey

# And made available under the GNU GPL.
###################################################################################
# You should have received a copy of the GNU General Public
License               #
# along with this program; if not, write to the Free
Software                     #
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
USA.     #
# Also, the GNU GPL may be viewed online at
http://www.gnu.org/licenses/gpl.html  #
###################################################################################
#
#   "The tyrant's foe, the people's friend, a free press." -Dr Benjamin
Franklin.
#
##################################################################
# Python can be studied and aquired at http://www.python.org/ !!!
##################################################################
#
# This module only handles receiving and sending out postings to a list.
# management of membership is handled by the favored command module
# - TLwebcommand, TLemailcommand, or both.
#
# we now import some functions from assorted libraries.

import sys, re, string, rfc822, smtplib, os.path

# someday we will collect each needed function
# and create a module just of those and distribute it
# with tinylist.

# make sure you set this to YOUR domain!
localhost = 'mydomain.foo'

# next line declares the path to stuff. DEFINE IT for *YOUR* server!
path = '/www/www.howlermonkey.net/cgi-bin'
# to the cgi-bin for your web dir,
# with no trailing '/'!
# note this tells TL where to start looking.
# everything is either here, or under this
# point in '/lists/' dir, mostly in '/lists/'.
                                        
# we read a command line arguement to determine the list name
listname = sys.argv[1]
# Arguement 0 is the name of the script run, 1 is the
# first arguement after that name in the command line,
# so this tells us the name of the email identity being addressed-
listname!

                                        
# variable 'incoming' receives the entire incoming message
# which is piped to the script on <stdin> which this reads by the alias
# such as:
#         foolist:"|/pathtoprogram/programname foolist"

#incoming = raw_input.lines()
#I commented this out for the moment to see if this is better

# this block will contain the rfc822 decoding code when we get it
finished.
# Using rfc822.py, we digest the message and make parts available to the
program.
#message = rfc822.message(incoming)
incoming = rfc822.Message(sys.stdin)
pass
pass
pass
# end of dummycode. Hereafter we act as if it is decoded.
# The information is in the dictionary 'message', each item keyed with
the header's
# name. The BODY of that dictionary is in the string 'msg'. So are any
attachments.

sender = Message.getAddr("From")                        # we must dig
out the 'from: ' field contents
# Note we already know who it is TO - 'listname' !
# Remember, the mail ssytem fed it here with a command
# line arguement, after sorting it out to a known identity,
# so the list's defining alias contains that info.

# Strip whitespace chars off every element in the list passed to this
function.
def gangstrip(str):                                     # ok, everybody
STRIP!
        index = 0                                       # initiate
counter=0
        while index<len(str):                           # define loopp
terination
                str[index]=string.strip(str[index])     # and strip each
element.
                index=index+1                           # increase the
index pointer

# ok, let's read that membership file. it is named (listname) with no
name extension.
a.open(path + "/lists/" + listname,
'r')                                                
members = a.readlines()                                 # read all of it
in.
a.close()                                               # and close the
file

# then we look to see if that FROM exists in the membership.
# clean it up;
gangstrip(members)      # strip all leading and trailing whitespace
                                # from each element in the list
'members'.

# then we look to see if the sender is a member of the list:
if sender in members :  # IF the sender is in the subscriber file, 
        subject = '[' + listname + ']' + subject        # then accept
the submission.
        if os.path.exists(path + "/lists/" +listname +".replyto"):      
                Reply_to = "Reply-to: " + listname + "@" + localhost +
CRLF # set the  optional
        else:                                           # Reply-to:
field.
                Reply_to = ""                           # if not, this
string
                                                        # is NULL.


        XLoop = "X-Loop: " + listname + "@" + localhost # This breaks
email 
                                                        # loops from
forming
        # need to add something to detect these to STOP such posts!
        if os.path.exists(path + "/lists/" + listname + ".footer"):    
# if there is a 
                                                                       
# footer, read it!

                ftr = open(path + "/lists/" + listname + ".footer",'r')
# read the footer
                                                                       
# file
                footer = ftr.readlines()                               
# into 'footer'
                                                                       
# 
                ftr.close()                                            
# close that file,
                msg = msg + footer + CRLF                              
# and append it to 
                                                                       
# the message. 

        if os.path.exists(path + "/lists/"+listname+".random"):        
# if this list has a random 
                                                                       
# rotation file,
                f1=open("./lists/"+listname+".random",'r')             
# Open the random footer
                                                                       
# rotation file
                randomline=gangstrip(f1.readlines())                   
# load the contents of the
                                                                       
# rotation
                f1.close()                                             
# then close the file
                msg = msg + randomline + CRLF                          
# and add the random element
                                                                       
# to the footer.
                        
# this end processing for an acceptable posting. Next block handles
process for
# REJECTED postings.
                        
else:                                                           # BUT IF
THEY ARE NOT...
        listnamemembers = sender                                # put
poster address as the
                                                                #
recipient in list
                                                                #
'listnamemembers'
        msg = ""                                                # and
clear the mesage.
        From_addr = "From: tinylist@" + localhost + CRLF       
#From:tinylist@mydomain.foo!
        Subject = "Subject: Unauthorized posting to list: " + listname +
CRLF # Setsubject
        Reply_to = "Reply-to: postmaster@" + localhost + CRLF   # replys
go to thePostmaster
        XLoop = "X-Loop: postmaster@" + localhost               # This
breaks email
                                                                # loops
from
                                                                #
forming
        msg = """
                
                To whom it may concern;
                
                Sorry, but as you are not a current member of """ +
listname + """, 
                you may not post to it. Your recent posting has been
rejected and destroyed.
                
                Feel free to contact the postmaster if there is any
question.
                Any reply to this letter should go directly to the
postmaster.
                
                You can also subscribe to this list if you like.
                
                Goodbye.
                
                """

# ABOVE IS 1 BLANK LINE, DO NOT DELETE IT!
# BTW, that was the end of the ELSE clause from way above.
# there cannot be comments in those line                                
# above this one, or they would be part
# of the triplequoted string!
# ok, if they are not a member, THEY GET 
# THE REPLY SHOWN ABOVE MAILED TO THEM! 
# (Maybe we could read a stock answer from a file?)
# there is no endif or fi in python.
# whitespace and tabulation therefore
# is rather important here.

# now we send whatever message is to go out to 
# whatever is in the recipient list.
server = smtplib.SMTP('localhost')      # setup for a smtp run.
# helo(localhost)                       # open a connection to the smtp
server,
                                        # possibly not needed
                                        # so it is commented out. If all
else fails,
                                        # use it.
server.connect()                        # and log in to the thing 170
                                        # as the identity this script
runs as.
for to_addr in listnamemembers :        # for each address in the list
listnamemembers,
        server.sendmail(from_addr, to_addr, Subject, reply-to, XLoop,
msg)
                                        # send envlope and msg!

                                        # don't delete the above line!
server.quit()                           # then close the connection.

# make sure this script runs as a TRUSTED USER-
# 180and NOT as root!!! You set that up in the Sendmail
# Config file (sendmail.cf).
# Make sure that a NON-priviliged user OWNS
# this script, and that it runs as that identity!
#
# The TinyList community hangs out at www.tinylist.org
# and is a pretty informal bunch of digiteratti. Come visit!
#
# We have lists there, which only seems right somehow.
# they are:
# tinylist-users - discussion for all aspects of using190 
#                  tinylist; somewhat technical.

# tinylist-chat - for all intrested in tl, lists, python,
#                 email: a broad charter! 
# tinylist-devlopers - discussion of new versions, features, 
#                      and bugchasing.
# evil-humor - sick, raunchy, crusty, cynical, depraved, 
#               deprived humor? OVER HERE!
# Fnord.
---------------------------------------------------------------------------------------------------
200


-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Sun Dec 16 01:42:15 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sat, 15 Dec 2001 20:42:15 -0500
Subject: [Tutor] preliminary testing of the thing- wanna take a look?
References: <XFMail.20011215141301.shalehperry@attbi.com>
Message-ID: <3C1BFBF7.DF9CD4F6@my995internet.com>

fed it a letter, redirecting input from file testletter.
AS:
ns#./TLpost.py testlist3 < testletter

Got these results:

ns# ./TLpost.py testlist3 < testletter
Traceback (innermost last):
  File "./TLpost.py", line 67, in ?
    sender = Message.getAddr("From")                    # we must dig
out the 'from: ' fies
NameError: Message
ns# 

Hmmm...

here is the latest listing. Danny, if you want to get your feet wet,
email me privately and I will send a password to you off list.

1--------0---------0---------0---------0---------0---------0---------0---------0---------0---------:=P
#!/usr/local/bin/python
# Tinylist MLM Pitchtime module.
# COPYRIGHT 2002 Kirk D Bailey
# And made available under the GNU GPL.
###############################################################################
####
# You should have received a copy of the GNU General Public
License           
  #
# along with this program; if not, write to the Free
Software                 
  #
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
USA. 
  #
# Also, the GNU GPL may be viewed online at
http://www.gnu.org/licenses/gpl.html  #
###############################################################################
####
#
#   "The tyrant's foe, the people's friend, a free press." -Dr Benjamin
Franklin.
#
##################################################################
# Python can be studied and aquired at http://www.python.org/ !!!
##################################################################
#
# This module only handles receiving and sending out postings to a list.
# management of membership is handled by the favored command module
# - TLwebcommand, TLemailcommand, or both.
#
# we now import some functions from assorted libraries.

import sys, re, string, rfc822, smtplib, os.path

# someday we will collect each needed function
# and create a module just of those and distribute it
# with tinylist.

# make sure you set this to YOUR domain!
localhost = 'mydomain.foo'

# next line declares the path to stuff. DEFINE IT for *YOUR* server!
path = '/www/www.howlermonkey.net/cgi-bin'
# to the cgi-bin for your web dir,
# with no trailing '/'!
# note this tells TL where to start looking.
# everything is either here, or under this
# point in '/lists/' dir, mostly in '/lists/'.
					
# we read a command line arguement to determine the list name
listname = sys.argv[1]
# Arguement 0 is the name of the script run, 1 is the
# first arguement after that name in the command line,
# so this tells us the name of the email identity being addressed-
listname!

					
# variable 'incoming' receives the entire incoming message
# which is piped to the script on <stdin> which this reads by the alias
# such as:
#         foolist:"|/pathtoprogram/programname foolist"

#incoming = raw_input.lines()
#I commented this out for the moment to see if this is better

# this block will contain the rfc822 decoding code when we get it
finished.
# Using rfc822.py, we digest the message and make parts available to the
program.
#message = rfc822.message(incoming)
incoming = rfc822.Message(sys.stdin)
pass
pass
pass
# end of dummycode. Hereafter we act as if it is decoded.
# The information is in the dictionary 'message', each item keyed with
the
header's
# name. The BODY of that dictionary is in the string 'msg'. So are any
attachments.

sender = Message.getAddr("From")			# we must dig out the 'from: ' field
contents
# Note we already know who it is TO - 'listname' !
# Remember, the mail ssytem fed it here with a command
# line arguement, after sorting it out to a known identity,
# so the list's defining alias contains that info.

# Strip whitespace chars off every element in the list passed to this
function.
def gangstrip(str):					# ok, everybody STRIP!
	index = 0					# initiate counter=0
	while index<len(str):				# define loopp terination
		str[index]=string.strip(str[index])	# and strip each element.
		index=index+1				# increase the index pointer

# ok, let's read that membership file. it is named (listname) with no
name
extension.
a.open(path + "/lists/" + listname, 'r')						
members = a.readlines()					# read all of it in.
a.close()						# and close the file

# then we look to see if that FROM exists in the membership.
# clean it up;
gangstrip(members)	# strip all leading and trailing whitespace
				# from each element in the list 'members'.

# then we look to see if the sender is a member of the list:
if sender in members :	# IF the sender is in the subscriber file, 
	subject = '[' + listname + ']' + subject	# then accept the submission.
	if os.path.exists(path + "/lists/" +listname +".replyto"):	
		Reply_to = "Reply-to: " + listname + "@" + localhost + CRLF # set the 
optional
	else:						# Reply-to: field.
		Reply_to = ""				# if not, this string
							# is NULL.

	XLoop = "X-Loop: " + listname + "@" + localhost # This breaks email 
							# loops from forming
	# need to add something to detect these to STOP such posts!
	if os.path.exists(path + "/lists/" + listname + ".footer"):	# if there
is a 
									# footer, read it!
		ftr = open(path + "/lists/" + listname + ".footer",'r')	# read the
footer
									# file
		footer = ftr.readlines()				# into 'footer'
									# 
		ftr.close()						# close that file,
		msg = msg + footer + CRLF				# and append it to 
									# the message. 

	if os.path.exists(path + "/lists/"+listname+".random"):		# if this list
has a
random 
									# rotation file,
		f1=open("./lists/"+listname+".random",'r')		# Open the random footer
									# rotation file
		randomline=gangstrip(f1.readlines())			# load the contents of the
									# rotation
		f1.close()						# then close the file
		msg = msg + randomline + CRLF				# and add the random element
									# to the footer.
			
# this end processing for an acceptable posting. Next block handles
process for
# REJECTED postings.
			
else:								# BUT IF THEY ARE NOT...
	listnamemembers = sender				# put poster address as the
								# recipient in list
								# 'listnamemembers'
	msg = ""						# and clear the mesage.
	From_addr = "From: tinylist@" + localhost + CRLF
#From:tinylist@mydomain.foo!
	Subject = "Subject: Unauthorized posting to list: " + listname + CRLF #
Setsubject
	Reply_to = "Reply-to: postmaster@" + localhost + CRLF 	# replys go to
thePostmaster
	XLoop = "X-Loop: postmaster@" + localhost		# This breaks email
								# loops from
								# forming
	msg = """
		
		To whom it may concern;
		
		Sorry, but as you are not a current member of """ + listname + """, 
		you may not post to it. Your recent posting has been rejected and
destroyed.
		
		Feel free to contact the postmaster if there is any question.
		Any reply to this letter should go directly to the postmaster.
		
		You can also subscribe to this list if you like.
		
		Goodbye.
		
		"""

# ABOVE IS 1 BLANK LINE, DO NOT DELETE IT!
# BTW, that was the end of the ELSE clause from way above.
# there cannot be comments in those line  				
# above this one, or they would be part
# of the triplequoted string!
# ok, if they are not a member, THEY GET 
# THE REPLY SHOWN ABOVE MAILED TO THEM! 
# (Maybe we could read a stock answer from a file?)
# there is no endif or fi in python.
# whitespace and tabulation therefore
# is rather important here.

# now we send whatever message is to go out to 
# whatever is in the recipient list.
server = smtplib.SMTP('localhost')	# setup for a smtp run.
# helo(localhost)			# open a connection to the smtp server,
					# possibly not needed
					# so it is commented out. If all else fails,
					# use it.
server.connect()			# and log in to the thing 170
					# as the identity this script runs as.
for to_addr in listnamemembers :	# for each address in the list
listnamemembers,
	server.sendmail(from_addr, to_addr, Subject, reply-to, XLoop, msg)
					# send envlope and msg!

					# don't delete the above line!
server.quit()				# then close the connection.

# make sure this script runs as a TRUSTED USER-
# 180and NOT as root!!! You set that up in the Sendmail
# Config file (sendmail.cf).
# Make sure that a NON-priviliged user OWNS
# this script, and that it runs as that identity!
#
# The TinyList community hangs out at www.tinylist.org
# and is a pretty informal bunch of digiteratti. Come visit!
#
# We have lists there, which only seems right somehow.
# they are:
# tinylist-users - discussion for all aspects of using190 
#                  tinylist; somewhat technical.
# tinylist-chat - for all intrested in tl, lists, python,
#                 email: a broad charter! 
# tinylist-devlopers - discussion of new versions, features, 
#                      and bugchasing.
# evil-humor - sick, raunchy, crusty, cynical, depraved, 
#               deprived humor? OVER HERE!
# Fnord.

200


From deliberatus@my995internet.com  Sun Dec 16 02:18:59 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sat, 15 Dec 2001 21:18:59 -0500
Subject: [Tutor] class and objects and such
References: <XFMail.20011215181801.shalehperry@attbi.com>
Message-ID: <3C1C0493.AEDAF6F8@my995internet.com>

ARG!

I am so close to having this finished it is unreal.

DANNY, you there?


Sean 'Shaleh' Perry wrote:
> 
> On 16-Dec-2001 Kirk Bailey wrote:
> > Glad to see you are home. Do you icq?
> >                                  msn?
> >                                    YIM?
> >                                       Tie mesages to rocks? :-)
> >
> >
> 
> Carrier pigeons (-:  Actually the wife is kicking me out for a party she is
> throwing with her lady friends.  Won't see the computer again until Monday.

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From dyoo@hkn.eecs.berkeley.edu  Sun Dec 16 02:30:34 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 15 Dec 2001 18:30:34 -0800 (PST)
Subject: [Tutor] (no subject)  [Escape codes / os.access()]
In-Reply-To: <000901c18583$e80164e0$0100c0a8@videotron.ca>
Message-ID: <Pine.LNX.4.21.0112151813170.15103-100000@hkn.eecs.berkeley.edu>

On Sat, 15 Dec 2001, Jean Montambeault wrote:

>     Hmmmmm! I had a little time on my hands and tried this :
> >>> os.access(r"c:\essai.py", os.R_OK)
> 1
> >>> os.access(r"c:\essai.py", os.W_OK)
> 1
> 
> and it works, as you can see,  but:
> 
> >>> os.access("c:\essai.py", os.W_OK)
> 1
> >>> os.access("c:\essasdafis.py", os.W_OK)
> 0
> >>>
> 
> works too so the os module takes care of the backslash problem as it seems.

Actually, os.access() doesn't.  In the particular case of figuring out
what "\e" means, Python sees that it doesn't know any escape code like
that, so it will let it through.

Python 2.1 shows this pretty well if we use the interpreter:

###
>>> "\e"
'\\e'
>>> "\n"
'\n'
###

In the first call, Python will automagically escape the backslash for
us.  That's why it shows the '\\e' in there, just to point out that
there's a literal backslash in the string.

In the second call, there is an escape code called '\n', which is the
"newline" character.  So that's why its representation looks different
from '\e'.

If your files began with an 'n' or 't', you would probably run into this
problem more often.  One way to get around worrying about backslashes is
to dodge them altogether, and use forward slashes '/' instead.  Windows
will understand that we're using the forward slashes to get inside
directories.  So this should work:

###
os.access("c:/essai.py", os.W_OK)
###


> It wouldn't work for :
>
> rich=open("c:\my file\ my beautiful file", "w")
>
> you must use the "r" or "\\" with open() there.
> That way I assumed that it would be the same for "os.access()"
> and now I'm consumed by shame. :o(


No no, you were right the first time.  Handing backslashes in string
literals should be consistant throughout Python.  open() doesn't do
anything more special with its input than os.access().  There may be
another reason why your open():

> rich=open("c:\my file\ my beautiful file", "w")

failed.  If you can show us the error message, we may get an idea of why
it didn't work.  One thing: can files begin with spaces on Windows?  I
don't have a Windows system at the moment to check this.


Talk to you later!



From rw_hyde@yahoo.com  Sat Dec 15 22:49:33 2001
From: rw_hyde@yahoo.com (Ryan W. Hyde)
Date: Sat, 15 Dec 2001 18:49:33 -0400
Subject: [Tutor] getting started
Message-ID: <00c401c185c4$b1bca8e0$0200a8c0@RYAN366>

This is a multi-part message in MIME format.

------=_NextPart_000_00C0_01C18599.3CB6FBC0
Content-Type: text/plain;
	charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable

how do i run a script typed up in txt format through the interpreter?
            -Ryan

------=_NextPart_000_00C0_01C18599.3CB6FBC0
Content-Type: text/html;
	charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Dwindows-1252" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.2314.1000" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>how do i run a script typed up in txt =
format=20
through the interpreter?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;=20
&nbsp;&nbsp;&nbsp; -Ryan</FONT></DIV></BODY></HTML>

------=_NextPart_000_00C0_01C18599.3CB6FBC0--


_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com



From jrm@videotron.ca  Sat Dec 15 19:43:53 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Sat, 15 Dec 2001 21:43:53 +0200
Subject: [Tutor] (no subject)  [Escape codes / os.access()]
References: <Pine.LNX.4.21.0112151813170.15103-100000@hkn.eecs.berkeley.edu>
Message-ID: <001101c185a0$d3f820c0$0100c0a8@videotron.ca>

----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "Jean Montambeault" <jrm@videotron.ca>

There may be
> another reason why your open():
>
> > rich=open("c:\my file\ my beautiful file", "w")
>
No, I was wrong and it works.
I just hope that vip is getting something useful from all that. I know I
have.

Thank Danny

Jean M.



From ak@silmarill.org  Sun Dec 16 02:52:58 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Sat, 15 Dec 2001 21:52:58 -0500
Subject: [Tutor] getting started
In-Reply-To: <00c401c185c4$b1bca8e0$0200a8c0@RYAN366>
References: <00c401c185c4$b1bca8e0$0200a8c0@RYAN366>
Message-ID: <20011215215258.B22016@sill.silmarill.org>

On Sat, Dec 15, 2001 at 06:49:33PM -0400, Ryan W. Hyde wrote:
> how do i run a script typed up in txt format through the interpreter?
>             -Ryan

Let's say your script is named test.py; start up your command line
interface (msdos prompt), and type "python test.py" without the quotes.

 - Andrei

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


From shalehperry@attbi.com  Sun Dec 16 04:10:10 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sat, 15 Dec 2001 20:10:10 -0800 (PST)
Subject: [Tutor] class and objects and such
In-Reply-To: <3C1C0493.AEDAF6F8@my995internet.com>
Message-ID: <XFMail.20011215201010.shalehperry@attbi.com>

I founbd my old icq uin.  1345612


From myuen@ucalgary.ca  Sun Dec 16 06:03:03 2001
From: myuen@ucalgary.ca (Mike Yuen)
Date: Sat, 15 Dec 2001 23:03:03 -0700 (MST)
Subject: [Tutor] Prompting and graphics
Message-ID: <Pine.A41.4.10.10112152301330.88488-100000@acs2.acs.ucalgary.ca>

I've got a couple of questions.  First one has to do with prompting a user
for data and reading it in, i'm from the C++ world and used to using cin
and cout statements.

Second, i've heard that I can graphically display some of my data.  Is
there a seperate module I have to import?

Thanks,
Mike




From toodles@yifan.net  Sun Dec 16 06:30:54 2001
From: toodles@yifan.net (Andy W)
Date: Sun, 16 Dec 2001 14:30:54 +0800
Subject: [Tutor] Prompting and graphics
References: <Pine.A41.4.10.10112152301330.88488-100000@acs2.acs.ucalgary.ca>
Message-ID: <004601c185fb$38324a70$0300a8c0@sun>

Hi Mike,

> I've got a couple of questions.  First one has to do with prompting a user
> for data and reading it in, i'm from the C++ world and used to using cin
> and cout statements.

You can use either of two functions (there might be other more obscure
ways):

input(prompt)
raw_input(prompt)

They work essentially the same, but "input" evaluates the data read, whereas
"raw_input" does not. This can be dangerous if your program is open to
malicious users, who could (the most frequently used example i've seen) open
a file for writing, thus truncating it. (by supplying the input prompt with
"open('important_file','w')".

Here's how raw_input works:

>>> x=raw_input('!> ')
!> 123
>>> x
'123'

Following on with "input"...

>>> input('eval: ')
eval: x
'1'

(Of course I could have put that into a variable, I just wanted to show the
evaluation part)

>
> Second, i've heard that I can graphically display some of my data.  Is
> there a seperate module I have to import?

There's a number of GUIs for Python. You will need to import a separate
module (and in non-Tkinter cases, download too).
Tkinter is the official Python GUI, but there are others such as, one which
I quite like, wxPython.

Tkinter resources:
http://www.python.org/topics/tkinter/

wxPython:
http://www.wxpython.org/

>
> Thanks,
> Mike

HTH,
Andrew

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



From listservb@quinceleaf.com  Sun Dec 16 06:40:20 2001
From: listservb@quinceleaf.com (Quniceleaf Listservs)
Date: Sun, 16 Dec 2001 01:40:20 -0500
Subject: [Tutor] Redirecting output from the HTMLParser to a file
Message-ID: <BCEBIEMBBOHIACIMFEEEOEFBCJAA.listservb@quinceleaf.com>

I'm trying to filter an HTML file through the HTMLParser, and have been
experiencing trouble with what I'm attempting.

I'm reading in an HTML file, then passing it to a combination of
writer/formatter/HTMLparser. The various steps are omitted, as I've merely
used standard scripts from various Python books.

	# print html body as plain text
	p = htmllib.HTMLParser(f)
	p.feed(workdata)
	p.close()

It filters the HTML text (workdata) beautifully to the Interactive Window,
but I cannot get it to feed its output into a string or file, which is the
whole point of the exercise.

If I try to redirect the output to an open file via a write() command, I get
the error:

	TypeError: argument 1 must be string or read-only character buffer, not
None

Does anyone have any advice? Does anyone know where I can find more detailed
information on the HTMLParser? The basic online documentation doesn't seem
to explain it in as much detail as I seem to need.



From listservb@quinceleaf.com  Sun Dec 16 07:02:13 2001
From: listservb@quinceleaf.com (Quniceleaf Listservs)
Date: Sun, 16 Dec 2001 02:02:13 -0500
Subject: [Tutor] Python not being found in the registry?
Message-ID: <BCEBIEMBBOHIACIMFEEEIEFCCJAA.listservb@quinceleaf.com>

I'm using Python 2.2c1 on a Win2K machine.

I've repeatedly tried installing two Python addons from different sources
(XIST and the MySQL-interface) that each use a Windows installer program
based on distutils-1.0.2pre.

Both need to locate the Python installation before proceeding with the
setup, and will not allow the user to browse and specify the location
themselves. Unfortunately, neither can ever find a Python installation, and
thus will not install.

I've tried this repeatedly with Python 2.1, 2.2b, 2.2c1, and with
ActiveState's distribution. In each case the installation is reflected in
the Windows registry, but only the ActiveState install appears in the setup
(and due to instability issues I am sticking with the standard
distribution).

Has anyone else encountered this problem?

- Brian





From deliberatus@my995internet.com  Sun Dec 16 09:02:07 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sun, 16 Dec 2001 04:02:07 -0500
Subject: [Tutor] smtplib
Message-ID: <3C1C630F.442C1E31@my995internet.com>

Quoting from the online manual in the module department, referring to
smtplib, I read:

sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) 
     Send mail. The required arguments are an RFC 822 from-address
string, a list of RFC 822 to-address strings,
     and a message string. The caller may pass a list of ESMTP options
(such as "8bitmime") to be used in "MAIL
     FROM" commands as mail_options. ESMTP options (such as "DSN"
commands) that should be used with all "RCPT"
     commands can be passed as rcpt_options. (If you need to use
different ESMTP options to different recipients
     you have to use the low-level methods such as mail, rcpt and data
to send the message.) 

Well, can I also pass along SUBJECT as a variable, or must I prepend
that to the msg string?

Any smtplib kahunas out there?

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From ak@silmarill.org  Sun Dec 16 15:41:43 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Sun, 16 Dec 2001 10:41:43 -0500
Subject: [Tutor] Prompting and graphics
In-Reply-To: <Pine.A41.4.10.10112152301330.88488-100000@acs2.acs.ucalgary.ca>
References: <Pine.A41.4.10.10112152301330.88488-100000@acs2.acs.ucalgary.ca>
Message-ID: <20011216104143.A25361@sill.silmarill.org>

On Sat, Dec 15, 2001 at 11:03:03PM -0700, Mike Yuen wrote:
> I've got a couple of questions.  First one has to do with prompting a user
> for data and reading it in, i'm from the C++ world and used to using cin
> and cout statements.

test = raw_input("type stuff here: ")
print test

> 
> Second, i've heard that I can graphically display some of my data.  Is
> there a seperate module I have to import?

Tkinter, I guess.. 

> 
> Thanks,
> Mike
> 
> 
> 
> _______________________________________________
> 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  Sun Dec 16 18:17:44 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun, 16 Dec 2001 10:17:44 -0800 (PST)
Subject: [Tutor] smtplib
In-Reply-To: <3C1C630F.442C1E31@my995internet.com>
Message-ID: <XFMail.20011216101744.shalehperry@attbi.com>

> 
> Well, can I also pass along SUBJECT as a variable, or must I prepend
> that to the msg string?
> 
> Any smtplib kahunas out there?
> 

you add any needed headers to the message string, then send the whole string to
sendmail().


From john@pertalion.org  Sun Dec 16 20:13:11 2001
From: john@pertalion.org (John Pertalion)
Date: Sun, 16 Dec 2001 15:13:11 -0500
Subject: [Tutor] smtplib
In-Reply-To: <3C1C630F.442C1E31@my995internet.com>
Message-ID: <DHENJFCDEPKIKGEFBLAHCEDECIAA.john@pertalion.org>

msg = "Subject:some text\r\n" + msg

>From rfc822, it's looking for the CRLF or \r\n to separate the subject from
the message body.

>Well, can I also pass along SUBJECT as a variable, or must I prepend
>that to the msg string?




From i812@iname.com  Sun Dec 16 21:36:40 2001
From: i812@iname.com (Rob McGee)
Date: Sun, 16 Dec 2001 15:36:40 -0600
Subject: [Tutor] dictionary vs. list considerations
Message-ID: <20011216153640.D3310@hal>

For what I want to do a dictionary would be a little easier to use, but
a list could suffice. What kind of considerations (such as performance
and memory use) are there in deciding which to use? I don't mind having
a little bit more code (to retrieve my objects out of a list) if it's
faster or uses less memory than a dictionary.

Thanks,
    Rob - /dev/rob0


From ak@silmarill.org  Sun Dec 16 21:44:01 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Sun, 16 Dec 2001 16:44:01 -0500
Subject: [Tutor] dictionary vs. list considerations
In-Reply-To: <20011216153640.D3310@hal>
References: <20011216153640.D3310@hal>
Message-ID: <20011216164401.A26634@sill.silmarill.org>

On Sun, Dec 16, 2001 at 03:36:40PM -0600, Rob McGee wrote:
> For what I want to do a dictionary would be a little easier to use, but
> a list could suffice. What kind of considerations (such as performance
> and memory use) are there in deciding which to use? I don't mind having
> a little bit more code (to retrieve my objects out of a list) if it's
> faster or uses less memory than a dictionary.
> 
> Thanks,
>     Rob - /dev/rob0

I think dictionary is usually faster, but it depends on circumstances.
Besides, the rule of thumb is that even gurus often make mistakes when
guessing performance of different approaches, so if you're concerned
with speed at all, try both ways and time 'em.

> 
> _______________________________________________
> 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 brian@quinceleaf.com  Sun Dec 16 06:09:57 2001
From: brian@quinceleaf.com (Brian Ibbotson)
Date: Sun, 16 Dec 2001 01:09:57 -0500
Subject: [Tutor] Redirecting output from the HTMLParser to a file
Message-ID: <BCEBIEMBBOHIACIMFEEEIEFACJAA.brian@quinceleaf.com>

I'm trying to filter an HTML file through the HTMLParser, and have been
experiencing trouble with what I'm attempting.

I'm reading in an HTML file, then passing it to a combination of
writer/formatter/HTMLparser. The various steps are omitted, as I've merely
used standard scripts from various Python books.

	# print html body as plain text
	p = htmllib.HTMLParser(f)
	p.feed(workdata)
	p.close()

It filters the HTML text (workdata) beautifully to the Interactive Window,
but I cannot get it to feed its output into a string or file, which is the
whole point of the exercise.

If I try to redirect the output to an open file via a write() command, I get
the error:

	TypeError: argument 1 must be string or read-only character buffer, not
None

Does anyone have any advice? Does anyone know where I can find more detailed
information on the HTMLParser? The basic online documentation doesn't seem
to explain it in as much detail as I seem to need.



From m_konermann@gmx.de  Mon Dec 17 02:22:12 2001
From: m_konermann@gmx.de (Marcus Konermann)
Date: Mon, 17 Dec 2001 03:22:12 +0100
Subject: [Tutor] Shadow Class Generation Problem
Message-ID: <3C1D56D4.C786885C@gmx.de>

--------------940C4D9B9E273F51B9DFD38E
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 8bit

Hi @ All !

I generate a Python Shadow Class from an excisting c++ file using SWIG.
The compiling and linking process went ok and a simanneal.py file was
generated beginning in the following form:

# This file was created automatically by SWIG.
import simannealfilec
class simanneal_varlist:
    def __init__(self,*args):
        self.this = apply(simannealfilec.new_simanneal_varlist,args)
        self.thisown = 1

And after using this simanneal.py by importing it the following error
occurs:

Traceback (most recent call last):
  File "C:\Python2_1_1\Pythonwin\pywin\framework\scriptutils.py", line
396, in ImportFile
    reload(sys.modules[modName])
  File "C:\Optimierer\ext1\mainko.py", line 2, in ?
    import simannealfile
  File "C:\Optimierer\AG TEM\simannealfile.py", line 2, in ?
    import simannealfilec
ImportError: No module named simannealfilec

In the SWIG manual i read that this simannealfilec was automatically
generated by SWIG and that this file is´nt visible.
Has anyone an idea to avoid this error message ?

Greetings
Marcus

--------------940C4D9B9E273F51B9DFD38E
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
Hi @ All !
<p>I generate a Python Shadow Class from an excisting c++ file using SWIG.
The compiling and linking process went ok and a simanneal.py file was generated
beginning in the following form:
<p><i># This file was created automatically by SWIG.</i>
<br><i>import simannealfilec</i>
<br><i>class simanneal_varlist:</i>
<br><i>&nbsp;&nbsp;&nbsp; def __init__(self,*args):</i>
<br><i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.this = apply(simannealfilec.new_simanneal_varlist,args)</i>
<br><i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.thisown = 1</i>
<p>And after using this simanneal.py by importing it the following error
occurs:
<p><i>Traceback (most recent call last):</i>
<br><i>&nbsp; File "C:\Python2_1_1\Pythonwin\pywin\framework\scriptutils.py",
line 396, in ImportFile</i>
<br><i>&nbsp;&nbsp;&nbsp; reload(sys.modules[modName])</i>
<br><i>&nbsp; File "C:\Optimierer\ext1\mainko.py", line 2, in ?</i>
<br><i>&nbsp;&nbsp;&nbsp; import simannealfile</i>
<br><i>&nbsp; File "C:\Optimierer\AG TEM\simannealfile.py", line 2, in
?</i>
<br><i>&nbsp;&nbsp;&nbsp; import simannealfilec</i>
<br><i>ImportError: No module named simannealfilec</i><i></i>
<p>In the SWIG manual i read that this simannealfilec was automatically
generated by SWIG and that this file is&acute;nt visible.
<br>Has anyone an idea to avoid this error message ?
<p>Greetings
<br>Marcus</html>

--------------940C4D9B9E273F51B9DFD38E--



From deliberatus@my995internet.com  Mon Dec 17 04:20:29 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sun, 16 Dec 2001 23:20:29 -0500
Subject: [Tutor] read a random line from a file
Message-ID: <3C1D728D.7F2616F5@my995internet.com>

OK, I know there is a simple way to do it, and I cannot locate the
correct ommand. I want to open a flat text file, read ONE randomly
selected line into a string, and close the file. I need the command for
reading a line at random, and what module it is in. I understand there
is such a command already defined, and it is simple to use, but canot
find it again.

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From ak@silmarill.org  Mon Dec 17 06:25:23 2001
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 17 Dec 2001 01:25:23 -0500
Subject: [Tutor] read a random line from a file
In-Reply-To: <3C1D728D.7F2616F5@my995internet.com>
References: <3C1D728D.7F2616F5@my995internet.com>
Message-ID: <20011217012523.A1408@sill.silmarill.org>

On Sun, Dec 16, 2001 at 11:20:29PM -0500, Kirk Bailey wrote:
> OK, I know there is a simple way to do it, and I cannot locate the
> correct ommand. I want to open a flat text file, read ONE randomly
> selected line into a string, and close the file. I need the command for
> reading a line at random, and what module it is in. I understand there
> is such a command already defined, and it is simple to use, but canot
> find it again.


#!/usr/bin/env python2

import os, sys, random

proj = os.path.expanduser("~/.t/p")
f = open(proj)
projects = []
lines = f.readlines()
for l in lines:
    if l.strip():
        projects.append(l)
print random.choice(projects),

It's good if file isn't too large..

> 
> -- 
> Respectfully,
>              -Kirk D Bailey (C)2001
>               Addme! icq #27840081
> end
> 
> 
> Within the sweep of his sword, Each man is an Ubar.
> 
> http://www.howlermonkey.net/
> http://www.sacredelectron.org/
> 
> _______________________________________________
> 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  Mon Dec 17 07:52:21 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 16 Dec 2001 23:52:21 -0800 (PST)
Subject: [Tutor] read a random line from a file
In-Reply-To: <20011217012523.A1408@sill.silmarill.org>
Message-ID: <Pine.LNX.4.21.0112162331330.23971-100000@hkn.eecs.berkeley.edu>

On Mon, 17 Dec 2001, Andrei Kulakov wrote:

> On Sun, Dec 16, 2001 at 11:20:29PM -0500, Kirk Bailey wrote:
> > OK, I know there is a simple way to do it, and I cannot locate the
> > correct ommand. I want to open a flat text file, read ONE randomly
> > selected line into a string, and close the file. I need the command for
> > reading a line at random, and what module it is in. I understand there
> > is such a command already defined, and it is simple to use, but canot
> > find it again.


Actually, I'm not sure if it's built in at all.  However, we can cook up a
few definitions so that it becomes a tool we can use.


To get a random line from a file, it might be useful to write something
that tells us how many lines a file contains.  Here's one way to do it:

###
def countLines(file):
    """Given a file, returns the number of lines it contains.

    The current file position should be preserved as long as the file
    supports tell() and seek()."""
    old_position = file.tell()
    count = 0
    while file.readline() != '':
        count = count + 1
    file.seek(old_position)
    return count
###


If we had a way to choose a random number between 0 and the countLines()
of a file, we'd be in business.  Thankfully, there is something in the
library that can help us: random.randrange():


###
>>> random.randrange(10)
4
>>> random.randrange(10)
7
>>> random.randrange(10)
4
###


There is documentation on random.randrange() here:

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

if you're interested in playing around with random stuff.  *grin*


Also, it would be great if, when we knew which line we wanted to pull out,
we could get get that particular line.  There's a module called
'linecache' that can do this for us:

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

But if 'linecache' wasn't there, it still wouldn't be too hard to cook
something up like it.


With these tools, it becomes possible to write a simple random line
grabber:

###
def getRandomLine(filename):
    """Given a filename, returns a random line."""
    linecount = countLines(open(filename))
    chosen_line_number = random.randrange(linecount)
    return linecache.getline(filename, chosen_line_number)
###



Writing function definitions can be a lot of fun.  Hope this helps!



From slime@vsnl.net  Mon Dec 17 08:51:31 2001
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Mon, 17 Dec 2001 14:21:31 +0530
Subject: [Tutor] display filter slow
Message-ID: <20011217085131.GA3141@localhost.localdomain>

--24zk1gE8NUlDmwG9
Content-Type: multipart/mixed; boundary="h31gzZEtNLTqOjlF"
Content-Disposition: inline


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

Hi,

Since this is my first post to this list, a 'howdy' to everyone here.

Now, I get many mails from people with really crazy quote-strings. So,
as I use mutt, I decided to hack up a script to filter the mail before
it is displayed in mutt's pager (using the $display_filter variable).

I've attached version 0.0001 of the script. The main problem in this
being, the filter takes a great deal of time. ie.

# With display_filter set to this script
    $ time -p mutt -f =3Dinbox -e "push <space>qq"
    real 0.60
    user 0.52
    sys 0.09

# With display_filter set to nothing
    $ time -p mutt -f =3Dinbox -e "push <space>qq"
    real 0.22
    user 0.17
    sys 0.05

As you can see, the script takes nearly thrice the amount of time as
without it. I'm sure there is a more efficient way of filtering my mail,
so any help would be appreciated.

Also, the script doesn't change the quote-string for deeper levels of
quoting, ie.

    % # * blah> quoted text here
    becomes
    > # * blah> quoted text here
    not
    > > > > quoted text here

I hope I have explained myself clearly.  Actually, a similar script
exists in perl (written by someone else), but I am re-inventing the
wheel because I want to learn python, and I want to do some other stuff
like line-wrapping, etc. which the perl script has not yet implemented.

pv.

--=20
Prahlad Vaidyanathan <slime@vsnl.net>                What, me worry ?
http://www.symonds.net/~prahladv/                    Don't Panic !
--

--h31gzZEtNLTqOjlF
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment; filename="display_filter.py"

#!/usr/bin/env python
import sys
import re

file = sys.stdin

# Set these accding to your needs
strip_trailing_spaces = 1   # "foo bar      \n" => "foo bar\n"
strip_empty_quotes = 1      # "> > \n" => "\n"

# REs
quote_regexp = re.compile("^(-->)|^([ \t]*[A-Za-z]+>)|^([ \t\"]*[|>}%])")
bad_sig = re.compile("^-{1,3}$")

for line in file.readlines():
    # Fix quotes
    if quote_regexp.match(line):
        line = quote_regexp.sub(">",line,10)
    # Strip trailing white-spaces, but not sig-dashes
    if strip_trailing_spaces and not re.match("^-- $",line):
        line = re.compile("\s+$").sub("\n",line)
    # String empty quoted lines
    if strip_empty_quotes:
        line = re.compile("^(>){1,}[ \t]*$").sub("",line)
    # Fix sig-dashes
    if re.match(bad_sig,line):
        line = re.sub(bad_sig,"-- ",line)
    # Display it
    print line,

--h31gzZEtNLTqOjlF--

--24zk1gE8NUlDmwG9
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

iD8DBQE8HbITIKhjOSElu4YRAkhtAJ4lfgg1wABu1z8WtfBIQs37KhHxUQCfSX0+
rLI0FzhP1v6rqTRVNH7DON8=
=M9PJ
-----END PGP SIGNATURE-----

--24zk1gE8NUlDmwG9--


From alan.gauld@bt.com  Mon Dec 17 15:46:22 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 17 Dec 2001 15:46:22 -0000
Subject: [Tutor] class Clowning: saving references to other instances
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1C7@mbtlipnt02.btlabs.bt.co.uk>

>     self.location = location    # an integer, unique
>     self.index = index          # also unique integer
>     self.name = uppercase[index]  # uppercase letter, also 

Huh? index is a unique integer... but you are taking 
the uppercase of it?

> from one Clown instance to another. The 
> distance(self, other) method uses "exec" 
> to store the distance values in self.(other.name) 

Oh dear, not again... ;-)
Using exec for this is really not very good.
A dictionary to store these would be better.

self.others = {}
self.others[other.name] = dist

and 

other.others[self.name] = dist

> Because it's tied to the way I'm storing these 
> instances, I don't like the way it works 

Correct, if you want to access things by a string key 
(name in this case) the best solution is nearly 
always to use a dictionary and nearly never to use 
exec()!

> how the data is stored I'll also have to change 
> the class method.

Not by much.

> The reason why I'm doing this is just to save 
> a little redundant processing. 

But you are introducing a heap of redundant 
processing by calling exec!

> One solution would be to put the "exec" code in a function 

That tidies it up a little but doesn't really help.

> should maintain them all in a single self.distances list:
>     [(B, 5.0), (C, 1.414), (D, 7.6645), ...]

Or a DICTIONARY? 

{ "B":5.0, "C":1.414,....}


> Then the distance(self, other) method filters self.distances 
> "x[0] == str(other)". If found, return x[1], 

  if x.has_key(str(other)) : return x[str(other)]
  else: return # call distance(...) 


>     self.distances.append((other.name, distance))
>     other.distances.append((self.name, distance))

Looks a lot better, and more OO like.

> Have I figured out my own solution?!? :) 

Getting closer, but dictionaries instead of lists 
would make it all much easier IMHO.

> [1] from an old Jim Croce song, "Operator", appx. 1971 (?)

Yeah, Nice taste in music :-)

Alan g.


From alan.gauld@bt.com  Mon Dec 17 16:01:00 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 17 Dec 2001 16:01:00 -0000
Subject: [Tutor] Hummm...dubious behavior.
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1C8@mbtlipnt02.btlabs.bt.co.uk>

> >>> 0.6125
> 0.61250000000000004
> >>>
> 
> occurs because of the fact, that the number 0.6125 
> is not a power of 2 (or 1/2) and so the internal 
> binary representation of it *has* to be
> an approximation of it.

Correct. And round is not intended to change the 
printed representation of the numbers but to change 
the actual value of the number.

To change the representation use string formatting 
codes

Thus:

>>> print "%5.3" % math.pi
3.142

ie 5 characters with 3 after the decimal point.

> (Maybe this has something to do with the difference
> between __repr__ and __str__   (?) )

Yes again. The interpreter uses one, print uses the other.
(I can't remember which is which, I thing print uses str...)

> >>> print 0.6125, 4.1225
> 0.6125 4.1225                  
> >>> print (0.6125, 4.1225)
> (0.61250000000000004, 4.1224999999999996)

No, its consistent, one is the __str__ of a number the 
other is the __str__  of a tuple. Its down to how those 
__str__ functions work not a discrepency in print.

[ You should be able to verify this by calling the 
__str__ and __repr__ functions explicitly, but 
I haven't tried... ]

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


From alan.gauld@bt.com  Mon Dec 17 16:34:14 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 17 Dec 2001 16:34:14 -0000
Subject: [Tutor] (no subject)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1C9@mbtlipnt02.btlabs.bt.co.uk>

> a) when I type in python - os.access('c:\...')

Erm, this isn't meant to be cheeky but you're not 
literally typing in the three dots are you?

ie You need to provide a valid file specification:

os.access('c:/autoexec.bat')  

(NB forward slash works on DOS too.)

If you are typing the three dots that's the problem, 
the os won't recognise it.

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


From alan.gauld@bt.com  Mon Dec 17 16:39:02 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 17 Dec 2001 16:39:02 -0000
Subject: [Tutor] (no subject)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1CA@mbtlipnt02.btlabs.bt.co.uk>

>     os.access("c:\\.........\\..........) etc...
> or
>     os.access(r"c:\..........\.......)etc...

or

os.access("c:/......./.....")

You can use forward slashes as path separators on 
Windows/DOS too.

Alan g.


From alan.gauld@bt.com  Mon Dec 17 18:35:05 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 17 Dec 2001 18:35:05 -0000
Subject: [Tutor] why BaseClass.__init__ needs to be called explicitly?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1CD@mbtlipnt02.btlabs.bt.co.uk>

> 1. I was just wondering why does'nt python call the base 
> class constructor automatically like in java? 

Theres several ways to view this, first __init__() 
isn't really a constructor - its called *after* the 
class is constructed. Its an initialisation hook...

Secondly, Java is unusual in this regard if it calls 
superclass constructors implicitly(I didn't actually 
realise it did that!). C++ which does have 
constructors and several other compiled languages 
require explicit calling of the base class constructor.

There is an advantage to this in that you can 
effectively override the base constructor, 
although its a fairly dangerous thing to do IMHO!


> I noticed that it does provided i don't've a
> __init__() in the derived class.

Thats because being an initialisation function it
gets called automatically after creation. Python 
just calls self.__init__() and that goes through 
the usual python tree search for a version of 
init() to run if none exists in the immediate 
object.

> Is there any specific reason behind this...

Its a good thing coz it offers more control to
the programmer.

> something to do with scripting languages?

Nope, nothing to do with scripting per se.

> 2. do we have a search facility on tutor/python-list sites? 

The ActiveState archive is searchable.

Alan G


From deliberatus@my995internet.com  Mon Dec 17 19:39:42 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Mon, 17 Dec 2001 14:39:42 -0500
Subject: [Tutor] latest snapshot of TLpost.py
Message-ID: <3C1E49FE.D7057959@my995internet.com>

Latest snapshot of TLpost.

Anyone want to look? Discussion, comments, suggestions all welcome.
Filthy jokes also, but 
they're off topic for this list (so email them to me seperately!)

rfc822 still leaves me blind. However, i wrote a fuction to load a file
and return one line from it.

Note how the footers are handled. 1 per list, 1 rotation per list, 1
footer for the entire service, 1
rotation for the entire service. If you do not want to use something,
leave it out and it is
bypassed. Samo for the REPLY-TO header field.

If we can simply grok the issness of rfc822, (and flesh out parsing the
from address), we got this
thing aced, and on to the web subscription manager.

-------------------------------------------------------------------------------------------------
#!/usr/local/bin/python
# Tinylist MLM Pitchtime module.
# COPYRIGHT 2002 Kirk D Bailey
# And made available under the GNU GPL.
#
#ADMIN AND LEGAL STUFF:
###############################################################################
# You should have received a copy of the GNU General Public
License           
# along with this program; if not, write to the Free
Software                 
#10
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
USA.
#
# Also, the GNU GPL may be viewed online at
# http://www.gnu.org/licenses/gpl.html
#########1#########2#########3#########4#########5#########6#########7#########8
#that line is 80 char across, try to stay within it if you can.
#
# "The tyrant's foe, the people's friend, a free press." -Dr Benjamin
Franklin.
#
###############################################################################
#21           Python can be studied and aquired at
http://www.python.org/ !!!
###############################################################################
#
# This module only handles receiving and sending out postings to a list.
# management of membership is handled by the favored command module
# - TLwebcommand, TLemailcommand, or both.
#
###############################################################################
#
# DEVLOPER'S NOTES:
# I have restored the old flavor of gangstrip, as the method we tried
had
# problems. This is larger and probably slower, but it works. -kdb
#
# I also have modified message processing so all the headers except to,
from
# are in msg itself, to comply with how sendmail() actually handles a
message.
# It just wants TO and FROM specified as variables, and the message as a
HUGE
# string with any other headers at the start of it. Recall that a body
of a 
# letter is preceeded with a blank line after the last header-
# that is, 
# (headlerdata)CRLFCRLFfirstlineofbodyCRLFsecondlineofbodyCRLF...
# -kdb
# 
# We also need to process the FROM address so we cook it down to a bare
assed
# email address with no decorations or extras.
# This is 'identity@domain.type' with NOTHING ELSE.
# we preserve the actual full data
# (such as '"Sean 'Shaleh' Perry" <shalehperry@attbi.com>'
# for politeness sake when dealing with the sending out
# of a posting. -kdb






# BEGIN PROCESSING PORTION
#######################################################
# we now import some functions from assorted libraries.
import sys, re, string, rfc822, smtplib, os.path

############################################################
# someday we will collect each needed function
# and create a module just of those and distribute it
# with tinylist. This will load faster, but will require
# the user to place it right and do other tech things most
# novices cringe from. And I don't blaim a novice from
# cringing, for the most part. -kdb
############################################################

# make sure you set this to YOUR domain!
localhost = 'howlermonkey.net'

# next line declares the path to stuff. DO NOT use a trailing '/'!

path = '/www/www.howlermonkey.net/cgi-bin'
print 'path=', path
# This ends the configuration portion. Hereafter only hackers need
venture.
###############################################################################

#

#

#

#

#

#

#

#

#

#

#

#

#

# WHAT?!? Still reading? ;-)

# we read a command line arguement to determine the list name
listname = sys.argv[1]

# Arguement #0 is the name of the script being run,
# #1 is the  first arguement after that name in the command line,
# so this tells us the  list name being addressed- listname!

# we append \r\n a lot, so we create a variable to contain that.
CRLF="\r\n"

# variable 'incoming' receives the entire incoming message
# which is piped to the script on <stdin> which this reads by the alias
# such as:
#         foolist:"|/pathtoprogram/programname foolist"
#
# Using rfc822.py, digest the message and make parts available to the
program.
Message = rfc822.Message(sys.stdin)



# now some code to debug with- remove it later.
type(Message)
print Message


# just strip off the leading and trailing whitespaces and
# place the resulting value in the variable.
# remember, 'FROM' is a reserved word in Python.
# I suspect 'TO' is also reserved.


# Extract the FROM data and copy it to a second storage variable to use
later-
# if there is a later.
RawSender = string.strip(Message['From'])
sender = RawSender
# preserve RawSender for later use,
# but process sender for the pure
# email address for membership testing.
print 'sender=', sender
print 'RawSender=', RawSender
# remove that print statement later.

# ADDRESS PROCESSING DUMMY CODE BLOCK
# We want to insert some code here replacing these lines
# to reduce sender to ONLY the word BEFORE '@',
# AFTER '@', and including '@' as 
# "me@here.foo"
# amd ignore any '<', '>'. or other words not in intimate contact with 
# that '@' symbol. 

subject= string.strip(Message['Subject'])
print 'Subject: ', subject

# The information is in the dictionary 'Message', each item keyed with
the
# header's name. The BODY of that dictionary is in the string 'msg'. So
are
# any attachments.
#
# Strip whitespace chars off every element in the list passed to this
function.
def gangstrip(thing):			# ok, everybody STRIP!
	index=0				# This strips out whitespace chars
	while index < len(thing):	# define exit
		thing[index]=string.strip(thing[index])
		index=index+1		# increase the counter

# and define fileoneline, which reads a file, selects one line at
random,
# and returns that as it's value.
def fileoneline(filename):
	f1=open(filename,'r')
	db=f1.readlines()
	f1.close()
	l=len(db)
	x=int(random.random()*l)
	return db[x]



# ok, let's read that membership file. it is named (listname)
# with no name extension.
f1 = open(path + "/lists/" + listname, 'r')						
members = f1.readlines()	# read all of it in.
f1.close()			# and close the file


# then we look to see if that FROM exists in the membership.
# clean it up;
gangstrip(members)		# strip all leading and trailing whitespace
				# from each element in the list 'members'.

# Ok, now er can start some real data processing!

msg="" 				# initiate a blank STRING variable for the
				# outgoing message.
				# then we look to see if the sender
				# is a member of the list:
if sender in members :		# IF sender is in members, they may post.
	msg = '[' + listname + ']' + subject + CRLF
	# Use OPIONAL reply-to field?
	if os.path.exists(path + "/lists/" +listname +".replyto"): 
		msg = msg + "Reply-to: " + listname + "@" + localhost + CRLF
	# Break email loops with other list servers from forming.
	msg = msg + "X-Loop: " + listname + "@" + localhost 
	
######################################################################
# need to add something to detect X=Loop header to STOP such posts!  #
# Simply ABORT the run if that header is present in the headers.     #
# if a message is QUOTED, it is in the BODY, ignore THAT. -kdb       #
######################################################################

# append incoming message body to outgoing message.
	rfc822.Rewindbody(Message) # set pointer to start of body.
				#  see http://www.python.org/doc/current/lib/message-objects.html
	msg = msg + Message	# for more details. rewindbody() rewinds to the
start of
the body.
	# that last line should add the body of the incoming message to the msg
variable.
	# the footer material is appended AFTER that, so if there is an
attachment, all
	# bloody hell will erupt- which is normal for list managers.
	
	# ok, here are 4 items that are optional.
	# a per list footer, a per list rotation, a global footer, a global
rotation.
	# these are turned on and off by the presence or absense of the
	# relevant file.
	# If you want more than one, duplicate that block, and change the
filename
	# reference. Remember, hackers only down here, yer on yer own.

	# append the list's static footer if there is one.
	if os.path.exists(path + "/lists/" + listname + ".footer"):
		f1=open(path + "/lists/" + listname + ".footer")
		ftr = fi.readlinies()
		f1.close()
		msg = msg + footer + CRLF 
 

	# append one line from the list's random rotation file if there is one.
	if os.path.exists(path + "/lists/"+listname+".random"):
		msg = msg + returnoneline(path + "/lists/"+listname+".random")

	# append the service's GLOBAL footer if there is one.
	if os.path.exists(path + "/lists/"+"global.footer"):
		f1=open(path + "/lists/" + "global.footer")
		f1.close()
		msg=msg + f1.readlines()


	# append one line from the GLOBAL ramdom rotation line if there is one.
	if os.path.exists(path + "/lists/"+"global.random"):
		msg = msg + returnoneline(path + "/lists/" + "global.footer")

	# other additions are certainly possible.
	# this ends processing for an acceptable posting.
	# Next block handles process for
	# REJECTED postings.
	#begin processing for a non member posting.
	
else:	# BUT IF THEY ARE NOT...
	listnamemembers = sender	# put poster address as the
					# ONLY recipient in list!
	msg = ""			# and clear the mesage.
	From_addr = "From: tinylist@" + localhost + CRLF
	msg = "Subject: Unauthorized posting to list: " + listname + CRLF
	msg = "Reply-to: postmaster@" + localhost + CRLF
	msg = "X-Loop: postmaster@" + localhost + CRLF
	msg = msg + CRLF + """To whom it may concern;

Sorry, but as you are not a current member of """ + listname + """, 
you may not post to it. Your recent posting has been rejected and
destroyed.

Feel free to contact the postmaster if there is any question.
Any reply to this letter should go directly to the postmaster.

You can also subscribe to this list if you like.

Goodbye.
	-Tiny the list robot.

"""

# End of alternate process. ABOVE IS 1 BLANK LINE, DO NOT DELETE IT!
# ok, if they are not a member, THEY GET 
# THE REPLY SHOWN ABOVE MAILED TO THEM! 
# (Maybe we could read a stock answer from a file?)


# now we send whatever message is to go out to 
# whatever is in the recipient list.
server = smtplib.SMTP('localhost')	# setup for a smtp run.
# helo(localhost)			# open a connection to the smtp server,
					# possibly not needed
					# so it is commented out.
					# If all else fails, use it.
server.connect()			# and log in to the thing 170
					# as the identity this script runs as.
for to_addr in listnamemembers :	# for each address in
'listnamemembers',
	server.sendmail(from_addr, to_addr, msg)
					# send envlope and msg!

					# don't delete the above line!
server.quit()				# then close the connection.

# make sure this script runs as a TRUSTED USER-
# and NOT as root!!! You set that up in the Sendmail
# Config file (sendmail.cf).
# Make sure that a NON-priviliged user OWNS
# this script, and that it runs as that identity!
#
# The TinyList community hangs out at www.tinylist.org
# and is a pretty informal and friendly bunch of digiteratti.
# Come visit!
#
# We have lists there, which only seems right somehow.
# they are:
# tinylist-users - discussion for all aspects of using
#                  tinylist; frequently quite technical.
#                  ask install and problem questions here.
#
# tinylist-chat - for all intrested in TL, lists, python,
#                 email: a broad charter! 
#
# tinylist-devlopers -	devlopers use this to suport the
#			devlopment of new versions, features, 
#			and bugchasing. *ROUTINELY* -VERY-
#			technical. NOI reccomended to the public.
#
# evil-humor - sick, raunchy, crusty, cynical, depraved, 
#               deprived humor? OVER HERE!
#
# Fnord.
-------------------------------------------------------------------------------------------------





-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From dyoo@hkn.eecs.berkeley.edu  Mon Dec 17 20:02:11 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 17 Dec 2001 12:02:11 -0800 (PST)
Subject: [Tutor] read a random line from a file (fwd)
Message-ID: <Pine.LNX.4.21.0112171155470.5200-100000@hkn.eecs.berkeley.edu>

Hi Kirk,

Let me forward this to the other people here.  Your function looks
good; there's just one line that might need a fix:

###
x = int(1+random.random()*l)
return db[x]
###

Is it possible for x to be 0?  The reason this is important is because
db[0] is the first line in our file --- if we don't allow the possibility
of returning the first line in a file, it's less random than it should be.  
*grin*

This is an example of a "boundary" case: a "boundary" case just means to
tread carefully around the edges of our problem.  In this case, the edges
we should think about are the first and last lines of a file --- make sure
that the function can deal with them well.

Good luck!

---------- Forwarded message ----------
Date: Mon, 17 Dec 2001 14:14:04 -0500
From: Kirk Bailey <deliberatus@my995internet.com>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] read a random line from a file

This works:
def fileoneline(filename):
	f1=open(filename,'r')
	db=f1.readlines()
	f1.close()
	l=len(db)
	x=int(1+random.random()*l)
	return db[x]

Can it be improved?

Danny Yoo wrote:
> 
> On Mon, 17 Dec 2001, Andrei Kulakov wrote:
> 
> > On Sun, Dec 16, 2001 at 11:20:29PM -0500, Kirk Bailey wrote:
> > > OK, I know there is a simple way to do it, and I cannot locate the
> > > correct ommand. I want to open a flat text file, read ONE randomly
> > > selected line into a string, and close the file. I need the command for
> > > reading a line at random, and what module it is in. I understand there
> > > is such a command already defined, and it is simple to use, but canot
> > > find it again.
> 
> Actually, I'm not sure if it's built in at all.  However, we can cook up a
> few definitions so that it becomes a tool we can use.
> 
> To get a random line from a file, it might be useful to write something
> that tells us how many lines a file contains.  Here's one way to do it:
> 
> ###
> def countLines(file):
>     """Given a file, returns the number of lines it contains.
> 
>     The current file position should be preserved as long as the file
>     supports tell() and seek()."""
>     old_position = file.tell()
>     count = 0
>     while file.readline() != '':
>         count = count + 1
>     file.seek(old_position)
>     return count
> ###
> 
> If we had a way to choose a random number between 0 and the countLines()
> of a file, we'd be in business.  Thankfully, there is something in the
> library that can help us: random.randrange():
> 
> ###
> >>> random.randrange(10)
> 4
> >>> random.randrange(10)
> 7
> >>> random.randrange(10)
> 4
> ###
> 
> There is documentation on random.randrange() here:
> 
>     http://www.python.org/doc/lib/module-random.html
> 
> if you're interested in playing around with random stuff.  *grin*
> 
> Also, it would be great if, when we knew which line we wanted to pull out,
> we could get get that particular line.  There's a module called
> 'linecache' that can do this for us:
> 
>     http://www.python.org/doc/lib/module-linecache.html
> 
> But if 'linecache' wasn't there, it still wouldn't be too hard to cook
> something up like it.
> 
> With these tools, it becomes possible to write a simple random line
> grabber:
> 
> ###
> def getRandomLine(filename):
>     """Given a filename, returns a random line."""
>     linecount = countLines(open(filename))
>     chosen_line_number = random.randrange(linecount)
>     return linecache.getline(filename, chosen_line_number)
> ###
> 
> Writing function definitions can be a lot of fun.  Hope this helps!
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/



From DavidCraig@pia.ca.gov  Mon Dec 17 15:37:42 2001
From: DavidCraig@pia.ca.gov (DavidCraig@pia.ca.gov)
Date: Mon, 17 Dec 2001 07:37:42 -0800
Subject: [Tutor] List index out of range
Message-ID: <OF65F8BDF4.A5D246EA-ON88256B25.00552D6E@PIA.CA.GOV>

I am using Idle on WIN 98.  I have the following program:

######################################################
#split and interactively page a string or file of text;
######################################################

import string

def more(text, numlines=15):
    lines=string.split(text, '\n')
    while lines:
        chunk=lines[:numlines]
        lines=lines[numlines:]
        for line in chunk:print line
        if lines and raw_input('More?') not in ['y', 'Y']:break

if __name__=='__main__':
    import sys                           #when run, not imported
    more(open(sys.argv[1]).read(), 10)   #page contents of file on cmdline

Every time I try to run it I get the following error message.

raceback (most recent call last):
  File "C:/Python21/Practice/more.py", line 17, in ?
    more(open(sys.argv[1]).read(), 10)   #page contents of file on cmdline
IndexError: list index out of range

I am unable to find the problem.  How is this out of range and what does
the error message mean?

TIA

Dave

D. H. Craig, CSM



From DavidCraig@pia.ca.gov  Mon Dec 17 18:02:52 2001
From: DavidCraig@pia.ca.gov (DavidCraig@pia.ca.gov)
Date: Mon, 17 Dec 2001 10:02:52 -0800
Subject: [Tutor] IndexError:list index out of range
Message-ID: <OFE3E9A0AC.0AA2BD66-ON88256B25.0062EC25@PIA.CA.GOV>

I am using Idle on WIN 98.  I have the following program:

######################################################
#split and interactively page a string or file of text;
######################################################

import string

def more(text, numlines=15):
    lines=string.split(text, '\n')
    while lines:
        chunk=lines[:numlines]
        lines=lines[numlines:]
        for line in chunk:print line
        if lines and raw_input('More?') not in ['y', 'Y']:break

if __name__=='__main__':
    import sys                           #when run, not imported
    more(open(sys.argv[1]).read(), 10)   #page contents of file on cmdline

Every time I try to run it I get the following error message.

raceback (most recent call last):
  File "C:/Python21/Practice/more.py", line 17, in ?
    more(open(sys.argv[1]).read(), 10)   #page contents of file on cmdline
IndexError: list index out of range

I am unable to find the problem.  How is this out of range and what does
the error message mean?

TIA

Dave

D. H. Craig, CSM

D. H. Craig, CSM



From rick@niof.net  Mon Dec 17 20:03:43 2001
From: rick@niof.net (rick@niof.net)
Date: Mon, 17 Dec 2001 15:03:43 -0500
Subject: [Tutor] latest snapshot of TLpost.py
In-Reply-To: <3C1E49FE.D7057959@my995internet.com>
References: <3C1E49FE.D7057959@my995internet.com>
Message-ID: <20011217150343.B17103@tc.niof.net>

On Mon, Dec 17, 2001 at 02:39:42PM -0500, Kirk Bailey wrote:
> Latest snapshot of TLpost.
> 
> # now some code to debug with- remove it later.
> type(Message)
> print Message

It's generally not a good idea to override a builtin function. Maybe
call it MyType or MyDebug.

-- 
You contend that I am wrong to practice Catholicism; and I contend
that you are wrong to practice Lutheranism. Let us leave it to God
to judge. Why should I strike at you, or why should you strike at
me? If it is not good that one of us should strike the other, how
can it be good that we should delegate to a third party, who
controls the public police force, the authority to strike at one
of us in order to please the other?
	-- Frédéric Bastiat (1801-1850)
    Rick Pasotto    rickp@telocity.com    http://www.niof.net


From dyoo@hkn.eecs.berkeley.edu  Mon Dec 17 20:20:53 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 17 Dec 2001 12:20:53 -0800 (PST)
Subject: [Tutor] IndexError:list index out of range
In-Reply-To: <OFE3E9A0AC.0AA2BD66-ON88256B25.0062EC25@PIA.CA.GOV>
Message-ID: <Pine.LNX.4.21.0112171215240.5492-100000@hkn.eecs.berkeley.edu>

On Mon, 17 Dec 2001 DavidCraig@pia.ca.gov wrote:

> 
> I am using Idle on WIN 98.  I have the following program:
> 
> ######################################################
> #split and interactively page a string or file of text;
> ######################################################
> 
> import string
> 
> def more(text, numlines=15):
>     lines=string.split(text, '\n')
>     while lines:
>         chunk=lines[:numlines]
>         lines=lines[numlines:]
>         for line in chunk:print line
>         if lines and raw_input('More?') not in ['y', 'Y']:break
> 
> if __name__=='__main__':
>     import sys                           #when run, not imported
>     more(open(sys.argv[1]).read(), 10)   #page contents of file on cmdline
> 
> Every time I try to run it I get the following error message.
> 
> raceback (most recent call last):
>   File "C:/Python21/Practice/more.py", line 17, in ?
>     more(open(sys.argv[1]).read(), 10)   #page contents of file on cmdline
> IndexError: list index out of range


The error's probably referring to the 'sys.argv[1]' part of that line:
that part is trying to get at the 2nd argument given from a command line.  
However, since we're running this from IDLE, and since we haven't
specified a command line, the sys.argv list is probably empty.


According to the IDLE documentation at:

    http://www.python.org/idle/doc/idle2.html

"""
You can of course also test files that are being developed to actually be
scripts in this way as well. You can't currently set command line options
and parameters when you invoke the Run script command. However, during
development you can always instrument your code with a simple test
function that sets sys.argv to any desired value (simulating a command
line invocation) before calling your regular top level script function.
"""


It sounds like it recommendsy hardcoding a sys.argv value while testing
the rest of your program out.  Does anyone know a better solution?



From dyoo@hkn.eecs.berkeley.edu  Mon Dec 17 20:29:36 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 17 Dec 2001 12:29:36 -0800 (PST)
Subject: [Tutor] class Clowning: saving references to other instances
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1C7@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.21.0112171225320.5492-100000@hkn.eecs.berkeley.edu>

On Mon, 17 Dec 2001 alan.gauld@bt.com wrote:
>
> > The reason why I'm doing this is just to save 
> > a little redundant processing. 
> 
> But you are introducing a heap of redundant 
> processing by calling exec!

And exec() can be extremely dangerous unless we're careful about it.  We
had a thread about it a while back in September:

    http://aspn.activestate.com/ASPN/Mail/Message/788238


There are usually alternatives to using exec() that are easier to read,
evaluate more quickly, and work out more nicely.



From dyoo@hkn.eecs.berkeley.edu  Mon Dec 17 20:34:52 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 17 Dec 2001 12:34:52 -0800 (PST)
Subject: [Tutor] why BaseClass.__init__ needs to be called explicitly?
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1CD@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.21.0112171230530.5492-100000@hkn.eecs.berkeley.edu>

On Mon, 17 Dec 2001 alan.gauld@bt.com wrote:

> > Is there any specific reason behind this...
> 
> Its a good thing coz it offers more control to
> the programmer.

It also fits well with the "explicitness" quality that Python programs
have --- Python tends to try avoiding actions that surprise programmers.
There's a tongue-in-cheek list of Python design decisions here:

    http://python.org/doc/Humor.html#zen



> > 2. do we have a search facility on tutor/python-list sites? 
> 
> The ActiveState archive is searchable.


Here's the link:

    http://aspn.activestate.com/ASPN/Mail/Archives/python-Tutor/



From lumbricus@gmx.net  Mon Dec 17 21:41:33 2001
From: lumbricus@gmx.net (Joerg Woelke)
Date: Mon, 17 Dec 2001 22:41:33 +0100
Subject: [Tutor] IndexError:list index out of range
In-Reply-To: <OFE3E9A0AC.0AA2BD66-ON88256B25.0062EC25@PIA.CA.GOV>; from DavidCraig@pia.ca.gov on Mon, Dec 17, 2001 at 10:02:52AM -0800
References: <OFE3E9A0AC.0AA2BD66-ON88256B25.0062EC25@PIA.CA.GOV>
Message-ID: <20011217224133.A7903@Laplace.localdomain>

On Mon, Dec 17, 2001 at 10:02:52AM -0800, DavidCraig@pia.ca.gov wrote:
> 
> I am using Idle on WIN 98.  I have the following program:
> 
> ######################################################
> #split and interactively page a string or file of text;
> ######################################################
> 

[ snip ]

> if __name__=='__main__':
>     import sys                           #when run, not imported
>     more(open(sys.argv[1]).read(), 10)   #page contents of file on cmdline

If there is no sys.argv[1] it yields IndexError.

A construct like this may help you:
try:
	what_you_want_to_do()
except IndexError:
	print "Usage: <cmd> <arg>"

> 
> Every time I try to run it I get the following error message.
> 
> raceback (most recent call last):
>   File "C:/Python21/Practice/more.py", line 17, in ?
>     more(open(sys.argv[1]).read(), 10)   #page contents of file on cmdline
           ^^^^^^^^^^^^^^^^^
<hint> If this file does not exist or you
are not allowed to read it, your script will
yield an error too.

> IndexError: list index out of range
> 
> I am unable to find the problem.  How is this out of range and what does
> the error message mean?

You want to read about try/except

> 
> TIA
> 
> Dave
> 
> D. H. Craig, CSM

HTH, HAND
and Greetings J"o!

-- 
Absence makes the heart grow frantic.


From fpeavy@pop.net  Mon Dec 17 21:08:32 2001
From: fpeavy@pop.net (Frank Peavy)
Date: Mon, 17 Dec 2001 13:08:32 -0800
Subject: [Tutor] Division question, simple
Message-ID: <5.1.0.14.0.20011217125840.00a8ada0@mail45566.popserver.pop.net>

In the interactive mode:
 >>> 75/100
0
 >>> float(75/100)
0.0
 >>> x = 75
 >>> y = 100
 >>> float(x/y)
0.0
 >>> float(75)/float(100)
0.75

In order to get 75%, I almost need to know my desired result, before I have 
my values. Is this how everyone handles simple division in Python?

When I am dividing 100 by 25 the result is an integer of 4, fine.
But, when I don't know my second value is 25... maybe it is 33, then my 
result would be 3.33333
BUT, Python gives me 3.  How does everyone else handle this?



From shalehperry@attbi.com  Mon Dec 17 21:11:59 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 17 Dec 2001 13:11:59 -0800 (PST)
Subject: [Tutor] Division question, simple
In-Reply-To: <5.1.0.14.0.20011217125840.00a8ada0@mail45566.popserver.pop.net>
Message-ID: <XFMail.20011217131159.shalehperry@attbi.com>

On 17-Dec-2001 Frank Peavy wrote:
> In the interactive mode:
>  >>> 75/100
> 0
>  >>> float(75/100)
> 0.0
>  >>> x = 75
>  >>> y = 100
>  >>> float(x/y)
> 0.0
>  >>> float(75)/float(100)
> 0.75
> 
> In order to get 75%, I almost need to know my desired result, before I have 
> my values. Is this how everyone handles simple division in Python?
> 
> When I am dividing 100 by 25 the result is an integer of 4, fine.
> But, when I don't know my second value is 25... maybe it is 33, then my 
> result would be 3.33333
> BUT, Python gives me 3.  How does everyone else handle this?
> 

if I know I want a decimal, I cast one number to a float.


From glingl@aon.at  Mon Dec 17 22:30:29 2001
From: glingl@aon.at (Gregor Lingl)
Date: Mon, 17 Dec 2001 23:30:29 +0100
Subject: [Tutor] Division question, simple
References: <XFMail.20011217131159.shalehperry@attbi.com>
Message-ID: <002201c1874a$6e6dbde0$1664a8c0@mega>

The answer is, that / simply performs two
different kinds of division (or as some say,
the / - Operator is overloaded ) depending
on the type of the operands.

If both operands ar of type int (or long int)
(as is the case when evaluating 75/100)
/ delivers the integer quotient of the operands.

if at least one of the operands is of type float
(for instance 75.0/100 or equivalently float(75)/100)
the result will also be of type float.

So if you want to perform floating-point-division you
have to ensure, that at least one operand is of type
float.

As the designers of Python recognized this to be
an error-prone approach, they decided (as usual after a
lengthy discussion) to change this
int the __future__ and to introduce a special
operator // for integer division - the / at the same
time reserving to conventional division.

You can take advantage of this from Dec. 21th (approx.) on
- if you like - by using Python 2.2 an the statement

from __future__ import division

at the beginning of your modules.
In any case Python 2.2 will provide the integer-division-operator //.

But beware of breaking older modules which depend
on the / - integer-division.

(I assume there will certainly be a paragraph on this in
the new Python 2.2 Documentation)

Gregor

----- Original Message -----
From: "Sean 'Shaleh' Perry" <shalehperry@attbi.com>
To: "Frank Peavy" <fpeavy@pop.net>
Cc: "tutor-python.org" <tutor@python.org>
Sent: Monday, December 17, 2001 10:11 PM
Subject: Re: [Tutor] Division question, simple


>
> On 17-Dec-2001 Frank Peavy wrote:
> > In the interactive mode:
> >  >>> 75/100
> > 0
> >  >>> float(75/100)
> > 0.0
> >  >>> x = 75
> >  >>> y = 100
> >  >>> float(x/y)
> > 0.0
> >  >>> float(75)/float(100)
> > 0.75
> >
> > In order to get 75%, I almost need to know my desired result, before I
have
> > my values. Is this how everyone handles simple division in Python?
> >
> > When I am dividing 100 by 25 the result is an integer of 4, fine.
> > But, when I don't know my second value is 25... maybe it is 33, then my
> > result would be 3.33333
> > BUT, Python gives me 3.  How does everyone else handle this?
> >
>
> if I know I want a decimal, I cast one number to a float.
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From glingl@aon.at  Mon Dec 17 22:34:25 2001
From: glingl@aon.at (Gregor Lingl)
Date: Mon, 17 Dec 2001 23:34:25 +0100
Subject: [Tutor] Hummm...dubious behavior.
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1C8@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <002901c1874a$fb3a0da0$1664a8c0@mega>

----- Original Message ----- 
From: <alan.gauld@bt.com>

> Thus:
> 
> >>> print "%5.3" % math.pi
> 3.142


This should read

>>> print "%5.3f" % math.pi
3.142

otherwise a ValueError would occur.

Gregor



From i812@iname.com  Mon Dec 17 22:49:32 2001
From: i812@iname.com (Rob McGee)
Date: Mon, 17 Dec 2001 16:49:32 -0600
Subject: [Tutor] class Clowning: saving references to other instances
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1C7@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Mon, Dec 17, 2001 at 03:46:22PM -0000
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1C7@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20011217164932.F18603@hal>

On Mon, Dec 17, 2001 at 03:46:22PM -0000, alan.gauld@bt.com wrote:
> >     self.location = location    # an integer, unique
> >     self.index = index          # also unique integer
> >     self.name = uppercase[index]  # uppercase letter, also 
> 
> Huh? index is a unique integer... but you are taking 
> the uppercase of it?

I was just using that as a way of generating the name string, which has
to be unique. I probably don't need to save self.index, but figured I
should hang on to it in case I find a use later. :) Like for help in
iterating through a list, for example.

Oh, let me explain it. This was preceded by a
    from string import uppercase
statement, so "uppercase" is a string here, and I am slicing it with the
"index" (integer, 0-25) value.

> > from one Clown instance to another. The 
> > distance(self, other) method uses "exec" 
> > to store the distance values in self.(other.name) 
> 
> Oh dear, not again... ;-)
> Using exec for this is really not very good.

No, not again. :) I think I've gotten away from exec, which was getting
to be my own personal GOTO. :)

> A dictionary to store these would be better.

I've already given up the exec. :) I will try a dictionary instead of a
list. Did you see my post about "dictionary vs. list considerations"
after this one? I was thinking that dictionaries would take up a lot
more memory. The one response I got indicated that speed of execution
would probably be better with dictionaries. But I was afraid that they
might hog a lot more memory?

> Correct, if you want to access things by a string key 
> (name in this case) the best solution is nearly 
> always to use a dictionary and nearly never to use 
> exec()!

ISTM if I switch to dictionaries I could use the objects themselves as
the keys? But I don't (yet) see how that would be easier than strings as
keys. The input will originate from the user, which of course means it
starts out as a string. I'll have to think about it some more.

> > The reason why I'm doing this is just to save 
> > a little redundant processing. 
> 
> But you are introducing a heap of redundant 
> processing by calling exec!

#!/usr/bin/env python
def exec(*args):
  print "Don't use exec!!"

In all my *.py files. Does that look better? :)

> > One solution would be to put the "exec" code in a function 
> 
> That tidies it up a little but doesn't really help.

Yes, I figured that out while I was writing the post to which you
replied. :)

> > Have I figured out my own solution?!? :) 
> 
> Getting closer, but dictionaries instead of lists 
> would make it all much easier IMHO.

Yes, I thought so too. I'll try it.

Thanks for taking the time to understand the situation and reply.

And to you, Danny, thanks for the link. I looked it up. In this case I
don't have a security issue, but it's important to be aware of such
things. On the side, I was especially pleased to find a searchable
archive of this list! :)

    Rob - /dev/rob0


From curtis.larsen@Covance.Com  Mon Dec 17 22:58:17 2001
From: curtis.larsen@Covance.Com (Curtis Larsen)
Date: Mon, 17 Dec 2001 16:58:17 -0600
Subject: [Tutor] Module Files Placement?
Message-ID: <sc1e243e.085@madis2.truax.covance.com>

What is the accepted standard on adding third-party modules to your
Python installation?  (Where do you put the files?)  Even though pretty
much anywhere in PYTHONPATH would work, there has to be a system of some
kind (a "/usr/local/bin" if you will) to keep them accessible, yet
separate -- including all the extra modules THEY would in turn call.

I know this has probably been covered Elsewhere, but I can't remember
how it was done.  Please point me in the right direction, or just
explain what works for you.


Thanks!
Curtis



From shalehperry@attbi.com  Mon Dec 17 23:51:54 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 17 Dec 2001 15:51:54 -0800 (PST)
Subject: [Tutor] Module Files Placement?
In-Reply-To: <sc1e243e.085@madis2.truax.covance.com>
Message-ID: <XFMail.20011217155154.shalehperry@attbi.com>

On 17-Dec-2001 Curtis Larsen wrote:
> What is the accepted standard on adding third-party modules to your
> Python installation?  (Where do you put the files?)  Even though pretty
> much anywhere in PYTHONPATH would work, there has to be a system of some
> kind (a "/usr/local/bin" if you will) to keep them accessible, yet
> separate -- including all the extra modules THEY would in turn call.
> 
> I know this has probably been covered Elsewhere, but I can't remember
> how it was done.  Please point me in the right direction, or just
> explain what works for you.
> 
> 

this is referred to as site-packages.


From karthikg@aztec.soft.net  Tue Dec 18 05:09:48 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Tue, 18 Dec 2001 10:39:48 +0530
Subject: [Tutor] properties not working in 2.2
In-Reply-To: <XFMail.20011217155154.shalehperry@attbi.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDOENDCLAA.karthikg@aztec.soft.net>

hi all,

http://www.python.org/2.2/descrintro.html#property

there is an example to use properties which is not workign for me under
Python 2.2a1

class C(object):
    def __init__(self):
        print "hello world"
        self.__x = 0
    def getx(self):
        print "get called"
        return self.__x
    def setx(self, x):
        print "set called"
        if x < 0: x = 0
        self.__x = x
    x = property(getx,setx,None,"this is property")


this is the trace....

  File "test.py", line 13, in C
    x = property(getx,setx,None,"this is property")
NameError: name 'property' is not defined

can someone tell me as what's wrong here? ..python2.2 a1 does not have this
feature??

thanx,
karthik




From glingl@aon.at  Tue Dec 18 06:29:20 2001
From: glingl@aon.at (Gregor Lingl)
Date: Tue, 18 Dec 2001 07:29:20 +0100
Subject: [Tutor] properties not working in 2.2
References: <NEBBJNMDEKBIBCMCNMBDOENDCLAA.karthikg@aztec.soft.net>
Message-ID: <001201c1878d$53942200$1664a8c0@mega>

My installation of Python 2.2c1 definitely
doesn't show this (or any other) error-massage
when running your example

instead, I got:

>>> huch = C()
hello world
>>> huch.x
get called
0
>>>

but what is property - and what is it for?

Gregor

----- Original Message -----
From: "karthik Guru" <karthikg@aztec.soft.net>
To: <tutor@python.org>
Sent: Tuesday, December 18, 2001 6:09 AM
Subject: [Tutor] properties not working in 2.2


> hi all,
>
> http://www.python.org/2.2/descrintro.html#property
>
> there is an example to use properties which is not workign for me under
> Python 2.2a1
>
> class C(object):
>     def __init__(self):
>         print "hello world"
>         self.__x = 0
>     def getx(self):
>         print "get called"
>         return self.__x
>     def setx(self, x):
>         print "set called"
>         if x < 0: x = 0
>         self.__x = x
>     x = property(getx,setx,None,"this is property")
>
>
> this is the trace....
>
>   File "test.py", line 13, in C
>     x = property(getx,setx,None,"this is property")
> NameError: name 'property' is not defined
>
> can someone tell me as what's wrong here? ..python2.2 a1 does not have
this
> feature??
>
> thanx,
> karthik
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From dyoo@hkn.eecs.berkeley.edu  Tue Dec 18 08:08:27 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 18 Dec 2001 00:08:27 -0800 (PST)
Subject: [Tutor] Module Files Placement?
In-Reply-To: <sc1e243e.085@madis2.truax.covance.com>
Message-ID: <Pine.LNX.4.21.0112180003480.23683-100000@hkn.eecs.berkeley.edu>

On Mon, 17 Dec 2001, Curtis Larsen wrote:

> What is the accepted standard on adding third-party modules to your
> Python installation?  (Where do you put the files?)  Even though
> pretty much anywhere in PYTHONPATH would work, there has to be a
> system of some kind (a "/usr/local/bin" if you will) to keep them
> accessible, yet separate -- including all the extra modules THEY would
> in turn call.

External modules should live in a 'site-packages' directory underneath
Python's lib directory.

For example, on my computer, it's located here:

    /usr/local/lib/python2.1/site-packages/

Out of curiosity though: are you trying to install a module?  The
"distutils" are a set of tools to make installing new modules fairly
automatic.  Third parties often use the distutils to more easily make an
installation script that works.



From toodles@yifan.net  Tue Dec 18 08:39:40 2001
From: toodles@yifan.net (Andy W)
Date: Tue, 18 Dec 2001 16:39:40 +0800
Subject: [Tutor] properties not working in 2.2
References: <NEBBJNMDEKBIBCMCNMBDOENDCLAA.karthikg@aztec.soft.net> <001201c1878d$53942200$1664a8c0@mega>
Message-ID: <004d01c1879f$8a075250$0300a8c0@sun>

> but what is property - and what is it for?
>
> Gregor

Quoting directly from: http://www.python.org/2.2/descrintro.html#property

"Properties are a neat way to implement attributes whose usage resembles
attribute access, but whose implementation uses method calls. These are
sometimes known as "managed attributes". In prior Python versions, you could
only do this by overriding __getattr__ and __setattr__; but overriding
__setattr__ slows down all attribute assignments considerably, and
overriding __getattr__ is always a bit tricky to get right. Properties let
you do this painlessly, without having to override __getattr__ or
__setattr__."

HTH,
Andrew

>
> ----- Original Message -----
> From: "karthik Guru" <karthikg@aztec.soft.net>
> To: <tutor@python.org>
> Sent: Tuesday, December 18, 2001 6:09 AM
> Subject: [Tutor] properties not working in 2.2
>
>
> > hi all,
> >
> > http://www.python.org/2.2/descrintro.html#property
> >
> > there is an example to use properties which is not workign for me under
> > Python 2.2a1
> >
> > class C(object):
> >     def __init__(self):
> >         print "hello world"
> >         self.__x = 0
> >     def getx(self):
> >         print "get called"
> >         return self.__x
> >     def setx(self, x):
> >         print "set called"
> >         if x < 0: x = 0
> >         self.__x = x
> >     x = property(getx,setx,None,"this is property")
> >
> >
> > this is the trace....
> >
> >   File "test.py", line 13, in C
> >     x = property(getx,setx,None,"this is property")
> > NameError: name 'property' is not defined
> >
> > can someone tell me as what's wrong here? ..python2.2 a1 does not have
> this
> > feature??
> >
> > thanx,
> > karthik
> >
> >
> >
> > _______________________________________________
> > 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 karthikg@aztec.soft.net  Tue Dec 18 09:18:09 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Tue, 18 Dec 2001 14:48:09 +0530
Subject: [Tutor] properties not working in 2.2
In-Reply-To: <001201c1878d$53942200$1664a8c0@mega>
Message-ID: <NEBBJNMDEKBIBCMCNMBDIENFCLAA.karthikg@aztec.soft.net>

class test:
	def __init__(self):
		pass
	__getattr__(self,name):


t = test()
t.age = 100
print t.age

the link has a detailed explanation for properties.
some of things i found very important..

__getattr__ is only called if age isn't found in the instance's dictionary.
so in this case it won't be called. __setattr__ is always called when we set
a value to an attribute.

but in case of properties, we have the new keyword "property" with which we
can qualify
an attribute as a property.

we can define accessor and mutator methods for that and register the same
using the
property keyword. Both the special methods "will" be called whenever someone
tries to change / access it.

so indirectly, we know when someone reads / sets an attribute and we can put
our custom code there. for eg: You might want to reject some values in your
set by
throwing an exception. Or you might not want a particular to client to read
a property ..
(so that code goes into the corresponding "get").

There was just one __getattr__ available to handle all attributes earlier.
But now we can have separate get and set for different atributes.

Also, if you don't define a set for a property named x, then it
automatically becomes read only.
if someone tries to set the value to that attribute it raises an
AttributeError.

I have observed such a feature in MS's C# as well. This was there in C#
specs long back.
Can some one tell from their experience if it's present in other languages
as well OR is it a MS innovation :-)

please refer to this for a very good explanation.
http://www.python.org/2.2/descrintro.html#property

karthik.














-----Original Message-----
From: Gregor Lingl [mailto:glingl@aon.at]
Sent: Tuesday, December 18, 2001 11:59 AM
To: karthik Guru; tutor@python.org
Subject: Re: [Tutor] properties not working in 2.2


My installation of Python 2.2c1 definitely
doesn't show this (or any other) error-massage
when running your example

instead, I got:

>>> huch = C()
hello world
>>> huch.x
get called
0
>>>

but what is property - and what is it for?

Gregor

----- Original Message -----
From: "karthik Guru" <karthikg@aztec.soft.net>
To: <tutor@python.org>
Sent: Tuesday, December 18, 2001 6:09 AM
Subject: [Tutor] properties not working in 2.2


> hi all,
>
> http://www.python.org/2.2/descrintro.html#property
>
> there is an example to use properties which is not workign for me under
> Python 2.2a1
>
> class C(object):
>     def __init__(self):
>         print "hello world"
>         self.__x = 0
>     def getx(self):
>         print "get called"
>         return self.__x
>     def setx(self, x):
>         print "set called"
>         if x < 0: x = 0
>         self.__x = x
>     x = property(getx,setx,None,"this is property")
>
>
> this is the trace....
>
>   File "test.py", line 13, in C
>     x = property(getx,setx,None,"this is property")
> NameError: name 'property' is not defined
>
> can someone tell me as what's wrong here? ..python2.2 a1 does not have
this
> feature??
>
> thanx,
> karthik
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From karthikg@aztec.soft.net  Tue Dec 18 09:19:06 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Tue, 18 Dec 2001 14:49:06 +0530
Subject: [Tutor] properties not working in 2.2
In-Reply-To: <001201c1878d$53942200$1664a8c0@mega>
Message-ID: <NEBBJNMDEKBIBCMCNMBDMENFCLAA.karthikg@aztec.soft.net>

by the way i downloaded python22c1 and it's working just fine now!

-----Original Message-----
From: Gregor Lingl [mailto:glingl@aon.at]
Sent: Tuesday, December 18, 2001 11:59 AM
To: karthik Guru; tutor@python.org
Subject: Re: [Tutor] properties not working in 2.2


My installation of Python 2.2c1 definitely
doesn't show this (or any other) error-massage
when running your example

instead, I got:

>>> huch = C()
hello world
>>> huch.x
get called
0
>>>

but what is property - and what is it for?

Gregor




From m_konermann@gmx.de  Tue Dec 18 09:50:59 2001
From: m_konermann@gmx.de (Marcus Konermann)
Date: Tue, 18 Dec 2001 10:50:59 +0100
Subject: [Tutor] Python Extension under Win 2000
Message-ID: <3C1F1183.69582871@gmx.de>

Hi @ All !

I´ve created a python extension under windows2000 using developer studio
like it is described under chapter 9 of the swig manual. I´ve also
created a python shadow class and now i want to use it by importing some
methods of the simannealfile.py module  (the generated shadow class),
but pythonwin says, that it don´t find the simannealfilec.py module.
what can i do ?

Greetings
Marcus



From alan.gauld@bt.com  Tue Dec 18 11:27:11 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 18 Dec 2001 11:27:11 -0000
Subject: [Tutor] properties not working in 2.2
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1CF@mbtlipnt02.btlabs.bt.co.uk>

> I have observed such a feature in MS's C# as well. 
> Can some one tell from their experience if it's present in 
> other languages

Its in VB and also in Delphi.
I'm not sure which did it first but it definitely seems 
to come from the Windows world, either via MS or Borland.

In both cases it was originally used to enable 
intelligent GUI builders - you can instantiate a 
copy of the object when placing it on the form and 
set attributes via properties. The property events 
can do smart things like display live data in 
design mode etc. At least I think thats what they 
were first in vented for, my memory is getting hazy 
as old age sets in ;-/

In any case it turns out that they are more generally 
useful - for example you can define a property which 
is a derived field but looks like a fixed field:

### Pseudo code warning ###
class X:
    def __init__(self,min,max):
       self.min b= min
       self.max = max
    def getMean(self): return (self.min-self.max)/2
    property average(self.getMean,None,None, "get average")

x = X(1,5)
print x.min
print x.max
print x.average

So it looks like average is a field of X but in 
fact is a return from a method. The same could 
be done for max,min and the whole thing could 
wrap a database table such that the min,max and 
average did a dynamic SQL lookup and returned 
the relevant values. But to the client it still 
looks like an attribute of the object...

Alan g.


From aschmidt@nv.cc.va.us  Tue Dec 18 12:52:08 2001
From: aschmidt@nv.cc.va.us (Schmidt, Allen J.)
Date: Tue, 18 Dec 2001 07:52:08 -0500
Subject: [Tutor] PayPal verification script
Message-ID: <5CDFEBB60E7FD311B9E30000F6D6090608CB8EA0@novamail2.nv.cc.va.us>

Has anyone done a PayPal Instant Payment Verification program for Python? On
PayPal's site is sample code for Perl and ASP. I need something in Python
(and/or Zope) to handle the payment verification part. Since its free to
sign up and use PayPal including Business and Premier accounts, I hope
someone will have this info or be willing/able to sign up and check it out.

Thanks

Allen


From karthikg@aztec.soft.net  Tue Dec 18 13:26:30 2001
From: karthikg@aztec.soft.net (karthik Guru)
Date: Tue, 18 Dec 2001 18:56:30 +0530
Subject: [Tutor] properties not working in 2.2
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1CF@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <NEBBJNMDEKBIBCMCNMBDGENJCLAA.karthikg@aztec.soft.net>

this is just my observation as a beginner...

i went through the changes in python2.2.
i think many basic things have changed.

I think newbies should learn python using python2.2!.
This is just a recommendation coming from another newbie (that's me).
i think it will be a lot easier to learn that way.

I saw some code in python cook book recipies to emulate properties
plus lots of other things.
I myself experienced the problems associated with __getattr__ ( as to how it
makes recursive calls).
But when i look @ some of the features in python2.2,
i guess we really don't've to be that smart :-)

i saw that now we can write static methods.

may be sometime down the lane we will have keywords like private, protected
and stuff like that as well.

Am not sure how others, who have been doing professional work in python for
years react to this?
Simply put this is my question,

do you guys prefer writing the kind of code presented in the cook book or
are you happy with having a
construct like "property" which makes life so simple?

thanks,
karthik.




-----Original Message-----
From: alan.gauld@bt.com [mailto:alan.gauld@bt.com]
Sent: Tuesday, December 18, 2001 4:57 PM
To: karthikg@aztec.soft.net; glingl@aon.at; tutor@python.org
Subject: RE: [Tutor] properties not working in 2.2


> I have observed such a feature in MS's C# as well.
> Can some one tell from their experience if it's present in
> other languages

Its in VB and also in Delphi.
I'm not sure which did it first but it definitely seems
to come from the Windows world, either via MS or Borland.

In both cases it was originally used to enable
intelligent GUI builders - you can instantiate a
copy of the object when placing it on the form and
set attributes via properties. The property events
can do smart things like display live data in
design mode etc. At least I think thats what they
were first in vented for, my memory is getting hazy
as old age sets in ;-/

In any case it turns out that they are more generally
useful - for example you can define a property which
is a derived field but looks like a fixed field:

### Pseudo code warning ###
class X:
    def __init__(self,min,max):
       self.min b= min
       self.max = max
    def getMean(self): return (self.min-self.max)/2
    property average(self.getMean,None,None, "get average")

x = X(1,5)
print x.min
print x.max
print x.average

So it looks like average is a field of X but in
fact is a return from a method. The same could
be done for max,min and the whole thing could
wrap a database table such that the min,max and
average did a dynamic SQL lookup and returned
the relevant values. But to the client it still
looks like an attribute of the object...

Alan g.



From slime@vsnl.net  Tue Dec 18 05:40:41 2001
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Tue, 18 Dec 2001 11:10:41 +0530
Subject: [Tutor] Re:  display filter slow
In-Reply-To: <20011217085131.GA3141@localhost.localdomain>
References: <20011217085131.GA3141@localhost.localdomain>
Message-ID: <20011218054041.GA3263@localhost.localdomain>

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

Hi,

On Mon, 17 Dec 2001 Prahlad Vaidyanathan spewed into the ether:
[-- snip --]
> As you can see, the script takes nearly thrice the amount of time as
> without it. I'm sure there is a more efficient way of filtering my mail,
> so any help would be appreciated.

I know replying to one's own post is a Bad Thing, but I found out on my
own, so I thought I should post it.

The reason it was taking so long to start was that the python
interpreter itself was taking a very long time to load. On startup, the
interpreter tries to import a whole bunch of site-packages. All the
packages it tried to import had a 'bad mtime' - hence it tried to
byte-compile the .py file into the .pyc equivalent. Since I didn't have
write-access to the /usr/lib/python2.0 directory, it complained, but
continued nonetheless. But, the delay involved in recongising and
reporting this problem caused the overall delay of the script.

Now, what I want to know is this :

* Why did python try importing a whole bunch of site-packages when I did
not give explicit instructions to import them

* Why were the mtimes for the .pyc files bad (This is prolly a problem
with my personal python package, but maybe it's universal)

I solved this problem by just giving myself write-access to the
/usr/lib/python2.0 directory. But, this is only possible on my home
system where I know the root password - on other systems it is not. I
would like to know how one would solve this if one didn't have root
access.

I hope I have been clear. I have attached a (slightly) updated version
of the script I posted yesterday. It works right now, but I hope to add
a few more features to it soon. Any feedback is welcome :-)

pv.

--=20
Prahlad Vaidyanathan <slime@vsnl.net>                What, me worry ?
http://www.symonds.net/~prahladv/                    Don't Panic !
--

--qDbXVdCdHGoSgWSk
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

iD8DBQE8HtbZIKhjOSElu4YRAqXxAKCn1elBnU9VC7L/e4sioCGBYJR5dQCfUu1k
0UdZWaNjBlr7cAUf+Tge15M=
=mpaN
-----END PGP SIGNATURE-----

--qDbXVdCdHGoSgWSk--


From dsh8290@rit.edu  Tue Dec 18 15:47:34 2001
From: dsh8290@rit.edu (dman)
Date: Tue, 18 Dec 2001 10:47:34 -0500
Subject: [Tutor] dictionary vs. list considerations
In-Reply-To: <20011216153640.D3310@hal>; from i812@iname.com on Sun, Dec 16, 2001 at 03:36:40PM -0600
References: <20011216153640.D3310@hal>
Message-ID: <20011218104734.A19265@harmony.cs.rit.edu>

On Sun, Dec 16, 2001 at 03:36:40PM -0600, Rob McGee wrote:
| For what I want to do a dictionary would be a little easier to use, but
| a list could suffice. What kind of considerations (such as performance
| and memory use) are there in deciding which to use? I don't mind having
| a little bit more code (to retrieve my objects out of a list) if it's
| faster or uses less memory than a dictionary.

Which one better embodies the conceptual structure you want to use?
Which one will make the code more readable and easier?  

-D

-- 

Python is executable pseudocode. Perl is executable line noise.



From dsh8290@rit.edu  Tue Dec 18 15:51:15 2001
From: dsh8290@rit.edu (dman)
Date: Tue, 18 Dec 2001 10:51:15 -0500
Subject: [Tutor] Re:  display filter slow
In-Reply-To: <20011218054041.GA3263@localhost.localdomain>; from slime@vsnl.net on Tue, Dec 18, 2001 at 11:10:41AM +0530
References: <20011217085131.GA3141@localhost.localdomain> <20011218054041.GA3263@localhost.localdomain>
Message-ID: <20011218105115.B19265@harmony.cs.rit.edu>

On Tue, Dec 18, 2001 at 11:10:41AM +0530, Prahlad Vaidyanathan wrote:
... 
| The reason it was taking so long to start was that the python
| interpreter itself was taking a very long time to load. On startup, the
| interpreter tries to import a whole bunch of site-packages. All the
| packages it tried to import had a 'bad mtime' - hence it tried to
| byte-compile the .py file into the .pyc equivalent. Since I didn't have
| write-access to the /usr/lib/python2.0 directory, it complained, but
| continued nonetheless. But, the delay involved in recongising and
| reporting this problem caused the overall delay of the script.
| 
| Now, what I want to know is this :
| 
| * Why did python try importing a whole bunch of site-packages when I did
| not give explicit instructions to import them

It imports "site.py" unless you explicitly say not to.  That script
often imports a bunch of standard stuff.  The site.py script is a way
that an admin can customize the local installation (set sys.path or
something, for example).

| * Why were the mtimes for the .pyc files bad (This is prolly a problem
| with my personal python package, but maybe it's universal)

The mtime (last modified) of the .py file is more recent than the .pyc
file.  Therefore the interpreter can't assume that the .pyc file
contains the code written in the .py file and must then parse and
byte-compile the .py file.

-D

-- 

Better a little with righteousness
than much gain with injustice.
        Proverbs 16:8



From dsh8290@rit.edu  Tue Dec 18 15:52:23 2001
From: dsh8290@rit.edu (dman)
Date: Tue, 18 Dec 2001 10:52:23 -0500
Subject: [Tutor] Python Extension under Win 2000
In-Reply-To: <3C1F1183.69582871@gmx.de>; from m_konermann@gmx.de on Tue, Dec 18, 2001 at 10:50:59AM +0100
References: <3C1F1183.69582871@gmx.de>
Message-ID: <20011218105223.C19265@harmony.cs.rit.edu>

On Tue, Dec 18, 2001 at 10:50:59AM +0100, Marcus Konermann wrote:
| Hi @ All !
|=20
| I=B4ve created a python extension under windows2000 using developer stu=
dio
| like it is described under chapter 9 of the swig manual. I=B4ve also
| created a python shadow class and now i want to use it by importing som=
e
| methods of the simannealfile.py module  (the generated shadow class),
| but pythonwin says, that it don=B4t find the simannealfilec.py module.
| what can i do ?

Add the directory containing simannealfile.py to sys.path.

-D

--=20

He who finds a wife finds what is good
and receives favor from the Lord.
        Proverbs 18:22



From curtis.larsen@Covance.Com  Tue Dec 18 16:03:03 2001
From: curtis.larsen@Covance.Com (Curtis Larsen)
Date: Tue, 18 Dec 2001 10:03:03 -0600
Subject: [Tutor] Module Files Placement?
Message-ID: <sc1f1460.028@madis2.truax.covance.com>

Ahhh... THAT's where they go.

Thanks for the "distutils" mention too -- I haven't used it at all
heretofore, so I'll check it out.  (Hopefull it can be found on all
platforms?)  Aside from a collection of modules as an app, the thing
I've had problems with are the "onesy-twosy" types of modules/scripts
that you find and what to use -- but can't quite determine the best
place to put them.

Thanks!
Curtis

>>> Danny Yoo <dyoo@hkn.eecs.berkeley.edu> 12/18/2001 2:08:27 AM >>>
On Mon, 17 Dec 2001, Curtis Larsen wrote:

> What is the accepted standard on adding third-party modules to your
> Python installation?  (Where do you put the files?)  Even though
> pretty much anywhere in PYTHONPATH would work, there has to be a
> system of some kind (a "/usr/local/bin" if you will) to keep them
> accessible, yet separate -- including all the extra modules THEY
would
> in turn call.

External modules should live in a 'site-packages' directory underneath
Python's lib directory.

For example, on my computer, it's located here:

    /usr/local/lib/python2.1/site-packages/

Out of curiosity though: are you trying to install a module?  The
"distutils" are a set of tools to make installing new modules fairly
automatic.  Third parties often use the distutils to more easily make
an
installation script that works.


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


-----------------------------------------------------
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 jeff@ccvcorp.com  Tue Dec 18 17:34:22 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue, 18 Dec 2001 09:34:22 -0800
Subject: [Tutor] class Clowning: saving references to other instances
References: <E16GGBM-0008Ea-00@mail.python.org>
Message-ID: <3C1F7E1E.AC9A46F@ccvcorp.com>

> Rob McGee <i812@iname.com> wrote:
>
> I will try a dictionary instead of a
> list. Did you see my post about "dictionary vs. list considerations"
> after this one? I was thinking that dictionaries would take up a lot
> more memory. The one response I got indicated that speed of execution
> would probably be better with dictionaries. But I was afraid that they
> might hog a lot more memory?

Dictionaries do use a bit more memory than lists, but really, it's unlikely that
you have any reason to worry about it unless you are working with embedded
devices or some such.  On a modern (within ~5 years old) PC, you'd need to be
using *thousands* of dictionaries (or a few dictionaries with many thousands of
entries) before you'd be likely to be affected by memory constraints.  (How many
200-300 byte structures can fit in 64MB of RAM? ;) )

The better way to decide between lists and dictionaries, is to look at which fits
your problem domain better--which one makes things clearer and easier to read?
If you're accessing the data in a regular, ordered sequence, or it will be
convenient to look them up by a numeric index, then use a list.  If you want to
use some other method of looking up data, such as finding it by "name", then use
a dictionary.  In 99% of the circumstances you're likely to work in, the
performance difference will be negligible.


> ISTM if I switch to dictionaries I could use the objects themselves as
> the keys? But I don't (yet) see how that would be easier than strings as
> keys. The input will originate from the user, which of course means it
> starts out as a string. I'll have to think about it some more.

You *could* use the objects themselves as keys--*if* they are hashable.  This
means that they'd have to never mutate once they were in the dict, and  you'd
probably have to give them a __hash__() function.  It's probably a lot easier to
stick with using the strings.  :)


Jeff Shannon
Technician/Programmer
Credit International




From beazley@cs.uchicago.edu  Tue Dec 18 15:50:26 2001
From: beazley@cs.uchicago.edu (David Beazley)
Date: Tue, 18 Dec 2001 09:50:26 -0600 (CST)
Subject: [Tutor] [Swig] Python Extension under Win 2000
In-Reply-To: <3C1F1183.69582871@gmx.de>
References: <3C1F1183.69582871@gmx.de>
Message-ID: <15391.26050.264650.793350@gargoyle.cs.uchicago.edu>

Marcus Konermann writes:
 > Hi @ All !
 >=20
 > I=B4ve created a python extension under windows2000 using developer =
studio
 > like it is described under chapter 9 of the swig manual. I=B4ve also=

 > created a python shadow class and now i want to use it by importing =
some
 > methods of the simannealfile.py module  (the generated shadow class)=
,
 > but pythonwin says, that it don=B4t find the simannealfilec.py modul=
e.
 > what can i do ?
 >=20

Maybe you're not compiling things correctly.  Did you compile the SWIG
wrappers into a file 'simannealfilec.dll' as described in the SWIG
manual?                            ^
                              note: extra c added

Cheers,

Dave


From DavidCraig@pia.ca.gov  Tue Dec 18 16:13:57 2001
From: DavidCraig@pia.ca.gov (DavidCraig@pia.ca.gov)
Date: Tue, 18 Dec 2001 08:13:57 -0800
Subject: [Tutor] IndexError:list index out of range
Message-ID: <OF5A9FCC18.982CCD9C-ON88256B26.0059023E@PIA.CA.GOV>

Thanks to all.

It works on the command line just fine.  It also works on idle if I use the
reference.

Dave

D. H. Craig, CSM



From dyoo@hkn.eecs.berkeley.edu  Tue Dec 18 18:44:29 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 18 Dec 2001 10:44:29 -0800 (PST)
Subject: [Tutor] Re:  display filter slow
In-Reply-To: <20011218054041.GA3263@localhost.localdomain>
Message-ID: <Pine.LNX.4.21.0112181041440.2462-100000@hkn.eecs.berkeley.edu>

On Tue, 18 Dec 2001, Prahlad Vaidyanathan wrote:

> Hi,
> 
> On Mon, 17 Dec 2001 Prahlad Vaidyanathan spewed into the ether:
> [-- snip --]
> > As you can see, the script takes nearly thrice the amount of time as
> > without it. I'm sure there is a more efficient way of filtering my mail,
> > so any help would be appreciated.
> 
> I know replying to one's own post is a Bad Thing, but I found out on my
> own, so I thought I should post it.
> 
> The reason it was taking so long to start was that the python
> interpreter itself was taking a very long time to load. On startup,
> the interpreter tries to import a whole bunch of site-packages. All
> the packages it tried to import had a 'bad mtime' - hence it tried to
> byte-compile the .py file into the .pyc equivalent. Since I didn't
> have write-access to the /usr/lib/python2.0 directory, it complained,
> but continued nonetheless. But, the delay involved in recongising and
> reporting this problem caused the overall delay of the script.

Ah!  Put at the top of your script the following magic line:

###
#!/usr/local/bin/python -S
###

or something equivalent to this.  The important part is the '-S' part.  
Every Python script implicitely does an 'import site' for site-specific
customizations.  By using '-S', we're telling Python that we know what
we're doing, and to not do the import.

Try that, and see if your load time improves.



From dyoo@hkn.eecs.berkeley.edu  Tue Dec 18 21:30:05 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 18 Dec 2001 13:30:05 -0800 (PST)
Subject: [Tutor] Module Files Placement?
In-Reply-To: <sc1f1460.028@madis2.truax.covance.com>
Message-ID: <Pine.LNX.4.21.0112181326250.6499-100000@hkn.eecs.berkeley.edu>

On Tue, 18 Dec 2001, Curtis Larsen wrote:

> Ahhh... THAT's where they go.
> 
> Thanks for the "distutils" mention too -- I haven't used it at all
> heretofore, so I'll check it out.  (Hopefull it can be found on all
> platforms?)

Yes, 'distutils' is one of the standard library modules as of Python 1.6,
so you should already have the tools you need to automate installations
with it.  It should be cross-platform as well.  I believe one can even
make Windows installers and Red Hat RPMs with 'distutils'.

There's some good documentation on using it here:

    http://python.org/sigs/distutils-sig/doc/


Good luck!



From scott@zenplex.com  Tue Dec 18 22:18:53 2001
From: scott@zenplex.com (Scott Comboni)
Date: 18 Dec 2001 17:18:53 -0500
Subject: [Tutor] Loggin info to syslog?
In-Reply-To: <20011212175416.C10409@proton.lysator.liu.se>
References: <1008168986.1685.22.camel@scoot.zenplex.com>
 <20011212175416.C10409@proton.lysator.liu.se>
Message-ID: <1008713936.4473.246.camel@scoot.zenplex.com>

Thanks Kalle,

Scott



On Wed, 2001-12-12 at 11:54, Kalle Svensson wrote:
> [Scott Comboni]
> > Is there a simple way to log info to syslog?   
> 
> Yes, use the syslog module.  Check out
> http://www.python.org/doc/current/lib/module-syslog.html
> 
> Peace,
>   Kalle
> -- 
> Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
> English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
> Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
____________________________________________________________



From dyoo@hkn.eecs.berkeley.edu  Tue Dec 18 22:48:34 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 18 Dec 2001 14:48:34 -0800 (PST)
Subject: [Tutor] Re:  display filter slow   [pyperl and Text::Autoformat]
In-Reply-To: <20011218054041.GA3263@localhost.localdomain>
Message-ID: <Pine.LNX.4.21.0112181426460.8309-100000@hkn.eecs.berkeley.edu>

[Warning: this post mentions the use of the pyperl module; those with weak
constitution to Perl should skip this message.]






Perl actually has a very nice module called Text::Autoformat that does a
very good job at justifying messages, especially email messages.

http://search.cpan.org/doc/DCONWAY/Text-Autoformat-1.04/lib/Text/Autoformat.pm

It is one of the nicest test formatters I've ever seen.  One of its
"downsides", though, is that it's in Perl.


This shouldn't stop us from considering it, though.  It's quite possible
to use Perl modules in Python, through the really cool 'pyperl' module:

    http://downloads.activestate.com/Zope-Perl/pyperl-1.0.1.tar.gz

pyperl makes using Perl modules almost transparent from Python.  I've
written a small wrapper below to simplify the use of Text::Autoformat in
Python.


###
"""autoformat.py: A small Python wrapper class for Perl's Text::Autoformat
module. This uses pyperl.

Example use:

    import autoformat
    rawtext = '''Hello world, this is a test of the emergency broadcast
    system.  This is only a test.  muahahahahaha
    this is quite neat.'''
    ## A simple call using all defaults.
    formatted = autoformat(rawtext)
    ## Calls that override the defaults with some options.
    formatted = autoformat(rawtext, left=8, right=70)
    formatted = autoformat(rawtext, justify='right')
"""

import perl
perl.eval("use Text::Autoformat;")

def autoformat(mystring, **kwargs):
    kwarg_ref = perl.get_ref('%')
    kwarg_ref.update(kwargs)
    return perl.call("autoformat", mystring, kwarg_ref)
###



Here's a sample session that uses this wrapper:

###
>>> sample_msg = """> On Mon, 17 Dec 2001 Prahlad Vaidyanathan spewed into
the ether:
> [-- snip --]
> > As you can see, the script takes nearly thrice the amount of time as
> > without it. I'm sure there is a more efficient way of filtering my
mail,
> > so any help would be appreciated."""
>>> print autoformat(sample_msg, left=8, right=60, all=1)
       > On Mon, 17 Dec 2001 Prahlad Vaidyanathan spewed
       > into the ether: [-- snip --]
       > > As you can see, the script takes nearly thrice
       > > the amount of time as without it. I'm sure there
       > > is a more efficient way of filtering my mail, so
       > > any help would be appreciated.
###


I thought this was pretty darn neat.  *grin*  Hope this helps!



From pythonpython@hotmail.com  Wed Dec 19 01:27:08 2001
From: pythonpython@hotmail.com (HY)
Date: Wed, 19 Dec 2001 10:27:08 +0900
Subject: [Tutor] Python record delimiter / record separator
Message-ID: <OE26xSkjtPahT2kopUb00003953@hotmail.com>

Is there a way to set a record delimiter in Python you while reading in a
file?
(Like $/ in Perl)


Thanks a lot.


Hy


From deliberatus@my995internet.com  Wed Dec 19 04:35:33 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Tue, 18 Dec 2001 23:35:33 -0500
Subject: [Tutor] TLpost.py listing now on line
Message-ID: <3C201915.FB2AE6F1@my995internet.com>

Rather than bore the unintrested, I have built a page with the power of
SSI which lists the actual RIGHT THIS MOMENT version of TLpost.py
sitting in the server.

Just click this link and you will see that page.

http://www.howlermonkey.net/TLpost.shtml

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From inkedmn@gmx.net  Wed Dec 19 04:31:18 2001
From: inkedmn@gmx.net (Brett Kelly)
Date: Wed, 19 Dec 2001 05:31:18 +0100 (MET)
Subject: [Tutor] while loop only executes once
Message-ID: <16571.1008736278@www39.gmx.net>

ok, here's my loop.  it only goes through once and exits.
(words is a dictionary with each letter of the alphabet corresponding to a
different word)

name = raw_input("Please enter your name: ")
name.lower()

for i in range(0, len(name)):
    letter = name[i]    

while len(name) > 0:
    print words[letter]
name[i] = name[1:] 


i can't figure this out!!!

please help, thanks!

Brett

-- 
Sent through GMX FreeMail - http://www.gmx.net



From lha2@columbia.edu  Wed Dec 19 10:43:49 2001
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Wed, 19 Dec 2001 05:43:49 -0500
Subject: [Tutor] while loop only executes once
References: <16571.1008736278@www39.gmx.net>
Message-ID: <3C206F64.EEACFB9E@mail.verizon.net>

Brett Kelly wrote:
> 
> ok, here's my loop.  it only goes through once and exits.
> (words is a dictionary with each letter of the alphabet corresponding to a
> different word)
> 
> name = raw_input("Please enter your name: ")
> name.lower()
> 
> for i in range(0, len(name)):
>     letter = name[i]
> 
> while len(name) > 0:
>     print words[letter]
> name[i] = name[1:]
> 
> i can't figure this out!!!
> 
> please help, thanks!
> 
> Brett
> 
> --
> Sent through GMX FreeMail - http://www.gmx.net
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

*name is not being changed within the while loop. If you want it to be,
indent name[i]=name[1:]

*except that name is currently a string. Strings don't like it when you
assign a slice to a character in the string (or when you assign anything
to a character in the string).

Is this what you want? I don't know what kind of output you are looking
for, and couldn't figure out what the for loop was supposed to do.

----begin code below this line-----

words = {'a':'foo', 'b':'foo2', 'c':'foo3'}

name = raw_input("Please enter your name: ")
name.lower()



while len(name) > 0:
    print words[name[0]]
    name = name[1:]

----end code above this line------

----begin output------
Please enter your name: abc
foo
foo2
foo3
----end output--------

I have a feeling that your troubles come from using two separated loops
when one will do, or from not nesting your loops if you want them to
interact with each other. A for loop is probably a better choice for the
above output, along the lines of

for letter in name:
    print words[letter]

(which is probably easier to understand than the double-indexed stuff in
the while loop above).


From toodles@yifan.net  Wed Dec 19 10:53:29 2001
From: toodles@yifan.net (Andy W)
Date: Wed, 19 Dec 2001 18:53:29 +0800
Subject: [Tutor] Python record delimiter / record separator
References: <OE26xSkjtPahT2kopUb00003953@hotmail.com>
Message-ID: <003301c1887b$66d87020$0300a8c0@sun>

Hi Hy,


> Is there a way to set a record delimiter in Python you while reading in a
> file?
> (Like $/ in Perl)

(n.b. I've never used Perl, I hope I'm understanding the question correctly)

Not as far as I know. You can just read in the data and split it, though.
ie.:-

my_file=open("the_file.extension")
data=my_file.read()
records=data.split(delimiter)

>
>
> Thanks a lot.
>
>
> Hy

No worries, hope this helps!

Andy

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



From toodles@yifan.net  Wed Dec 19 11:14:46 2001
From: toodles@yifan.net (Andy W)
Date: Wed, 19 Dec 2001 19:14:46 +0800
Subject: [Tutor] while loop only executes once
References: <16571.1008736278@www39.gmx.net> <3C206F64.EEACFB9E@mail.verizon.net>
Message-ID: <004701c1887e$6111ae10$0300a8c0@sun>

> Brett Kelly wrote:
> >
> > ok, here's my loop.  it only goes through once and exits.
> > (words is a dictionary with each letter of the alphabet corresponding to
a
> > different word)
> >
> > name = raw_input("Please enter your name: ")
> > name.lower()

Also here, this doesn't assign the lowered string to name.
Change it to

name=name.lower()

<snip/>

>
> I have a feeling that your troubles come from using two separated loops
> when one will do, or from not nesting your loops if you want them to
> interact with each other. A for loop is probably a better choice for the
> above output, along the lines of
>
> for letter in name:
>     print words[letter]
>
> (which is probably easier to understand than the double-indexed stuff in
> the while loop above).

I'd have to agree with that. Just remember that lower() bit, though! :)

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



From thejoness3@attbi.com  Tue Dec 18 02:07:51 2001
From: thejoness3@attbi.com (Jeff Jones)
Date: Mon, 17 Dec 2001 21:07:51 -0500
Subject: [Tutor] IDLE in linux
References: <XFMail.20011217155154.shalehperry@attbi.com>
Message-ID: <000001c188a8$dbc9c000$141af50c@attbi.com>

Well, thanks to the help of many fine python tutor mail list subscribers,
especially Rob for his help off list, I was finally able to properly install
and configure Slackware, X, and Gnome. I thought it fitting that Python be
the first program I compile with my new Linux wings, and everything went
great except I cannot use IDLE. I went into
/usr/local/Python2.2c1/Tools/idle and the idle command is there, but when I
try to run it from bash I get "command not found". I tried to run it in X
and out. I also tried at python command line without success. Thanks in
advance for any assistance. I hope this is within the scope of the e-mail
list...




From alan.gauld@bt.com  Wed Dec 19 17:51:33 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 19 Dec 2001 17:51:33 -0000
Subject: [Tutor] IDLE in linux
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1E6@mbtlipnt02.btlabs.bt.co.uk>

> and configure Slackware, X, and Gnome. 

Well done!

> great except I cannot use IDLE. 

Assuming you built IDLE with Tkinter support built in....


> /usr/local/Python2.2c1/Tools/idle and the idle command is 
> there, but when I try to run it from bash I 
> get "command not found". 

How exactly did you try to run IDLE?

$ python idle.py

Should do it if you are in the same directory as idle.py

> run it in X

Yes you will need X running.

> I also tried at python command line without success. 

That probably won't work, your best to use the Bash prompt.

You could create an alias for bash:

alias idle='python <your idle path here>/idle.py'

Or a link to the idle.py file from GNOME if the association 
of .py and python is set up.

Alan G.


From dvass@felis.uni-freiburg.de  Wed Dec 19 18:33:00 2001
From: dvass@felis.uni-freiburg.de (Joerg Woelke)
Date: Wed, 19 Dec 2001 19:33:00 +0100
Subject: [Tutor] IDLE in linux
In-Reply-To: <000001c188a8$dbc9c000$141af50c@attbi.com>; from thejoness3@attbi.com on Mon, Dec 17, 2001 at 09:07:51PM -0500
References: <XFMail.20011217155154.shalehperry@attbi.com> <000001c188a8$dbc9c000$141af50c@attbi.com>
Message-ID: <20011219193300.A749@Laplace.localdomain>

On Mon, Dec 17, 2001 at 09:07:51PM -0500, Jeff Jones wrote:
> Well, thanks to the help of many fine python tutor mail list subscribers,
> especially Rob for his help off list, I was finally able to properly install
> and configure Slackware, X, and Gnome. I thought it fitting that Python be
> the first program I compile with my new Linux wings, and everything went
> great except I cannot use IDLE. I went into
> /usr/local/Python2.2c1/Tools/idle and the idle command is there, but when I
> try to run it from bash I get "command not found". 

try "./idle" in that directory

> and out. I also tried at python command line without success. Thanks in
> advance for any assistance. I hope this is within the scope of the e-mail
> list...
> 

HTH,HAND 
and Greetings J"o!

-- 
There's a way out of any cage.
		-- Captain Christopher Pike, "The Menagerie" ("The Cage"),
		   stardate unknown.


From Bruce.Lee-Shanok@cognos.com  Wed Dec 19 20:54:47 2001
From: Bruce.Lee-Shanok@cognos.com (Lee-Shanok, Bruce)
Date: Wed, 19 Dec 2001 15:54:47 -0500
Subject: [Tutor] Unsigned numerical literals?
Message-ID: <FB15E670DA55D51185350008C786514A0140EBAD@sottexch1.cognos.com>

Hello all. Quick question: I'm writing a wrapper for some C calls in Python.
The issue here is that the C code takes an unsigned long. Now, Python
integers are, to the best of my understanding, also 32 bit, but not unsigned
by default. Is there a clean way to force them to be unsigned? I'd hate to
have to force the users of the Python code to write an "L" at the end of
every value they bring in....

Cheers,
Bruce



This message may contain privileged and/or confidential information.  If you
have received this e-mail in error or are not the intended recipient, you
may not use, copy, disseminate, or distribute it; do not open any
attachments, delete it immediately from your system and notify the sender by
e-mail promptly that you have done so.  Thank You.


From thejoness3@attbi.com  Wed Dec 19 21:11:46 2001
From: thejoness3@attbi.com (Jeff Jones)
Date: Wed, 19 Dec 2001 16:11:46 -0500
Subject: [Tutor] IDLE in linux
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1E6@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <001501c188d1$c4d1a2e0$141af50c@attbi.com>

I tried ./idle but got this error (retyped from linux to outlook):

Traceback (most recent call last):
  File "./idle", line 5, in ?
     from idlelib import idleconf
ImportError: No module IdleConf

Thanks for all your help! I know I have seen people ask similar ?'s. Is
there an archive of this list somewhere?
----- Original Message -----
From: <alan.gauld@bt.com>
To: <thejoness3@attbi.com>; <tutor@python.org>
Sent: Wednesday, December 19, 2001 12:51 PM
Subject: RE: [Tutor] IDLE in linux


> > and configure Slackware, X, and Gnome.
>
> Well done!
>
> > great except I cannot use IDLE.
>
> Assuming you built IDLE with Tkinter support built in....
>
>
> > /usr/local/Python2.2c1/Tools/idle and the idle command is
> > there, but when I try to run it from bash I
> > get "command not found".
>
> How exactly did you try to run IDLE?
>
> $ python idle.py
>
> Should do it if you are in the same directory as idle.py
>
> > run it in X
>
> Yes you will need X running.
>
> > I also tried at python command line without success.
>
> That probably won't work, your best to use the Bash prompt.
>
> You could create an alias for bash:
>
> alias idle='python <your idle path here>/idle.py'
>
> Or a link to the idle.py file from GNOME if the association
> of .py and python is set up.
>
> Alan G.
>



From arcege@speakeasy.net  Wed Dec 19 23:43:16 2001
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Wed, 19 Dec 2001 18:43:16 -0500
Subject: [Tutor] IDLE in linux
In-Reply-To: <000001c188a8$dbc9c000$141af50c@attbi.com>; from thejoness3@attbi.com on Mon, Dec 17, 2001 at 09:07:51PM -0500
References: <XFMail.20011217155154.shalehperry@attbi.com> <000001c188a8$dbc9c000$141af50c@attbi.com>
Message-ID: <20011219184316.E907@speakeasy.net>

On Mon, Dec 17, 2001 at 09:07:51PM -0500, Jeff Jones wrote:
> Well, thanks to the help of many fine python tutor mail list subscribers,
> especially Rob for his help off list, I was finally able to properly install
> and configure Slackware, X, and Gnome. I thought it fitting that Python be
> the first program I compile with my new Linux wings, and everything went
> great except I cannot use IDLE. I went into
> /usr/local/Python2.2c1/Tools/idle and the idle command is there, but when I
> try to run it from bash I get "command not found". I tried to run it in X
> and out. I also tried at python command line without success. Thanks in
> advance for any assistance. I hope this is within the scope of the e-mail
> list...

You might want to check the "shebang" line (first line in the file)
to make sure the pathname of the interpreter in
  #!/path/to/interpreter

is correct (sometimes it is /usr/local/bin/python when it is really
in /usr/bin/python or /usr/local/bin/python2).

  -Arcege



From glingl@aon.at  Thu Dec 20 00:35:18 2001
From: glingl@aon.at (Gregor Lingl)
Date: Thu, 20 Dec 2001 01:35:18 +0100
Subject: [Tutor] Unsigned numerical literals?
References: <FB15E670DA55D51185350008C786514A0140EBAD@sottexch1.cognos.com>
Message-ID: <005b01c188ee$332f81f0$1664a8c0@mega>

----- Original Message -----
From: "Lee-Shanok, Bruce" <Bruce.Lee-Shanok@cognos.com>
To: <tutor@python.org>
Sent: Wednesday, December 19, 2001 9:54 PM
Subject: [Tutor] Unsigned numerical literals?


> Hello all. Quick question: I'm writing a wrapper for some C calls in
Python.
> The issue here is that the C code takes an unsigned long. Now, Python
> integers are, to the best of my understanding, also 32 bit, but not
unsigned
> by default. Is there a clean way to force them to be unsigned? I'd hate to
> have to force the users of the Python code to write an "L" at the end of
> every value they bring in....
>

This would only make sense if you used the input-statement:

If you tried:

>>> a = input("any integer: ")
any integer: 123412312341234
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in ?
    a = input("any integer: ")
OverflowError: integer literal too large
>>>

To avoid this, use raw_input:

>>> a = long(raw_input("any integer: "))
any integer: 123412341234
>>> a
123412341234L
>>>

thus reading in a string and converting it immediately to a float.

Gregor

P.S.: Since the day after tomorrow you will get with Python V 2.2:

Python 2.2c1 (#27, Dec 14 2001, 13:15:16) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> a = input("any integer: ")
any integer: 123412312341234
>>> a
123412312341234L
>>>

Python V2.2 will do the conversion int=>long automatically

P.P.S.: Perhaps - depending on your application - it would be better
to use:

>>> try:
 a = long(raw_input("any integer: "))
except: # if something weird was input
 print "Nonsense!"


any integer: 123412312341234xyz
Nonsense!
>>>

... to catch unplausible userinput.


> Cheers,
> Bruce
>




From glingl@aon.at  Thu Dec 20 00:41:56 2001
From: glingl@aon.at (Gregor Lingl)
Date: Thu, 20 Dec 2001 01:41:56 +0100
Subject: Fw: [Tutor] Unsigned numerical literals?
Message-ID: <007901c188ef$2043a570$1664a8c0@mega>

In my last posting, this should read:

> To avoid this, use raw_input:
>
> >>> a = long(raw_input("any integer: "))
> any integer: 123412312341234
> >>> a
> 123412312341234L
> >>>
>
> thus reading in a string and converting it immediately to a long.
                                                              ^^^^
                               (It' already too late here in good old
Europe)

Gregor



From slime@vsnl.net  Wed Dec 19 17:32:49 2001
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Wed, 19 Dec 2001 23:02:49 +0530
Subject: [Tutor] Re:  display filter slow   [pyperl and Text::Autoformat]
In-Reply-To: <Pine.LNX.4.21.0112181426460.8309-100000@hkn.eecs.berkeley.edu>
References: <20011218054041.GA3263@localhost.localdomain> <Pine.LNX.4.21.0112181426460.8309-100000@hkn.eecs.berkeley.edu>
Message-ID: <20011219173249.GA2790@localhost.localdomain>

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

Hi,

On Tue, 18 Dec 2001 Danny Yoo spewed into the ether:
[-- snip --]
>     http://downloads.activestate.com/Zope-Perl/pyperl-1.0.1.tar.gz

Thanks a lot ! Now to get cracking ...

pv.

--=20
Prahlad Vaidyanathan <slime@vsnl.net>
	Make sure your code does nothing gracefully.

--bp/iNruPH9dso1Pn
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

iD8DBQE8IM9BIKhjOSElu4YRAk13AKC0KaTOt8DQW1G+SUTvMdDRqG0pWACfTuHc
aok3m0WsIAqJpT3778+jGlw=
=RjHz
-----END PGP SIGNATURE-----

--bp/iNruPH9dso1Pn--


From rufmetal@rogers.com  Thu Dec 20 04:17:30 2001
From: rufmetal@rogers.com (Chris Keelan)
Date: Wed, 19 Dec 2001 23:17:30 -0500
Subject: [Tutor] Passing a variable to 'import'
Message-ID: <20011220043209.JBYO42229.fep01-mail.bloor.is.net.cable.rogers.com@there>

I have a piece of code like so:

moduleName="someModule"

def import_module(someModule):
	import someModule

Of course that gives me the following output:

Traceback (most recent call last):
  File "<stdin>", line 1, in import_module
ImportError: No module named moduleName

So how do I, for example, grab a module name from sys.argv and then pass it 
to the import command as a variable?

- Chris


From rufmetal@rogers.com  Thu Dec 20 04:26:01 2001
From: rufmetal@rogers.com (Chris Keelan)
Date: Wed, 19 Dec 2001 23:26:01 -0500
Subject: [Tutor] Passing a variable to 'import'
In-Reply-To: <20011220043209.JBYO42229.fep01-mail.bloor.is.net.cable.rogers.com@there>
References: <20011220043209.JBYO42229.fep01-mail.bloor.is.net.cable.rogers.com@there>
Message-ID: <20011220044040.SXXM342755.fep04-mail.bloor.is.net.cable.rogers.com@there>

On Wednesday 19 December 2001 11:17 pm, Chris Keelan wrote:

Dang it! I should proof my messages.

Try it this way:

I have a piece of code like so:

>>moduleName="someModule"

>>def import_module(someModule):
        import someModule

Of course that gives me the following output:

>>Traceback (most recent call last):
>>  File "<stdin>", line 1, in import_module
>>ImportError: No module named someModule

But you all knew what I meant, right?

- Chris


From deliberatus@my995internet.com  Thu Dec 20 05:01:19 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Thu, 20 Dec 2001 00:01:19 -0500
Subject: [Tutor] COMPIMER QUEST
Message-ID: <3C21709F.95031F9F@my995internet.com>

SHOWINg the TLpost.py code to Jim Porter, he wants to know if there is a
compiler out there toconvert python to C, or compile machine language
files from python.

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From i812@iname.com  Thu Dec 20 05:37:23 2001
From: i812@iname.com (Rob McGee)
Date: Wed, 19 Dec 2001 23:37:23 -0600
Subject: [Tutor] Passing a variable to 'import'
In-Reply-To: <20011220044040.SXXM342755.fep04-mail.bloor.is.net.cable.rogers.com@there>; from rufmetal@rogers.com on Wed, Dec 19, 2001 at 11:26:01PM -0500
References: <20011220043209.JBYO42229.fep01-mail.bloor.is.net.cable.rogers.com@there> <20011220044040.SXXM342755.fep04-mail.bloor.is.net.cable.rogers.com@there>
Message-ID: <20011219233723.E3310@hal>

On Wed, Dec 19, 2001 at 11:26:01PM -0500, Chris Keelan wrote:
> >>moduleName="someModule"
> 
> >>def import_module(someModule):
>         import someModule
> 
> Of course that gives me the following output:
> 
> >>Traceback (most recent call last):
> >>  File "<stdin>", line 1, in import_module
> >>ImportError: No module named someModule

Sounds like a job for my once-beloved "exec" statement. :)

{code}
moduleName = 'someModule'

def import_module(someModule):
  """Imports a module (someModule as string)"""
  exec 'import ' + someModule

import_module(moduleName)
{/code}

But don't listen to me, I'm a beginner. :) IIRC there's also the
execfile() function which might do it more elegantly. See the
lib/built-in-funcs.html in your documentation (or online at
www.python.org/doc/).

HTH, sorry if it doesn't :) ...
    Rob - /dev/rob0


From toodles@yifan.net  Thu Dec 20 05:43:27 2001
From: toodles@yifan.net (Andy W)
Date: Thu, 20 Dec 2001 13:43:27 +0800
Subject: [Tutor] min() & mutable sequences
Message-ID: <000501c18919$40fe2630$0300a8c0@sun>

Hi people,

First to give some background: I have a list of instances, each has an
attributes "distance". I want to get the instance with the smallest
distance.

I have at present:-

robots=[...] #The ... is a whole lot of instances :)
closest=min([robot.distance for robot in robots])

Okay, I now have the closest *distance*.
Say more than one instance has the same distance, will min() return the
first instance with that smallest distance? Because if that is so, I could
then just get the related instance using:-

closest_index=[robot.distance for robot in robots].index(closest)
#Yeah, I used that list comprehension twice, this is just for demonstration,
though.
closest_robot=robots[closest_index]

Is there a better way to do it?

I guess I could iterate over the list, and keep a smallest distance variable
somewhere. I guess I've become somewhat of a list-comprehension-addict
*grin*

TIA,
Andrew



From toodles@yifan.net  Thu Dec 20 05:51:16 2001
From: toodles@yifan.net (Andy W)
Date: Thu, 20 Dec 2001 13:51:16 +0800
Subject: [Tutor] Passing a variable to 'import'
References: <20011220043209.JBYO42229.fep01-mail.bloor.is.net.cable.rogers.com@there>
Message-ID: <002f01c1891a$58aa8610$0300a8c0@sun>

Hi Christ

> So how do I, for example, grab a module name from sys.argv and then pass
it
> to the import command as a variable?
>
> - Chris

You'll want to look at the "imp" module.

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

Also, take a look at the example for the imp module.

http://www.python.org/doc/current/lib/examples-imp.html

HTH,
Andrew

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



From toodles@yifan.net  Thu Dec 20 05:58:22 2001
From: toodles@yifan.net (Andy W)
Date: Thu, 20 Dec 2001 13:58:22 +0800
Subject: [Tutor] COMPIMER QUEST
References: <3C21709F.95031F9F@my995internet.com>
Message-ID: <003701c1891b$568c4480$0300a8c0@sun>

Hiya,

> SHOWINg the TLpost.py code to Jim Porter, he wants to know if there is a
> compiler out there toconvert python to C, or compile machine language
> files from python.

Hmm there might be a couple of projects going on for C
conversion/compilation, but I don't know how well they work (especially with
exec calls and such things...)

There are a few packages around that create executables, that take the
python code, analyse what the dependencies are and glue a minimalistic
python interpreter to it.
Of these, I have tried and found Gordon McMillan's "installer" package to be
useful.
http://www.mcmillan-inc.com/install5_ann.html

There's also py2exe, http://starship.python.net/crew/theller/py2exe/

HTH,
Andrew

>
> --
> Respectfully,
>              -Kirk D Bailey (C)2001
>               Addme! icq #27840081
> end
>
>
> Within the sweep of his sword, Each man is an Ubar.
>
> http://www.howlermonkey.net/
> http://www.sacredelectron.org/
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From toodles@yifan.net  Thu Dec 20 06:00:07 2001
From: toodles@yifan.net (Andy W)
Date: Thu, 20 Dec 2001 14:00:07 +0800
Subject: [Tutor] Passing a variable to 'import'
References: <20011220043209.JBYO42229.fep01-mail.bloor.is.net.cable.rogers.com@there> <002f01c1891a$58aa8610$0300a8c0@sun>
Message-ID: <004101c1891b$953a9010$0300a8c0@sun>

> Hi Christ

Oh dear, that's got to be the best typo I've ever done.

>
> > So how do I, for example, grab a module name from sys.argv and then pass
> it
> > to the import command as a variable?
> >
> > - Chris
>
> You'll want to look at the "imp" module.
>
> http://www.python.org/doc/current/lib/module-imp.html
>
> Also, take a look at the example for the imp module.
>
> http://www.python.org/doc/current/lib/examples-imp.html
>
> HTH,
> Andrew
>
> >
> > _______________________________________________
> > 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 mark21rowe@yahoo.com  Thu Dec 20 06:11:34 2001
From: mark21rowe@yahoo.com (Mark Rowe)
Date: Thu, 20 Dec 2001 19:11:34 +1300
Subject: [Tutor] Passing a variable to 'import'
References: <20011220043209.JBYO42229.fep01-mail.bloor.is.net.cable.rogers.com@there>
Message-ID: <3C218116.10500@yahoo.com>

Hi,

Have a read up on the __import__ function in the Python documentation.

Mark Rowe


Chris Keelan wrote:

>I have a piece of code like so:
>
>moduleName="someModule"
>
>def import_module(someModule):
>	import someModule
>
>Of course that gives me the following output:
>
>Traceback (most recent call last):
>  File "<stdin>", line 1, in import_module
>ImportError: No module named moduleName
>
>So how do I, for example, grab a module name from sys.argv and then pass it 
>to the import command as a variable?
>
>- Chris
>


_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com



From i812@iname.com  Thu Dec 20 06:14:53 2001
From: i812@iname.com (Rob McGee)
Date: Thu, 20 Dec 2001 00:14:53 -0600
Subject: [Tutor] initializing multiple attributes to same value
Message-ID: <20011220001453.F3310@hal>

I tripped myself up on something like this:

{code}
class Whatever:
  def __init__(self):
    self.one = self.two = self.three = 0
    self.listOne = self.listTwo = []

whoKnows = Whatever()

someOtherObject = ['spam', 'eggs']

whoKnows.listOne.append(someOtherObject)
{/code}

With that I also end up with someOtherObject in whoKnows.listTwo.
Presumably if I add 42 to whoKnows.one, I also add 42 to the values for
two and three attributes. Is that right?

So, how do I initialize multiple attributes to the same value? Would
something like this ...

{code}
class Whatever:
  def __init__(self):
    list1 = self.one, self.two, self.three
    for item in list1:
      item = 0
    list2 = self.listOne, self.listTwo
    for item in list2:
      item = []
{/code}

... keep these attributes' values distinct from one another?

Thanks,
    Rob - /dev/rob0


From toodles@yifan.net  Thu Dec 20 06:33:43 2001
From: toodles@yifan.net (Andy W)
Date: Thu, 20 Dec 2001 14:33:43 +0800
Subject: [Tutor] initializing multiple attributes to same value
References: <20011220001453.F3310@hal>
Message-ID: <000b01c18920$46a60a10$0300a8c0@sun>

Hiya,
(Answer is right down the bottom)

> I tripped myself up on something like this:
>
> {code}
> class Whatever:
>   def __init__(self):
>     self.one = self.two = self.three = 0
>     self.listOne = self.listTwo = []
>
> whoKnows = Whatever()
>
> someOtherObject = ['spam', 'eggs']
>
> whoKnows.listOne.append(someOtherObject)
> {/code}
>
> With that I also end up with someOtherObject in whoKnows.listTwo.
> Presumably if I add 42 to whoKnows.one, I also add 42 to the values for
> two and three attributes. Is that right?
>
> So, how do I initialize multiple attributes to the same value? Would
> something like this ...
>
> {code}
> class Whatever:
>   def __init__(self):
>     list1 = self.one, self.two, self.three
>     for item in list1:
>       item = 0
>     list2 = self.listOne, self.listTwo
>     for item in list2:
>       item = []
> {/code}
>
> ... keep these attributes' values distinct from one another?

Well, no. That would be referring to variables not yet assigned. You could
use a dictionary if you wanted to do it that way, with the keys as "one",
"two", "three" etc.

Another way is to use sequence unpacking, eg.:-

self.one, self.two, self.three = (0,0,0)

HTH,
Andrew

>
> Thanks,
>     Rob - /dev/rob0
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From alan.gauld@bt.com  Thu Dec 20 10:49:53 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 20 Dec 2001 10:49:53 -0000
Subject: [Tutor] Passing a variable to 'import'
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1EA@mbtlipnt02.btlabs.bt.co.uk>

> > >>moduleName="someModule"
> > 
> > >>def import_module(someModule):
> >         import someModule
> 
> Sounds like a job for my once-beloved "exec" statement. :)

Rob, this time I agree with you :-)

I think there may be other ways to do this using some of 
the internals of Python but in this case exec does seem 
the best option.

Alan G.



From alan.gauld@bt.com  Thu Dec 20 10:53:23 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 20 Dec 2001 10:53:23 -0000
Subject: [Tutor] Passing a variable to 'import'
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1EB@mbtlipnt02.btlabs.bt.co.uk>

> > So how do I, for example, grab a module name from sys.argv 
> and then pass it to the import command as a variable?
> 
> You'll want to look at the "imp" module.
> 
> http://www.python.org/doc/current/lib/module-imp.html
> 

Oh well, wrong again! exec isn't the best way 
- once more Python's "battery power" impresses me :-)

Alan g.


From lonetwin@yahoo.com  Thu Dec 20 11:43:59 2001
From: lonetwin@yahoo.com (lonetwin)
Date: Thu, 20 Dec 2001 17:13:59 +0530
Subject: [Tutor] printing out the definition of a func ++
Message-ID: <01122017135901.05475@mercury.worli>

Hi everybody,
     A quick question, can I print out the definition of a func/class *after* 
I have defined it, in the python intepreter ??? ....it'd be nice to be able 
to do this 'cos I seem to need it pretty often (for debugging stuff)....and 
no, I do not use IDLE, 'cos I work at command prompt (under linux) and 
fire-up the intepreter there (X *crawls* on my system).

In other words, I want to:
===================================================
[steve@mercury ~]$ python
Python 2.0 (#1, Apr 11 2001, 19:18:08) 
[GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux-i386
Type "copyright", "credits" or "license" for more information.
>>> def func(foo):
            .......
            .......
            .......
>>> doStuff()
>>> doSomeMore()
>>> ........
>>> ........
<at this point the definition of func() has scrolled up>
>>> print code(func) <----- Could someone prolly show me how to write
                                                      this function ???
def func(foo):           /
    ..........                   {-------- This is what should happen...sorry 
    ...........                   \                 I forgot mentioning this
===================================================
.....or am I asking for too much ??

Peace
Steve
-- 
----------------------------------------------
I get up each morning, gather my wits.
Pick up the paper, read the obits.
If I'm not there I know I'm not dead.
So I eat a good breakfast and go back to bed.

Oh, how do I know my youth is all spent?
My get-up-and-go has got-up-and-went.
But in spite of it all, I'm able to grin,
And think of the places my get-up has been.
                -- Pete Seeger
----------------------------------------------


From glingl@aon.at  Thu Dec 20 12:03:35 2001
From: glingl@aon.at (Gregor Lingl)
Date: Thu, 20 Dec 2001 13:03:35 +0100
Subject: [Tutor] Passing a variable to 'import'
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1EA@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3C21D397.9E9CA1A2@rg16.asn-wien.ac.at>


alan.gauld@bt.com schrieb:

> > > >>moduleName="someModule"
> > >
> > > >>def import_module(someModule):
> > >         import someModule
> >
> > Sounds like a job for my once-beloved "exec" statement. :)
>
> Rob, this time I agree with you :-)
>
> I think there may be other ways to do this using some of
> the internals of Python but in this case exec does seem
> the best option.
>

I think, this is not the case, because of the same reason, why
the following doesn't work properly ().

>>> def pival():
      import math
      return math.pi

>>> pival()
3.1415926535897931
>>> math.pi
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in ?
    math.pi
NameError: name 'math' is not defined
>>>

(Apparently the module math is only
imported locally (to the function-body))

Similarly we have:

>>> def import_module(someModule):
      """Imports a module (someModule as string)"""
      exec 'import ' + someModule


>>> import_module('math')
>>> math.pi
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in ?
    math.pi
NameError: name 'math' is not defined

I assume that the definer of the import_module()
function wants the module to be imported to the
'namespace' (?) from which the function is
called.
Otherwise such a function would not make much
sense. (Or am I wrong?)

Gregor




From alan.gauld@bt.com  Thu Dec 20 12:15:00 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 20 Dec 2001 12:15:00 -0000
Subject: [Tutor] Passing a variable to 'import'
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1ED@mbtlipnt02.btlabs.bt.co.uk>

> I assume that the definer of the import_module()
> function wants the module to be imported to the
> 'namespace' (?) from which the function is
> called.

Maybe, I assumed(*) it was just for local consumption.
However as someone already pointed out the imp module 
looks a lot better for this.

Alan G.

(*) Assume = Ass + U + me :-)



From jrm@videotron.ca  Thu Dec 20 06:21:29 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Thu, 20 Dec 2001 08:21:29 +0200
Subject: [Tutor] COMPIMER QUEST
References: <3C21709F.95031F9F@my995internet.com> <003701c1891b$568c4480$0300a8c0@sun>
Message-ID: <000701c1891e$9008bb00$0100c0a8@videotron.ca>

----- Original Message -----
From: "Andy W" <toodles@yifan.net>
To: "Kirk Bailey" <deliberatus@my995internet.com>; <tutor@python.org>

> Hmm there might be a couple of projects going on for C
> conversion/compilation, but I don't know how well they work (especially
with
> exec calls and such things...)

One such project :
    http://homepages.ulb.ac.be/~arigo/psyco/



From lonetwin@yahoo.com  Thu Dec 20 11:38:41 2001
From: lonetwin@yahoo.com (lonetwin)
Date: Thu, 20 Dec 2001 17:08:41 +0530
Subject: [Tutor] printing out the definition of a func
Message-ID: <01122017084100.05475@mercury.worli>

Hi everybody,
     A quick question, can I print out the definition of a func/class *after* 
I have defined it, in the python intepreter ??? ....it'd be nice to be able 
to do this 'cos I seem to need it pretty often (for debugging stuff)....and 
no, I do not use IDLE, 'cos I work at command prompt (under linux) and 
fire-up the intepreter there (X *crawls* on my system).

In other words, I want to:
===================================================
[steve@mercury ~]$ python
Python 2.0 (#1, Apr 11 2001, 19:18:08) 
[GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux-i386
Type "copyright", "credits" or "license" for more information.
>>> def func(foo):
            .......
            .......
            .......
>>> doStuff()
>>> doSomeMore()
>>> ........
>>> ........
<at this point the definition of func() has scrolled up>
>>> print code(func) <----------- Could someone prolly show me how to write
                                                             this function ???
===================================================
.....or am I asking for too much ??

Peace
Steve
-- 
----------------------------------------------
I get up each morning, gather my wits.
Pick up the paper, read the obits.
If I'm not there I know I'm not dead.
So I eat a good breakfast and go back to bed.

Oh, how do I know my youth is all spent?
My get-up-and-go has got-up-and-went.
But in spite of it all, I'm able to grin,
And think of the places my get-up has been.
                -- Pete Seeger
----------------------------------------------


From pythontutor@venix.com  Thu Dec 20 13:56:01 2001
From: pythontutor@venix.com (Lloyd Kvam)
Date: Thu, 20 Dec 2001 08:56:01 -0500
Subject: [Tutor] printing out the definition of a func
References: <01122017084100.05475@mercury.worli>
Message-ID: <3C21EDF1.7010209@venix.com>

I am pretty sure that you are asking too much.  Even in text mode,
you should be able to switch between different sessions.  Keep one
session in your editor window where the source file is visible.
Then have a Python session.  Use:
import FILENAME		- the first time
reload(FILENAME) 
- later times
to get the latest changes from the source file.  Rember to save to
the disk from your editor.

So far as I know, all Linux distributions use <Alt-FunctionKey> to
switch between sessions.

lonetwin wrote:

> Hi everybody,
>      A quick question, can I print out the definition of a func/class *after* 
> I have defined it, in the python intepreter ??? ....it'd be nice to be able 
> to do this 'cos I seem to need it pretty often (for debugging stuff)....and 
> no, I do not use IDLE, 'cos I work at command prompt (under linux) and 
> fire-up the intepreter there (X *crawls* on my system).
> 
> In other words, I want to:
> ===================================================
> [steve@mercury ~]$ python
> Python 2.0 (#1, Apr 11 2001, 19:18:08) 
> [GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux-i386
> Type "copyright", "credits" or "license" for more information.
> 
>>>>def func(foo):
>>>>
>             .......
>             .......
>             .......
> 
>>>>doStuff()
>>>>doSomeMore()
>>>>........
>>>>........
>>>>
> <at this point the definition of func() has scrolled up>
> 
>>>>print code(func) <----------- Could someone prolly show me how to write
>>>>
>                                                              this function ???
> ===================================================
> .....or am I asking for too much ??
> 
> Peace
> Steve
> 


-- 
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  Thu Dec 20 18:20:36 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 20 Dec 2001 18:20:36 -0000
Subject: [Tutor] printing out the definition of a func
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1F0@mbtlipnt02.btlabs.bt.co.uk>

> I am pretty sure that you are asking too much.  Even in text mode,
> you should be able to switch between different sessions.  Keep one
> session in your editor window where the source file is visible.
> Then have a Python session.  

Or use CTRL-Z to suspend the editor and fg to bring python up etc, 
lots of options, but.... His post suggested he wanted to do it 
all from within the python promppt - thats a tad harder!

Maybe emacs -nw would be your best bet - then you can split the 
screen in text mode, run a shell in one pane(running python) 
and edit the code in the other pane. However emacs may be 
as big a resource hog as X....

Just a thought, Its how I used to work on Unix before I got
a workstation and had to use a real VT200....

Alan g.


From Bruce.Lee-Shanok@cognos.com  Thu Dec 20 20:30:55 2001
From: Bruce.Lee-Shanok@cognos.com (Lee-Shanok, Bruce)
Date: Thu, 20 Dec 2001 15:30:55 -0500
Subject: [Tutor] Global variables
Message-ID: <FB15E670DA55D51185350008C786514A0140EBC5@sottexch1.cognos.com>

Hello all,

	I'm trying to declare a global variable to keep count of a value
without constantly passing it around. The problem I'm running into is =
that
it's not being recognized in any of my functions. The basic format is:

totalerrors =3D 0
def CheckErrors(statuscode):
	if statuscode < 0:
		totalerrors =3D totalerrors + 1
		print "Error with code",
		print statuscode

def RunTest():
	status =3D Func1()
	CheckErrors(status)
	status =3D Func2()
	CheckErrors(status)
	status =3D Func3()
	CheckErrors(status)
	status =3D Func4()
	CheckErrors(status)

RunTest()

.. is there any way for me to get totalerrors recognized? How does =
Python
determine where the scope of the variable ends?

Bruce Lee-Shanok
Access Manager
(613) 738-1338 ext 5764
Cognos, Ottawa=20
[Riverside, 4th Floor, E9]

Ce message peut contenir des informations prot=E9g=E9es et/ou =
confidentielles.
Si vous avez re=E7u ce mail par erreur ou si vous n'en =EAtes pas le
destinataire, il vous est interdit d'utiliser, de copier, de diffuser =
ou de
distribuer les pi=E8ces qui y sont jointes. Supprimez-le et notifiez
imm=E9diatement par e-mail la personne qui vous l'a envoy=E9e. Merci =
d'avance.


This message may contain privileged and/or confidential information.  =
If you
have received this e-mail in error or are not the intended recipient, =
you
may not use, copy, disseminate, or distribute it; do not open any
attachments, delete it immediately from your system and notify the =
sender by
e-mail promptly that you have done so.  Thank You.


From pythontutor@venix.com  Thu Dec 20 20:59:01 2001
From: pythontutor@venix.com (Lloyd Kvam)
Date: Thu, 20 Dec 2001 15:59:01 -0500
Subject: [Tutor] Global variables
References: <FB15E670DA55D51185350008C786514A0140EBC5@sottexch1.cognos.com>
Message-ID: <3C225115.4010908@venix.com>

Any variable that is the target of an assignment statement is automatical=
ly
marked as a local variable.  You need to use the global statement first
if you want to assign to a global variable.

totalerrors =3D 0
def CheckErrors(statuscode):
	global totalerrors
	if statuscode < 0:
	...

You will need to repeat the global statement within each scope - for
each function def in your example.



Lee-Shanok, Bruce wrote:

> Hello all,
>=20
> 	I'm trying to declare a global variable to keep count of a value
> without constantly passing it around. The problem I'm running into is t=
hat
> it's not being recognized in any of my functions. The basic format is:
>=20
> totalerrors =3D 0
> def CheckErrors(statuscode):
> 	if statuscode < 0:
> 		totalerrors =3D totalerrors + 1
> 		print "Error with code",
> 		print statuscode
>=20
> def RunTest():
> 	status =3D Func1()
> 	CheckErrors(status)
> 	status =3D Func2()
> 	CheckErrors(status)
> 	status =3D Func3()
> 	CheckErrors(status)
> 	status =3D Func4()
> 	CheckErrors(status)
>=20
> RunTest()
>=20
> .. is there any way for me to get totalerrors recognized? How does Pyth=
on
> determine where the scope of the variable ends?
>=20
> Bruce Lee-Shanok
> Access Manager
> (613) 738-1338 ext 5764
> Cognos, Ottawa=20
> [Riverside, 4th Floor, E9]
>=20
> Ce message peut contenir des informations prot=E9g=E9es et/ou confident=
ielles.
> Si vous avez re=E7u ce mail par erreur ou si vous n'en =EAtes pas le
> destinataire, il vous est interdit d'utiliser, de copier, de diffuser o=
u de
> distribuer les pi=E8ces qui y sont jointes. Supprimez-le et notifiez
> imm=E9diatement par e-mail la personne qui vous l'a envoy=E9e. Merci d'=
avance.
>=20
>=20
> This message may contain privileged and/or confidential information.  I=
f you
> have received this e-mail in error or are not the intended recipient, y=
ou
> may not use, copy, disseminate, or distribute it; do not open any
> attachments, delete it immediately from your system and notify the send=
er by
> e-mail promptly that you have done so.  Thank You.
>=20
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>=20
>=20


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

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



From bwinton@tor.dhs.org  Fri Dec 21 02:09:43 2001
From: bwinton@tor.dhs.org (Blake Winton)
Date: Thu, 20 Dec 2001 21:09:43 -0500
Subject: [Tutor] printing out the definition of a func
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1F0@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1F0@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20011220210943.A1694@tor.dhs.org>

* alan.gauld@bt.com <alan.gauld@bt.com> [011220 20:25]:
> > I am pretty sure that you are asking too much.  Even in text mode,
> > you should be able to switch between different sessions.  Keep one
> > session in your editor window where the source file is visible.
> > Then have a Python session.  
> Maybe emacs -nw would be your best bet - then you can split the 
> screen in text mode, run a shell in one pane(running python) 
> and edit the code in the other pane. However emacs may be 
> as big a resource hog as X....

or screen...
http://www.math.fu-berlin.de/~guckes/screen/

And it's a little smaller than emacs...  ;)
 236404 Aug 18  1999 /usr/bin/screen
2878448 Sep 25  1999 /usr/bin/emacs

Of course, I'm still kind of surprised no-one's mentioned the
"dis" module yet.  It doesn't seem to be exactly what the original
poster wants, but it's a little closer...

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

Later,
Blake.
-- 
9:40pm up 52 days, 21:07, 2 users, load average: 0.02, 0.09, 0.07


From syrinx@simplecom.net  Fri Dec 21 04:54:45 2001
From: syrinx@simplecom.net (Scott)
Date: Thu, 20 Dec 2001 22:54:45 -0600
Subject: [Tutor] hash table
Message-ID: <200112202256823.SM13047@there>

If all I really want is an efficient hash table, should I just use a 
dictionary?  Or is there a better way?

Thanks.


From deliberatus@my995internet.com  Fri Dec 21 06:10:16 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Fri, 21 Dec 2001 01:10:16 -0500
Subject: [Tutor] rfc822.rewindbody()
Message-ID: <3C22D248.3CA5DB26@my995internet.com>

OK, I confizedde... how do I properly use rewindbody()?

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From dvass@felis.uni-freiburg.de  Thu Dec 20 01:40:46 2001
From: dvass@felis.uni-freiburg.de (Joerg Woelke)
Date: Thu, 20 Dec 2001 02:40:46 +0100
Subject: [Tutor] IDLE in linux
In-Reply-To: <001501c188d1$c4d1a2e0$141af50c@attbi.com>; from thejoness3@attbi.com on Wed, Dec 19, 2001 at 04:11:46PM -0500
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1E6@mbtlipnt02.btlabs.bt.co.uk> <001501c188d1$c4d1a2e0$141af50c@attbi.com>
Message-ID: <20011220024046.B1287@Laplace.localdomain>

On Wed, Dec 19, 2001 at 04:11:46PM -0500, Jeff Jones wrote:
> I tried ./idle but got this error (retyped from linux to outlook):
                                                           ^^^^^^^^
                                                           *baeh* 
man mutt

> Traceback (most recent call last):
>   File "./idle", line 5, in ?
>      from idlelib import idleconf
> ImportError: No module IdleConf

Well - it does not find idleconf.py[c]. What is it? I don't have it
on my system with idle installed and running.
<hints>
- Unix is case sensitive *duck*
- Use the source Luke!
</hints>

> 
> Thanks for all your help! I know I have seen people ask similar ?'s. Is
> there an archive of this list somewhere?

try comp.lang.python at groups.google.com.
 
HTH,HAND
and good luck J"o!

-- 
Man belongs wherever he wants to go.
		-- Wernher von Braun


From dvass@felis.uni-freiburg.de  Thu Dec 20 01:24:45 2001
From: dvass@felis.uni-freiburg.de (Joerg Woelke)
Date: Thu, 20 Dec 2001 02:24:45 +0100
Subject: [Tutor] IDLE in linux
In-Reply-To: <20011219184316.E907@speakeasy.net>; from arcege@speakeasy.net on Wed, Dec 19, 2001 at 06:43:16PM -0500
References: <XFMail.20011217155154.shalehperry@attbi.com> <000001c188a8$dbc9c000$141af50c@attbi.com> <20011219184316.E907@speakeasy.net>
Message-ID: <20011220022445.A1287@Laplace.localdomain>

On Wed, Dec 19, 2001 at 06:43:16PM -0500, Michael P. Reilly wrote:
> to make sure the pathname of the interpreter in
>   #!/path/to/interpreter
> 
> is correct (sometimes it is /usr/local/bin/python when it is really
> in /usr/bin/python or /usr/local/bin/python2).

How about "#!/usr/bin/env python" wich sets up the environment for you?

> 
>   -Arcege

HTH,HAND
and Greetings J"o!

-- 
Man belongs wherever he wants to go.
		-- Wernher von Braun


From wheelege@hotmail.com  Fri Dec 21 08:27:06 2001
From: wheelege@hotmail.com (Glen Wheeler)
Date: Fri, 21 Dec 2001 19:27:06 +1100
Subject: [Tutor] hash table
References: <200112202256823.SM13047@there>
Message-ID: <DAV22Rl5gWpcRdqwkEz00004006@hotmail.com>

> If all I really want is an efficient hash table, should I just use a
> dictionary?  Or is there a better way?
>

  Dictionaries are very efficient - I use them all the time.  I guess you
could use a C hash but really...the performance difference is negligible to
zero :)
  I am not up to scratch in C, but I think dicts are more versatile as well.

  HTH,
  Glen


From lonetwin@yahoo.com  Fri Dec 21 08:09:58 2001
From: lonetwin@yahoo.com (lonetwin)
Date: Fri, 21 Dec 2001 13:39:58 +0530
Subject: [Tutor] printing out the definition of a func
In-Reply-To: <3C21EDF1.7010209@venix.com>
References: <01122017084100.05475@mercury.worli> <3C21EDF1.7010209@venix.com>
Message-ID: <01122113395801.08105@mercury.worli>

Hi there, Llyod, Alan, Blake, (and a note for everybody else futher down)
     Thanx for replying,

On Thursday 20 December 2001 19:26, Llyod wrote:
> I am pretty sure that you are asking too much.
     I thought as much <sigh>

>  Even in text mode,
> you should be able to switch between different sessions.  Keep one
> session in your editor window where the source file is visible.
> Then have a Python session.  Use:
> import FILENAME		- the first time
> reload(FILENAME)
> - later times
> to get the latest changes from the source file.  Rember to save to
> the disk from your editor.
     That's how I do it .....but it's such a pain, 'cos I keep forgetting to 
save, or to reload.....or I just end up def-ing a function/class in the 
intepreter itself, before I realise it just got too long :)

Alan wrote:
> Maybe emacs -nw would be your best bet - then you can split the 
> screen in text mode, run a shell in one pane(running python) 
> and edit the code in the other pane. However emacs may be 
> as big a resource hog as X....
      Emacs ......who that ??? .......me vi  guy :)

Blake wrote:
> or screen...
> http://www.math.fu-berlin.de/~guckes/screen/
     Hey thanx....I didn't know about screen, it was already there on my 
system......looks useful :)

Thanx all

Ok, now everything beyond this is purely fun value....I might never use 
something like this actually.......but here goes (pssst Danny I think you 
like games .......even if they are totally pointless :)
===========
 ......here goes, now this is utterly stupid, but since I was so taken up by 
this problem .....I started writing some crap,  I thought I'd write a wrapper 
around the python intepreter (call it wrappy.py) and use that instead ....the 
idea is, I fire up the intepreter as a sub process to my program, connect the 
stdin/stdout to the sub-process, with the stdin/stdout of my program, and 
monitor everything that goes thru' the stdin, as soon as I see a def or a 
class keyword, I start saving up the strings in a dict with the 
func-name/class-name as key. And when I see another keyword
 (say "showCode argument") I recall and print the string that was saved with 
"argument" as key. I don't know if I'm clear enough ??!! (tell me if I'm not)

     I tried using a os.popen[2/3] but didn't seem to get anywhere, I don't 
really know how os.pipe() works, but maybe that should serve my purpose ...I 
don't know !!!....an' I won't get sleep untill I get it working (then 
ofcourse I'll throw it away :)) ......
......I think I need professional help :). If anyone could help me 
out....please do 

Peace
Steve

-- 
----------------------------------------------
I get up each morning, gather my wits.
Pick up the paper, read the obits.
If I'm not there I know I'm not dead.
So I eat a good breakfast and go back to bed.

Oh, how do I know my youth is all spent?
My get-up-and-go has got-up-and-went.
But in spite of it all, I'm able to grin,
And think of the places my get-up has been.
                -- Pete Seeger
----------------------------------------------


From karthikg@aztec.soft.net  Fri Dec 21 11:24:23 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Fri, 21 Dec 2001 16:54:23 +0530
Subject: [Tutor] An hour's talk on python...Suggestions required (from a newbie)
In-Reply-To: <3C22D248.3CA5DB26@my995internet.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDGEBHCMAA.karthikg@aztec.soft.net>

hi all,

Our company does'nt use python. many have'nt even heard of it.
hi all,

Ours is mainly a java shop.

We have lots of internal training sessions @ our place.
Anyone with a decent knowledge of a particular subject can take such
sessions.
I was planning to take an introductory session on python.

I feel irrespective of how good the language is, not many
w'd want to try it out unless and otherwise they can see lots of
supporting tools and libraries.

It has to be a 1 hour talk.
Can someone give me pointers as to how this session c'd be organized?

1. functional programming in python
2. about new features that have been included in 2.2?
3. threading as for as tools/libraries are concerned,
4. GUI : Tkinter
5. xml?? : the one which ships with standard module or something else?
6. cgi:

am kind of a newbie.
But i want to develop some interest here @ my place.
Any suggestion w'd be of great help to me.

thanks and regards,
karthik.



-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Kirk Bailey
Sent: Friday, December 21, 2001 11:40 AM
To: tutor@python.org
Subject: [Tutor] rfc822.rewindbody()


OK, I confizedde... how do I properly use rewindbody()?

--
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/

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


From ylee12@uiuc.edu  Fri Dec 21 16:34:34 2001
From: ylee12@uiuc.edu (Young-Jin Lee)
Date: Fri, 21 Dec 2001 10:34:34 -0600
Subject: [Tutor] [Q] Install Python in RedHat
Message-ID: <010201c18a3d$5fcf3de0$95757e82@visit2>

Hi, I have a question on how to install Python in redhat linux. (I was using
Python in windows and now I want to use it on linux.)
I downloaded the latest version of Python (2.2c1) into home directory. I,
then, did gunzip, tar xvf, ".configure", and make. After I tried to run
python interpreter after installation, I still got the python 1.5.2, not
python 2.2.2 rc1. I guess the reason is I should install the new python in
the right place. I downloaded it into my user directory and did above things
on that directory.
Where is the right place to install the newer version of Python?
What should I do to make the newer version to be a default Python
interpreter for the linux?

TIA.

Young-Jin



From mazaraul@hotmail.com  Fri Dec 21 17:20:36 2001
From: mazaraul@hotmail.com (Raul)
Date: Fri, 21 Dec 2001 12:20:36 -0500
Subject: [Tutor] do not send anymore email to this address
Message-ID: <OE433XNZyp994GYVzRS00005e87@hotmail.com>

This is a multi-part message in MIME format.

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

do not send anymore email to this address


------=_NextPart_000_001A_01C18A19.E5266A00
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#aaafff>
<DIV>
<P><FONT color=3D#aa0bb0 size=3D7>do not send anymore email to this=20
address</FONT></P></DIV></BODY></HTML>

------=_NextPart_000_001A_01C18A19.E5266A00--


From wilson@visi.com  Fri Dec 21 17:11:23 2001
From: wilson@visi.com (Timothy Wilson)
Date: Fri, 21 Dec 2001 11:11:23 -0600 (CST)
Subject: [Tutor] unpickling a class
Message-ID: <Pine.GSO.4.21.0112211106100.6665-100000@isis.visi.com>

Hi everyone,

I'm going to try to ask this question in a general enough way to avoid
getting bogged down in specifics.

My students are just finishing a program that keeps track of the
performance of a collection of stocks in an investment portfolio
(http://www.isd197.org/sibley/cs/icp/assignments/portfolio_html). We're
about to start object-oriented programming (OOP) and I'm in the process
of converting my version of the portfolio program to use objects. I
thought this might make a good comparison study for them.

I'm having trouble building a constructor method for the Portfolio class
that allows me to *either* create a portfolio instance from scratch or
load one from disk using the pickle module.

Any hints or do I need to post some code?

-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 toodles@yifan.net  Fri Dec 21 17:29:33 2001
From: toodles@yifan.net (Andy W)
Date: Sat, 22 Dec 2001 01:29:33 +0800
Subject: [Tutor] unpickling a class
References: <Pine.GSO.4.21.0112211106100.6665-100000@isis.visi.com>
Message-ID: <003301c18a45$13b8f6f0$0300a8c0@sun>

Hi Tim,

> I'm having trouble building a constructor method for the Portfolio class
> that allows me to *either* create a portfolio instance from scratch or
> load one from disk using the pickle module.

How about something like:

import pickle

class Portfolio:
  def __init__(self,pickle_file=None):
    if pickle_file is not None:
      pickled_instance=pickle.load(pickle_file)
      ... extract whatever you need from it
    else:
      ... continue as normal

I'm not sure if there's a way to make an instance become equal to another
value within the constructor, perhaps someone else can enlighten you (and me
at the same time! :)

HTH,
Andrew

>
> Any hints or do I need to post some code?
>
> -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
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From dsh8290@rit.edu  Fri Dec 21 17:54:41 2001
From: dsh8290@rit.edu (dman)
Date: Fri, 21 Dec 2001 12:54:41 -0500
Subject: [Tutor] Unsigned numerical literals?
In-Reply-To: <FB15E670DA55D51185350008C786514A0140EBAD@sottexch1.cognos.com>; from Bruce.Lee-Shanok@cognos.com on Wed, Dec 19, 2001 at 03:54:47PM -0500
References: <FB15E670DA55D51185350008C786514A0140EBAD@sottexch1.cognos.com>
Message-ID: <20011221125441.A1680@harmony.cs.rit.edu>

On Wed, Dec 19, 2001 at 03:54:47PM -0500, Lee-Shanok, Bruce wrote:
| Hello all. Quick question: I'm writing a wrapper for some C calls in Python.
| The issue here is that the C code takes an unsigned long. Now, Python
| integers are, to the best of my understanding, also 32 bit, but not unsigned
| by default. Is there a clean way to force them to be unsigned? I'd hate to
| have to force the users of the Python code to write an "L" at the end of
| every value they bring in....

How about :

>>> import struct
>>> s = struct.pack( "L" , 123 )
>>> i = struct.unpack( "L" , s )
>>> print i
(123L,)

The struct module allows you to treat a string as a bunch of binary
data.  It may be helpful for you to use it to turn the python objects
into binary data.  You may want to just convert the numbers to longs
and ensure the value is positive.

-D

-- 

the nice thing about windoze is - it does not just crash,
it displays a dialog box and lets you press 'ok' first.



From dsh8290@rit.edu  Fri Dec 21 17:56:55 2001
From: dsh8290@rit.edu (dman)
Date: Fri, 21 Dec 2001 12:56:55 -0500
Subject: [Tutor] Passing a variable to 'import'
In-Reply-To: <20011220043209.JBYO42229.fep01-mail.bloor.is.net.cable.rogers.com@there>; from rufmetal@rogers.com on Wed, Dec 19, 2001 at 11:17:30PM -0500
References: <20011220043209.JBYO42229.fep01-mail.bloor.is.net.cable.rogers.com@there>
Message-ID: <20011221125655.B1680@harmony.cs.rit.edu>

On Wed, Dec 19, 2001 at 11:17:30PM -0500, Chris Keelan wrote:

| So how do I, for example, grab a module name from sys.argv and then pass it 
| to the import command as a variable?

the_mod = __import__( sys.argv[1] )

-D

-- 

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



From vcardon@siue.edu  Fri Dec 21 17:56:45 2001
From: vcardon@siue.edu (Victor R. Cardona)
Date: Fri, 21 Dec 2001 11:56:45 -0600
Subject: [Tutor] string replacements using dictionaries
Message-ID: <20011221115645.A21968@client156-52.ll.siue.edu>

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

Hi everyone,

I am having a bit of a problem with string replacements. I am writing a
cgi script that reads in a html file and subtitutes all of the '%(key)s'
markers for the values in a dictionary. There are five such markers
containing four different keys. The dictionary has values assigned for
the four keys. However, when I run the script I get "TypeError: Not
enough arguements for format string" Does anyone have any idea as to
what I am doing wrong?

Thanks,
Victor
--=20
Victor R. Cardona
Powered by SuSE Linux 7.1 (i386) Professional
GPG key ID E81B3A1C
Key fingerprint =3D 0147 A234 99C3 F4C5 BC64  F501 654F DB49 E81B 3A1C

--ReaqsoxgOBHFXBhH
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

iD8DBQE8I3fdZU/bSegbOhwRAjdcAKCDYAfNf3k4/XrY3Zak7bccfogVxACeLXVW
rvTji5AonIvM3Zp6hJX5AZI=
=vrcE
-----END PGP SIGNATURE-----

--ReaqsoxgOBHFXBhH--


From dsh8290@rit.edu  Fri Dec 21 18:05:04 2001
From: dsh8290@rit.edu (dman)
Date: Fri, 21 Dec 2001 13:05:04 -0500
Subject: [Tutor] min() & mutable sequences
In-Reply-To: <000501c18919$40fe2630$0300a8c0@sun>; from toodles@yifan.net on Thu, Dec 20, 2001 at 01:43:27PM +0800
References: <000501c18919$40fe2630$0300a8c0@sun>
Message-ID: <20011221130504.C1680@harmony.cs.rit.edu>

On Thu, Dec 20, 2001 at 01:43:27PM +0800, Andy W wrote:
| Hi people,
| 
| First to give some background: I have a list of instances, each has an
| attributes "distance". I want to get the instance with the smallest
| distance.
| 
| I have at present:-
| 
| robots=[...] #The ... is a whole lot of instances :)
| closest=min([robot.distance for robot in robots])
| 
| Okay, I now have the closest *distance*.
| Say more than one instance has the same distance, will min() return the
| first instance with that smallest distance? Because if that is so, I could
| then just get the related instance using:-

No.  min() returns the smallest object in the list.  In this case the
object is a number, not a robot.

| closest_index=[robot.distance for robot in robots].index(closest)
| #Yeah, I used that list comprehension twice, this is just for demonstration,
| though.
| closest_robot=robots[closest_index]

This could be done, but I think it is inefficient.  How about defining
__lt__ in your class?  Then you don't need to create separate lists
using the distances.

| Is there a better way to do it?
| 
| I guess I could iterate over the list, and keep a smallest distance variable
| somewhere. I guess I've become somewhat of a list-comprehension-addict
| *grin*

This should do it :

m = robots[0]
d = m.distance
for r in robots[1:] :
    if r.distance < d : m = r
print m

certainly there are other ways, though.  

I'm kinda surprised that min() doesn't take a comparison function like
sort does.  Say, I just thought of :

robots.sort( lamda a , b : a.distance < b.distance )
print robots[0]

If you sort it, the minimum will be the first element in the list :-).
    
-D

-- 

If your company is not involved in something called "ISO 9000" you
probably have no idea what it is.  If your company _is_ involved in ISO
9000 then you definitely have no idea what it is.
                                (Scott Adams - The Dilbert principle)



From dsh8290@rit.edu  Fri Dec 21 18:08:26 2001
From: dsh8290@rit.edu (dman)
Date: Fri, 21 Dec 2001 13:08:26 -0500
Subject: [Tutor] initializing multiple attributes to same value
In-Reply-To: <20011220001453.F3310@hal>; from i812@iname.com on Thu, Dec 20, 2001 at 12:14:53AM -0600
References: <20011220001453.F3310@hal>
Message-ID: <20011221130826.D1680@harmony.cs.rit.edu>

On Thu, Dec 20, 2001 at 12:14:53AM -0600, Rob McGee wrote:
| I tripped myself up on something like this:
| 
| {code}
| class Whatever:
|   def __init__(self):
|     self.one = self.two = self.three = 0

This works as intended because integers are immutable.

|     self.listOne = self.listTwo = []

If you then try 
    self.listOne.append( "foo" )
you'll see that both names refer to the same object, and you just
changed that object.

|   def __init__(self):
|     list1 = self.one, self.two, self.three
|     for item in list1:
|       item = 0
|     list2 = self.listOne, self.listTwo
|     for item in list2:
|       item = []

This won't work because you are assigning to the name 'item', not
'self.listOne'.  Also, 'self.listOne' must exist before you can put it
in a tuple.

-D

-- 

"GUIs normally make it simple to accomplish simple actions and
impossible to accomplish complex actions."
    --Doug Gwyn  (22/Jun/91 in comp.unix.wizards)



From lumbricus@gmx.net  Fri Dec 21 18:14:27 2001
From: lumbricus@gmx.net (Joerg Woelke)
Date: Fri, 21 Dec 2001 19:14:27 +0100
Subject: [Tutor] [Q] Install Python in RedHat
In-Reply-To: <010201c18a3d$5fcf3de0$95757e82@visit2>; from ylee12@uiuc.edu on Fri, Dec 21, 2001 at 10:34:34AM -0600
References: <010201c18a3d$5fcf3de0$95757e82@visit2>
Message-ID: <20011221191427.A4028@Laplace.localdomain>

On Fri, Dec 21, 2001 at 10:34:34AM -0600, Young-Jin Lee wrote:

[ snip ]

> Where is the right place to install the newer version of Python?
> What should I do to make the newer version to be a default Python
> interpreter for the linux?

$ ls -l `which python`
lrwxrwxrwx   1 root     root           24 Aug 17 20:12 /usr/bin/python -> \
 /usr/local/bin/python2.0
$

or man alias
or copy the python2.0 to python somewhere in your $PATH.

> 
> TIA.
> 
> Young-Jin

HTH,HAND
and greetings J"o!

-- 
I don't believe there really IS a GAS SHORTAGE.. I think it's all just
a BIG HOAX on the part of the plastic sign salesmen -- to sell more numbers!!


From dsh8290@rit.edu  Fri Dec 21 18:14:04 2001
From: dsh8290@rit.edu (dman)
Date: Fri, 21 Dec 2001 13:14:04 -0500
Subject: [Tutor] [Q] Install Python in RedHat
In-Reply-To: <010201c18a3d$5fcf3de0$95757e82@visit2>; from ylee12@uiuc.edu on Fri, Dec 21, 2001 at 10:34:34AM -0600
References: <010201c18a3d$5fcf3de0$95757e82@visit2>
Message-ID: <20011221131404.E1680@harmony.cs.rit.edu>

On Fri, Dec 21, 2001 at 10:34:34AM -0600, Young-Jin Lee wrote:
| Hi, I have a question on how to install Python in redhat linux. (I was using
| Python in windows and now I want to use it on linux.)
| I downloaded the latest version of Python (2.2c1) into home directory. I,
| then, did gunzip, tar xvf, ".configure", and make. After I tried to run
| python interpreter after installation, I still got the python 1.5.2, not
| python 2.2.2 rc1. I guess the reason is I should install the new python in
| the right place. I downloaded it into my user directory and did above things
| on that directory.
| Where is the right place to install the newer version of Python?

# make install

I suggest getting package instead, though.  Someone has surely made an
rpm of it, or you can make your own if you find a srpm.

| What should I do to make the newer version to be a default Python
| interpreter for the linux?

That depends.  How does python get run, *by all scripts or programs
that run it*?

For Debian systems there is a policy that allows multiple simultaneous
python installes.  For example I have the python2.1' and 'python2.2'
packages installed.  Thus I have /usr/bin/python2.1 and
/usr/bin/python2.2 (/usr/bin/python is a symlink to python2.1).
Scripts can then either specify the version they want or use the
default.

HTH,
-D

-- 

Bugs come in through open windows. Keep Windows shut!



From dsh8290@rit.edu  Fri Dec 21 18:16:45 2001
From: dsh8290@rit.edu (dman)
Date: Fri, 21 Dec 2001 13:16:45 -0500
Subject: [Tutor] string replacements using dictionaries
In-Reply-To: <20011221115645.A21968@client156-52.ll.siue.edu>; from vcardon@siue.edu on Fri, Dec 21, 2001 at 11:56:45AM -0600
References: <20011221115645.A21968@client156-52.ll.siue.edu>
Message-ID: <20011221131645.F1680@harmony.cs.rit.edu>

On Fri, Dec 21, 2001 at 11:56:45AM -0600, Victor R. Cardona wrote:
| Hi everyone,
| 
| I am having a bit of a problem with string replacements. I am writing a
| cgi script that reads in a html file and subtitutes all of the '%(key)s'
| markers for the values in a dictionary. There are five such markers
| containing four different keys. The dictionary has values assigned for
| the four keys. However, when I run the script I get "TypeError: Not
| enough arguements for format string" Does anyone have any idea as to
| what I am doing wrong?

Not without seeing the code.  This works fine for me :

(on one line)
>>> print "%(foo)s %(bar)s %(spam)s %(eggs)s" %
        { "foo":1 , "bar":2, "eggs":4, "spam":3 }
1 2 3 4
>>>

-D

-- 

"He is no fool who gives up what he cannot keep to gain what he cannot lose."
        --Jim Elliot



From vcardon@siue.edu  Fri Dec 21 18:28:28 2001
From: vcardon@siue.edu (Victor R. Cardona)
Date: Fri, 21 Dec 2001 12:28:28 -0600
Subject: [Tutor] string replacements using dictionaries
In-Reply-To: <20011221131645.F1680@harmony.cs.rit.edu>; from dsh8290@rit.edu on Fri, Dec 21, 2001 at 01:16:45PM -0500
References: <20011221115645.A21968@client156-52.ll.siue.edu> <20011221131645.F1680@harmony.cs.rit.edu>
Message-ID: <20011221122828.A22113@client156-52.ll.siue.edu>

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

On Fri, Dec 21, 2001 at 01:16:45PM -0500, dman wrote:
> On Fri, Dec 21, 2001 at 11:56:45AM -0600, Victor R. Cardona wrote:
> | Hi everyone,
> |=20
> | I am having a bit of a problem with string replacements. I am writing a
> | cgi script that reads in a html file and subtitutes all of the '%(key)s'
> | markers for the values in a dictionary. There are five such markers
> | containing four different keys. The dictionary has values assigned for
> | the four keys. However, when I run the script I get "TypeError: Not
> | enough arguements for format string" Does anyone have any idea as to
> | what I am doing wrong?
>=20
> Not without seeing the code.  This works fine for me :
>=20
> (on one line)
> >>> print "%(foo)s %(bar)s %(spam)s %(eggs)s" %
>         { "foo":1 , "bar":2, "eggs":4, "spam":3 }
> 1 2 3 4
> >>>

Yeah, that works for me too. I have included the code below.

<?xml version=3D"1.0" encoding=3D"UTF-8"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "DTD/xhtml1-strict.dtd">
<html xmlns=3D"http://www.w3.org/1999/xhtml" xml:lang=3D"en" lang=3D"en">
<head>
<title>%(title)s</title>
<meta name=3D"author" content=3D"Victor R. Cardona"/>
<link rel=3D"stylesheet" href=3D"../sysconfig/styles/work.css" type=3D"text=
/css"/>
</head>

<body>
<div align=3D"center">
%(blank)s
<table width=3D"98%" border=3D"1" frame=3D"void" rules=3D"none" cellspacing=
=3D"0" cellpadding=3D"10">
<tr class=3D"header"><td><h2>
%(head)s
</h2>
</td>
</tr>
%(items)s
</table>
%(blank)s
</div>
</body>
</html>


#!/usr/local/bin/python
#
# This script will read in the todo.txt fule, and the template.html files,=
=20
# and create an html document from the two.
import textproc

template =3D '/usr/local/www/data/sysconfig/template2.html'
content =3D '/usr/local/www/data/sysconfig/todo.txt'

templateString =3D open(template, 'r').read()
dataList =3D open(content, 'r').readlines()

data =3D {'title':'To Do', 'head':'System Configurator -- To Do'}

for i in range(len(dataList)):
    str =3D dataList[i]
    str =3D '<li>' + str[:-1] + '</li>\n'
    dataList[i] =3D str

newStr =3D '<tr><td><ul>\n'

for str in dataList:
    newStr =3D newStr + str

newStr =3D newStr + '</ul></td></tr>'
data['items'] =3D newStr
data['blank'] =3D ''

textproc.print_file(template % data)


Thanks,
Victor
--=20
Victor R. Cardona
Powered by SuSE Linux 7.1 (i386) Professional
GPG key ID E81B3A1C
Key fingerprint =3D 0147 A234 99C3 F4C5 BC64  F501 654F DB49 E81B 3A1C

--SUOF0GtieIMvvwua
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

iD8DBQE8I39MZU/bSegbOhwRAmHqAKCsTKOvlX24kLIkNZG+xH4R+nWYBgCeLpHq
C9eM0ukvBUz+Gbv6Wm49HSk=
=nf/H
-----END PGP SIGNATURE-----

--SUOF0GtieIMvvwua--


From vcardon@siue.edu  Fri Dec 21 18:52:56 2001
From: vcardon@siue.edu (Victor R. Cardona)
Date: Fri, 21 Dec 2001 12:52:56 -0600
Subject: [Tutor] string replacements using dictionaries
In-Reply-To: <20011221122828.A22113@client156-52.ll.siue.edu>; from vcardon@siue.edu on Fri, Dec 21, 2001 at 12:28:28PM -0600
References: <20011221115645.A21968@client156-52.ll.siue.edu> <20011221131645.F1680@harmony.cs.rit.edu> <20011221122828.A22113@client156-52.ll.siue.edu>
Message-ID: <20011221125256.A22278@client156-52.ll.siue.edu>

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

On Fri, Dec 21, 2001 at 12:28:28PM -0600, Victor R. Cardona wrote:
> On Fri, Dec 21, 2001 at 01:16:45PM -0500, dman wrote:
> > On Fri, Dec 21, 2001 at 11:56:45AM -0600, Victor R. Cardona wrote:
> > | Hi everyone,
> > |=20
> > | I am having a bit of a problem with string replacements. I am writing=
 a
> > | cgi script that reads in a html file and subtitutes all of the '%(key=
)s'
> > | markers for the values in a dictionary. There are five such markers
> > | containing four different keys. The dictionary has values assigned for
> > | the four keys. However, when I run the script I get "TypeError: Not
> > | enough arguements for format string" Does anyone have any idea as to
> > | what I am doing wrong?
> >=20
> > Not without seeing the code.  This works fine for me :
> >=20
> > (on one line)
> > >>> print "%(foo)s %(bar)s %(spam)s %(eggs)s" %
> >         { "foo":1 , "bar":2, "eggs":4, "spam":3 }
> > 1 2 3 4
> > >>>
>=20
> Yeah, that works for me too. I have included the code below.
>=20
> <?xml version=3D"1.0" encoding=3D"UTF-8"?>
> <!DOCTYPE html
>     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
>     "DTD/xhtml1-strict.dtd">
> <html xmlns=3D"http://www.w3.org/1999/xhtml" xml:lang=3D"en" lang=3D"en">
> <head>
> <title>%(title)s</title>
> <meta name=3D"author" content=3D"Victor R. Cardona"/>
> <link rel=3D"stylesheet" href=3D"../sysconfig/styles/work.css" type=3D"te=
xt/css"/>
> </head>
>=20
> <body>
> <div align=3D"center">
> %(blank)s
> <table width=3D"98%" border=3D"1" frame=3D"void" rules=3D"none" cellspaci=
ng=3D"0" cellpadding=3D"10">
> <tr class=3D"header"><td><h2>
> %(head)s
> </h2>
> </td>
> </tr>
> %(items)s
> </table>
> %(blank)s
> </div>
> </body>
> </html>
>=20
>=20
> #!/usr/local/bin/python
> #
> # This script will read in the todo.txt fule, and the template.html files=
,=20
> # and create an html document from the two.
> import textproc
>=20
> template =3D '/usr/local/www/data/sysconfig/template2.html'
> content =3D '/usr/local/www/data/sysconfig/todo.txt'
>=20
> templateString =3D open(template, 'r').read()
> dataList =3D open(content, 'r').readlines()
>=20
> data =3D {'title':'To Do', 'head':'System Configurator -- To Do'}
>=20
> for i in range(len(dataList)):
>     str =3D dataList[i]
>     str =3D '<li>' + str[:-1] + '</li>\n'
>     dataList[i] =3D str
>=20
> newStr =3D '<tr><td><ul>\n'
>=20
> for str in dataList:
>     newStr =3D newStr + str
>=20
> newStr =3D newStr + '</ul></td></tr>'
> data['items'] =3D newStr
> data['blank'] =3D ''
>=20
> textproc.print_file(template % data)

The last line should read:

textproc.print_file(templateString % data)

-v
--=20
Victor R. Cardona
Powered by SuSE Linux 7.1 (i386) Professional
GPG key ID E81B3A1C
Key fingerprint =3D 0147 A234 99C3 F4C5 BC64  F501 654F DB49 E81B 3A1C

--MGYHOYXEY6WxJCY8
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

iD8DBQE8I4UIZU/bSegbOhwRAhGbAJsHKcj+yLkf07LsDyUbZsqBNgEKHwCfbAoi
3ldB8wFNdB5NbhD1a1EGsDE=
=ltK4
-----END PGP SIGNATURE-----

--MGYHOYXEY6WxJCY8--


From lkvam@venix.com  Fri Dec 21 14:17:50 2001
From: lkvam@venix.com (Lloyd Kvam)
Date: Fri, 21 Dec 2001 09:17:50 -0500
Subject: [Tutor] An hour's talk on python...Suggestions required (from a newbie)
References: <NEBBJNMDEKBIBCMCNMBDGEBHCMAA.karthikg@aztec.soft.net>
Message-ID: <3C23448E.6060502@venix.com>

For a Java shop, you'd probably want to include an example of Jython
fitting in with your existing Java classes.  While most modules are
available for Jython, there are exceptions.  To the extent you are
using Python to supplement Java, you don't want to tout modules that
aren't available for Jython.

Karthik Gurumurthy wrote:

> hi all,
> 
> Our company does'nt use python. many have'nt even heard of it.
> hi all,
> 
> Ours is mainly a java shop.
> 
> We have lots of internal training sessions @ our place.
> Anyone with a decent knowledge of a particular subject can take such
> sessions.
> I was planning to take an introductory session on python.
> 
> I feel irrespective of how good the language is, not many
> w'd want to try it out unless and otherwise they can see lots of
> supporting tools and libraries.
> 
> It has to be a 1 hour talk.
> Can someone give me pointers as to how this session c'd be organized?
> 
> 1. functional programming in python
> 2. about new features that have been included in 2.2?
> 3. threading as for as tools/libraries are concerned,
> 4. GUI : Tkinter
> 5. xml?? : the one which ships with standard module or something else?
> 6. cgi:
> 
> am kind of a newbie.
> But i want to develop some interest here @ my place.
> Any suggestion w'd be of great help to me.
> 
> thanks and regards,
> karthik.
> 
> 
> 
> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Kirk Bailey
> Sent: Friday, December 21, 2001 11:40 AM
> To: tutor@python.org
> Subject: [Tutor] rfc822.rewindbody()
> 
> 
> OK, I confizedde... how do I properly use rewindbody()?
> 
> --
> Respectfully,
>              -Kirk D Bailey (C)2001
>               Addme! icq #27840081
> end
> 
> 
> Within the sweep of his sword, Each man is an Ubar.
> 
> http://www.howlermonkey.net/
> http://www.sacredelectron.org/
> 
> _______________________________________________
> 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 dsh8290@rit.edu  Fri Dec 21 19:57:20 2001
From: dsh8290@rit.edu (dman)
Date: Fri, 21 Dec 2001 14:57:20 -0500
Subject: [Tutor] string replacements using dictionaries
In-Reply-To: <20011221122828.A22113@client156-52.ll.siue.edu>; from vcardon@siue.edu on Fri, Dec 21, 2001 at 12:28:28PM -0600
References: <20011221115645.A21968@client156-52.ll.siue.edu> <20011221131645.F1680@harmony.cs.rit.edu> <20011221122828.A22113@client156-52.ll.siue.edu>
Message-ID: <20011221145720.A2107@harmony.cs.rit.edu>

On Fri, Dec 21, 2001 at 12:28:28PM -0600, Victor R. Cardona wrote:
| On Fri, Dec 21, 2001 at 01:16:45PM -0500, dman wrote:
| > On Fri, Dec 21, 2001 at 11:56:45AM -0600, Victor R. Cardona wrote:
| > | Hi everyone,
| > | 
| > | I am having a bit of a problem with string replacements. I am writing a
| > | cgi script that reads in a html file and subtitutes all of the '%(key)s'
| > | markers for the values in a dictionary. There are five such markers
| > | containing four different keys. The dictionary has values assigned for
| > | the four keys. However, when I run the script I get "TypeError: Not
| > | enough arguements for format string" Does anyone have any idea as to
| > | what I am doing wrong?
| > 
| > Not without seeing the code.  This works fine for me :

| Yeah, that works for me too. I have included the code below.

Ok, I found the problem :

| <table width="98%" 
                  ^

You've got an extra % operator in there :-).

| for i in range(len(dataList)):
|     str = dataList[i]
|     str = '<li>' + str[:-1] + '</li>\n'
|     dataList[i] = str

If you want, this could be

dataList = [ ('<li>'+s[:-1]+'</li>\n') for s in dataList]

('str' is a built-in name, so it is preferred not to use it)

| newStr = '<tr><td><ul>\n'
| 
| for str in dataList:
|     newStr = newStr + str
| 
| newStr = newStr + '</ul></td></tr>'

I don't think this is what you want :

<tr><td><ul>
foo
<tr><td><ul>
bar
</ul></td></tr>


I think you want just

newStr = '<tr><td><ul>\n' + "\n".join( dataList ) + '</ul></td></tr>'


-D

-- 

"GUIs normally make it simple to accomplish simple actions and
impossible to accomplish complex actions."
    --Doug Gwyn  (22/Jun/91 in comp.unix.wizards)



From dyoo@hkn.eecs.berkeley.edu  Fri Dec 21 19:57:56 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 21 Dec 2001 11:57:56 -0800 (PST)
Subject: [Tutor] printing out the definition of a func [dis/inspect]
In-Reply-To: <01122017084100.05475@mercury.worli>
Message-ID: <Pine.LNX.4.21.0112211149030.14101-100000@hkn.eecs.berkeley.edu>

On Thu, 20 Dec 2001, lonetwin wrote:

>      A quick question, can I print out the definition of a func/class
> *after* I have defined it, in the python intepreter ??? ....it'd be
> nice to be able to do this 'cos I seem to need it pretty often (for
> debugging stuff)....and no, I do not use IDLE, 'cos I work at command
> prompt (under linux) and fire-up the intepreter there (X *crawls* on
> my system).

I don't think this will be easy to do.  Python does give us access to a
"code" object for a function:

###
>>> def hello(): print "Hello world"
... 
>>> hello.func_code
<code object hello at 80c9390, file "<stdin>", line 1>
###

but this func_code is something that's already been digested by Python's
byte compiler.

We can take a look at it more closely by using the 'dis' module:

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

###
>>> dis.dis(hello)     
          0 SET_LINENO          1

          3 SET_LINENO          1
          6 LOAD_CONST          1 ('Hello world')
          9 PRINT_ITEM     
         10 PRINT_NEWLINE  
         11 LOAD_CONST          0 (None)
         14 RETURN_VALUE 
###

but by then, it's already a bit uglified.

Wait, wait, I spoke too soon.  It is possible!  Take a look at:

    http://www.python.org/doc/lib/inspect-source.html

Hope this helps!



From dyoo@hkn.eecs.berkeley.edu  Fri Dec 21 20:07:56 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 21 Dec 2001 12:07:56 -0800 (PST)
Subject: [Tutor] hash table
In-Reply-To: <DAV22Rl5gWpcRdqwkEz00004006@hotmail.com>
Message-ID: <Pine.LNX.4.21.0112211203540.14101-100000@hkn.eecs.berkeley.edu>

On Fri, 21 Dec 2001, Glen Wheeler wrote:

> 
> > If all I really want is an efficient hash table, should I just use a
> > dictionary?  Or is there a better way?
> >
> 
>   Dictionaries are very efficient - I use them all the time.  I guess you
> could use a C hash but really...the performance difference is negligible to
> zero :)

My impression was that a Python dictionary is the same thing as a
"hashtable".  All things that can be used as keys in a dictionary need to
support the hash() function:

###
>>> hash(42)
42
>>> hash("lothlorien")
-435310080
>>> hash(['no', 'good'])
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: unhashable type
###



From dyoo@hkn.eecs.berkeley.edu  Fri Dec 21 20:24:42 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 21 Dec 2001 12:24:42 -0800 (PST)
Subject: [Tutor] min() & mutable sequences
In-Reply-To: <20011221130504.C1680@harmony.cs.rit.edu>
Message-ID: <Pine.LNX.4.21.0112211210580.14101-100000@hkn.eecs.berkeley.edu>

On Fri, 21 Dec 2001, dman wrote:

> On Thu, Dec 20, 2001 at 01:43:27PM +0800, Andy W wrote:
> | closest=min([robot.distance for robot in robots])
> | 
> | Okay, I now have the closest *distance*.
> | Say more than one instance has the same distance, will min() return the
> | first instance with that smallest distance? Because if that is so, I could
> | then just get the related instance using:-
> 
> No.  min() returns the smallest object in the list.  In this case the
> object is a number, not a robot.
> 
> | closest_index=[robot.distance for robot in robots].index(closest)
> | #Yeah, I used that list comprehension twice, this is just for demonstration,
> | though.
> | closest_robot=robots[closest_index]
> 
> 
> I'm kinda surprised that min() doesn't take a comparison function like
> sort does.


Here's an example of writing our own mymin() function that does take a
comparision function:

###
def mymin(elements, cmp_func=cmp):
    if len(elements) == 0:
        raise ValueError, 'mymin() of empty sequence'
    current_min = elements[0]
    for e in elements[1:]:
        if cmp_func(e, current_min) < 0:
            current_min = e
    return current_min
###


This mymin() is useful because now we can tell it what it means for one
thing to be 'smaller' than another.  Take a look:

###
>>> def cmpByLength(x, y): return cmp(len(x), len(y))
>>> mymin(['i', 'am', 'the', 'wind'])
'am'
>>> mymin(['i', 'am', 'the', 'wind'], cmpByLength)
'i'
###

Happy holidays!



From vcardon@siue.edu  Fri Dec 21 20:32:16 2001
From: vcardon@siue.edu (Victor R. Cardona)
Date: Fri, 21 Dec 2001 14:32:16 -0600
Subject: [Tutor] string replacements using dictionaries
In-Reply-To: <20011221145720.A2107@harmony.cs.rit.edu>; from dsh8290@rit.edu on Fri, Dec 21, 2001 at 02:57:20PM -0500
References: <20011221115645.A21968@client156-52.ll.siue.edu> <20011221131645.F1680@harmony.cs.rit.edu> <20011221122828.A22113@client156-52.ll.siue.edu> <20011221145720.A2107@harmony.cs.rit.edu>
Message-ID: <20011221143216.A22698@client156-52.ll.siue.edu>

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

On Fri, Dec 21, 2001 at 02:57:20PM -0500, dman wrote:
> On Fri, Dec 21, 2001 at 12:28:28PM -0600, Victor R. Cardona wrote:
> | On Fri, Dec 21, 2001 at 01:16:45PM -0500, dman wrote:
> | > On Fri, Dec 21, 2001 at 11:56:45AM -0600, Victor R. Cardona wrote:
> | > | I am having a bit of a problem with string replacements. I am writi=
ng a
> | > | cgi script that reads in a html file and subtitutes all of the '%(k=
ey)s'
> | > | markers for the values in a dictionary. There are five such markers
> | > | containing four different keys. The dictionary has values assigned =
for
> | > | the four keys. However, when I run the script I get "TypeError: Not
> | > | enough arguements for format string" Does anyone have any idea as to
> | > | what I am doing wrong?
> | >=20
> | > Not without seeing the code.  This works fine for me :
>=20
> | Yeah, that works for me too. I have included the code below.
>=20
> Ok, I found the problem :

Thanks! I will make the changes.

-v
--=20
Victor R. Cardona
Powered by SuSE Linux 7.1 (i386) Professional
GPG key ID E81B3A1C
Key fingerprint =3D 0147 A234 99C3 F4C5 BC64  F501 654F DB49 E81B 3A1C

--gKMricLos+KVdGMg
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

iD8DBQE8I5xQZU/bSegbOhwRArmRAKCsRvZWZz64YfsoJyaUogKqFH/hDACeIMNQ
FsOeWrHfBUWh3wQqlEER+Ew=
=uIGP
-----END PGP SIGNATURE-----

--gKMricLos+KVdGMg--


From dyoo@hkn.eecs.berkeley.edu  Fri Dec 21 20:39:42 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 21 Dec 2001 12:39:42 -0800 (PST)
Subject: [Tutor] initializing multiple attributes to same value
In-Reply-To: <20011220001453.F3310@hal>
Message-ID: <Pine.LNX.4.21.0112211227110.14101-100000@hkn.eecs.berkeley.edu>

On Thu, 20 Dec 2001, Rob McGee wrote:

> I tripped myself up on something like this:
> 
> {code}
> class Whatever:
>   def __init__(self):
>     self.one = self.two = self.three = 0
>     self.listOne = self.listTwo = []

What you're running into has more to do with the way that lists work than
member attributes.  For example:

###
>>> universities = colleges = ['berkeley', 'stanford']                  
>>> universities
['berkeley', 'stanford']
>>> colleges
['berkeley', 'stanford']
>>> universities.append('ucla')
>>> universities
['berkeley', 'stanford', 'ucla']
>>> colleges
['berkeley', 'stanford', 'ucla']
###

And you're right; the lists are being shared.  In the example above,
colleges and universites both refer to the "same" list.

It might help if we visualize variable names as ways of pointing our
fingers at a list object, sorta like this:


    colleges -------------------> ['berkeley', 'stanford', 'ucla']
                                  ^
                                  |
    universities -----------------+



What you probably want, instead, is something like this:

    colleges -------------------> ['berkeley', 'stanford', 'ucla']

    universities ---------------> ['berkeley', 'stanford', 'ucla']


That is, the two variables refer to lists that have the same stuff, but
are, nevertheless, different lists.  For that, we need to make a "copy" of
the list.

There are several ways to do this.  One way is to just hardcode it.

###
universities = ['berkeley', 'stanford', 'ucla']
colleges = ['berkeley', 'stanford', 'ucla']
###


Another way to copy lists is to take a full slice of a list:

###
universities = ['berkeley', 'stanford', 'ucla']
colleges = universities[:]
###


Don't worry if this doesn't make complete sense yet; please feel free to
ask more questions about this.  Good luck!



From dyoo@hkn.eecs.berkeley.edu  Fri Dec 21 20:59:32 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 21 Dec 2001 12:59:32 -0800 (PST)
Subject: [Tutor] rfc822.rewindbody()
In-Reply-To: <3C22D248.3CA5DB26@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112211240470.14101-100000@hkn.eecs.berkeley.edu>

On Fri, 21 Dec 2001, Kirk Bailey wrote:

> OK, I confizedde... how do I properly use rewindbody()?


Let's say that we have a sample message, like this:

###
m = """From sclaus@northpole.com Tue Dec  25 15:49:13 2001 -0800
Date: Tue, 25 Dec 2001 15:49:13 -0800 (PST)
From: Santa <sclaus@northpole.net>
To: Ebenezer <moneymoney@money.com>

Here.  Have a lump of coal.
"""
###

When we have something like this, rfc822.Message can parse it out into a
bunch of headers and the message body.  Since we're making a message from
a string, we need to wrap it with StringIO to make it look like a file:

###
>>> msg = rfc822.Message(StringIO.StringIO(m))
###

Now that we have this parsed message, we can read it's contents!  The
message body becomes accessible through an 'fp' attribute:

###
>>> msg.fp.read()
'Here.  Have a lump of coal.                                                    
 \012'
>>> msg.fp.read()
''
###

But notice that we can only read it once(); if we want to read it again,
we need to rewindbody() back:

###
>>> msg.rewindbody()                                                             
>>> msg.fp.read()                                                                
'Here.  Have a lump of coal.                                                    
 \012'
###



What's nice about rfc822.Message is that the headers are all there for us
too:

###
>>> msg.getheader('from')
'Santa <sclaus@northpole.net>'
>>> msg.getheader('to')                                                          
'Ebenezer <moneymoney@money.com>'
>>> msg.getheader('date')
'Tue, 25 Dec 2001 15:49:13 -0800 (PST)'
###


Happy holidays!



From wilson@visi.com  Fri Dec 21 22:49:41 2001
From: wilson@visi.com (Timothy Wilson)
Date: Fri, 21 Dec 2001 16:49:41 -0600 (CST)
Subject: [Tutor] unpickling a class
In-Reply-To: <003301c18a45$13b8f6f0$0300a8c0@sun>
Message-ID: <Pine.GSO.4.21.0112211645430.3128-100000@isis.visi.com>

On Sat, 22 Dec 2001, Andy W wrote:

> > I'm having trouble building a constructor method for the Portfolio class
> > that allows me to *either* create a portfolio instance from scratch or
> > load one from disk using the pickle module.
> 
> How about something like:
> 
> import pickle
> 
> class Portfolio:
>   def __init__(self,pickle_file=None):
>     if pickle_file is not None:
>       pickled_instance=pickle.load(pickle_file)
>       ... extract whatever you need from it
>     else:
>       ... continue as normal

OK, this make sense. I'm puzzled about the "... extract whatever you
need from it" part. It doesn't seem as though the attributes that have
been pickled are automatically unpickled. 

Here's my constructor method:

class Portfolio:
    def __init__(self, file=None):
        if file is not None:
            if fileExists(file):
                f = open(file, 'r')
                self = pickle.load(f)
                self.filename = file
                self.modified = 0
            else:
                print "File '%s' does not exist." % file               
        else:   
            self.owner = raw_input("Your name: ")
            self.account= raw_input("Account # ")
            self.contents = []
            self.modified = 0
            self.filename = ''

It would be nice if the 'self = pickle.load(f)' would automatically
regenerate all the instance's attributes. I looked in the file and I
know that "owner" and "account" attributes were there.

Any pointers?

-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 rufmetal@rogers.com  Fri Dec 21 23:57:03 2001
From: rufmetal@rogers.com (Chris Keelan)
Date: Fri, 21 Dec 2001 18:57:03 -0500
Subject: [Tutor] Passing a variable to 'import'
In-Reply-To: <3C218116.10500@yahoo.com>
References: <20011220043209.JBYO42229.fep01-mail.bloor.is.net.cable.rogers.com@there> <3C218116.10500@yahoo.com>
Message-ID: <20011222001245.MHAF399509.fep02-mail.bloor.is.net.cable.rogers.com@there>

On Thursday 20 December 2001 01:11 am, Mark Rowe wrote:
> Hi,
>
> Have a read up on the __import__ function in the Python documentation.

That's probably the nicest way that anyone's ever told me to RTFM ;o)

You were right. There's lots of info and I'll make the docs my first stop 
from now on. Yet another way that Python comes with batteries included.

- Chris


From rufmetal@rogers.com  Fri Dec 21 23:58:10 2001
From: rufmetal@rogers.com (Chris Keelan)
Date: Fri, 21 Dec 2001 18:58:10 -0500
Subject: [Tutor] Passing a variable to 'import'
In-Reply-To: <004101c1891b$953a9010$0300a8c0@sun>
References: <20011220043209.JBYO42229.fep01-mail.bloor.is.net.cable.rogers.com@there> <002f01c1891a$58aa8610$0300a8c0@sun> <004101c1891b$953a9010$0300a8c0@sun>
Message-ID: <20011222001352.GFZH342755.fep04-mail.bloor.is.net.cable.rogers.com@there>

On Thursday 20 December 2001 01:00 am, Andy W wrote:
> > Hi Christ
>
> Oh dear, that's got to be the best typo I've ever done.

I've been called worse.

> > You'll want to look at the "imp" module.
> >
> > http://www.python.org/doc/current/lib/module-imp.html
> >
> > Also, take a look at the example for the imp module.
> >
> > http://www.python.org/doc/current/lib/examples-imp.html
> >
> > HTH,

Yes it does. Thanks for the links. They've solved my immediate problem.

- Chris


From prjoshi@ntc.net.np  Sat Dec 22 01:29:39 2001
From: prjoshi@ntc.net.np (Pravin Raj Joshi)
Date: Sat, 22 Dec 2001 06:59:39 +0530
Subject: [Tutor] About Tkinter
Message-ID: <MABBICBJKOGBBPCNIOOBOEJKCCAA.prjoshi@ntc.net.np>

Hi,
I am a new user of Python. I would like to know how to use the clipboard for
temporary data to use in menu items like copy, paste, etc. I looked around
the documentation and archives, but all I could find was reference to
clipboard_append and clipboard_clear.
Thanks.
PRJoshi



From dyoo@hkn.eecs.berkeley.edu  Sat Dec 22 04:05:18 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 21 Dec 2001 20:05:18 -0800 (PST)
Subject: [Tutor] [Q] Install Python in RedHat
In-Reply-To: <010201c18a3d$5fcf3de0$95757e82@visit2>
Message-ID: <Pine.LNX.4.21.0112211958410.23116-100000@hkn.eecs.berkeley.edu>

On Fri, 21 Dec 2001, Young-Jin Lee wrote:

> Hi, I have a question on how to install Python in redhat linux. (I was
> using Python in windows and now I want to use it on linux.)
>
> I downloaded the latest version of Python (2.2c1) into home directory.

(By the way, Python 2.2 final is released today!  Woohoo!  *grin*)


> I, then, did gunzip, tar xvf, ".configure", and make. After I tried to
> run python interpreter after installation, I still got the python
> 1.5.2, not python 2.2.2 rc1.

Did you do 'make install' afterwards?  The 'make' step will compile and
prepare the Python files, but it doesn't copy them to your '/usr/local'
directory until you do 'make install'.  You may need to use your root user
account to do this step.

By default, Python will install in '/usr/local' if you're on a Linux
system.  This can be redirected to a different location if you use the
'--prefix' option during the 'configure' step.


> Where is the right place to install the newer version of Python? What
> should I do to make the newer version to be a default Python
> interpreter for the linux?

You may need to check to see that your PATH puts preference of
'/usr/local/bin' over '/usr/bin'.  Make sure that '/usr/local/bin' comes
first in your PATH, and things should work ok.


Good luck to you.



From toodles@yifan.net  Sat Dec 22 06:12:16 2001
From: toodles@yifan.net (Andy W)
Date: Sat, 22 Dec 2001 14:12:16 +0800
Subject: [Tutor] unpickling a class
References: <Pine.GSO.4.21.0112211645430.3128-100000@isis.visi.com>
Message-ID: <004b01c18aaf$9c3392a0$0300a8c0@sun>

> OK, this make sense. I'm puzzled about the "... extract whatever you
> need from it" part. It doesn't seem as though the attributes that have
> been pickled are automatically unpickled.

Sorry I'm confusing at best. What I meant was, because as
self=pickle.load(...) doesn't work (as you found out), you'd need to
manually take the attributes from the unpickled instance.

The easiest way that I can think of...

> class Portfolio:
>     def __init__(self, file=None):
>         if file is not None:
>             if fileExists(file):
>                 f = open(file, 'r')

                  unpickled_instance = pickle.load(f)
                  self.__dict__.update(unpickled_instance.__dict__) #copies
attributes from unpickled_instance to self

Perhaps there's a better way though. Sorry for giving incomprehensible
answers!

HTH,
Andrew



From dyoo@hkn.eecs.berkeley.edu  Sat Dec 22 06:14:20 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 21 Dec 2001 22:14:20 -0800 (PST)
Subject: [Tutor] hash table
In-Reply-To: <20011221221141.SM13047@there>
Message-ID: <Pine.LNX.4.21.0112212131190.23898-100000@hkn.eecs.berkeley.edu>

On Fri, 21 Dec 2001, Scott wrote:
> 
> Hmm.  I was thinking that a hashtable was like a dictionary, except
> that it was more of an index "decoupled" from the data items.  But
> since, in Python, variables don't designate an actual memory address,
> but instead reference data located *somewhere* in memory, this becomes
> a distinction without a difference, as they say.  Do I have that about
> right?

A dictionary is a container that makes it very quick to look up particular
things.  The "quick lookup" part is the big reason why we have
dictionaries.


Let's pretend, for the moment, that we didn't have dictionaries at all:
Would we still be able to do without them?  Let's try it:

###
defns = [('slang', 'informal language'),
         ('jargon', 'denotes "slangy" language peculiar to hackers'),
         ('techspeak', 'formal technical vocabulary of programming')]
###

Here is a list of terms and their definitions.  We could have done this
with a dictionary:

###
defns_as_a_dict = { 'slang' : 'informal language',
                    'jargon' : 'denotes "slangy" ...'
                    'techspeak' : 'formal technical vocabulary' }
###

but let's keep pretending for a moment that we don't know about
dictionaries yet.  There's one main thing we really need to do with
dictionaries: we need to know how to look things up with them, if we have
some sort of keyword.


How can we look up things in this 'defns' list?

###
def lookup(target, key_value_list):
    for key, value in key_value_list:
        if key == target:
            return value
    raise KeyError, "Can't find %s in key_value_list." % target
###


(Don't worry about the last line if you haven't seen exception handling
yet.)  Now that we have this definition, let's try it out, just to make
sure it sorta works:

###
>>> lookup('slang', defns)                                                      
'informal language'                                                             
>>> lookup('foobar', defns)
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 5, in lookup
KeyError: Can't find foobar in key_value_list.
###


So looking things up works.  And it's not too hard to cook up something
that can add an entry in this structure.  (I have the overwhelming
temptation to say "Exercise for the Reader".  *grin*)


So on a first glance, we don't need dictionaries to record keys and their
values.  It's only after we've played around with these key-value-pair
lists a bit that we notice something: it takes quite a long time to find
anything in there!  In an average sense, when we lookup() through a
key-value-pair list, we have to march through half of the elements to find
anything.  Very very slow.

One strategy we can use to make looking up things faster is to organize
and make sense out of the chaos.  A language dictionary, for example,
organizes things by alphabetical order.  Many English dictionaries, in
fact, make section divisions based on the first letter of a word: there's
the section for words starting with 'A', words starting with 'B', and so
on.  This makes looking up definitions a bit easier, since we have less to
search through.

By putting words in different sections, we can put reasonable limits on
where we can find something.  In normal language, dictionaries have
sections that differ based on their first letter.  In techspeak, Python
dictionaries have "bins" that differ based on their "hash" value.



> Hmm.  I was thinking that a hashtable was like a dictionary, except
> that it was more of an index "decoupled" from the data items.  But

Yes, the index 'keys' don't have to be directly coupled with the data item
'values'.  But the same idea goes with lists:

###
l1 = [0, 1, 2, 3, 4]
l2 = ['four', 'three', 'two', 'one', 'zero']
###

In the first list, it does appear that there's a relationship between
l1[0] and 0 itself, but that's just a coincidence, since in l2, if we grab
at l[1], we get the string 'three'.


I believe that the term "hashtable" and "dictionary" is synonymous; I
can't think of anything that distinguishes one from the other.



> I'm really enjoying tinkering with Python, but sometimes these little
> distinctions get me downright confused!

Keep asking questions on tutor; we'll try to make sure it gets less
confusing over time.  *grin*



From dyoo@hkn.eecs.berkeley.edu  Sat Dec 22 06:18:08 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 21 Dec 2001 22:18:08 -0800 (PST)
Subject: [Tutor] rfc822.rewindbody()
In-Reply-To: <3C241287.B5C87BF5@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112212214520.23898-100000@hkn.eecs.berkeley.edu>

yOn Fri, 21 Dec 2001, Kirk Bailey wrote:

> BTW, here is the new and improved(?) line of intrest:
> 
> 	msg = msg + string.join(l, Message.fp.read())

Looking better.  You don't need to string.join(), since what comes out of
Message.fp.read() will give us back a single string.  That string might
itself contain a bunch of newline characters in it, but it's still just a
string.



From toodles@yifan.net  Sat Dec 22 06:25:42 2001
From: toodles@yifan.net (Andy W)
Date: Sat, 22 Dec 2001 14:25:42 +0800
Subject: [Tutor] About Tkinter
References: <MABBICBJKOGBBPCNIOOBOEJKCCAA.prjoshi@ntc.net.np>
Message-ID: <005401c18ab1$7c6ae7f0$0300a8c0@sun>

Hello,

> Hi,
> I am a new user of Python. I would like to know how to use the clipboard
for
> temporary data to use in menu items like copy, paste, etc. I looked around
> the documentation and archives, but all I could find was reference to
> clipboard_append and clipboard_clear.
> Thanks.
> PRJoshi

I did a search on google, and came up with a couple of different answers.
One was to generate a "<Control-v>", which I can't say I like much, but if
it works for you... :)
I also got this from the python-list archive.

HTH,
Andrew

###

Hi there,
>
>I was wondering how to use the clipboard from Tkinter. I noticed there
>are some methods for clearing and appending to the clipboard, but none
>to retreive something from it... Is there no way at all to retreive
>data from the clipboard using Tkinter? I'm writing a small texteditor
>that has to work cross-platform, so the Tkinter-way would be a lot
>easier than using the windows-clipboard lib. If there's no way to do
>it using Tkinter, though, could you people tell me how to work with
>the clipboard in X? 'Cause I did not find anything about that either
>:)
>
>Thanx a bunch,
>
>Guido Wesdorp, Holland

It is quite simple atlhough not at all obvious. For example from an
event handler:

  def onRightClick(self, event):
    data =  event.widget.selection_get(selection="CLIPBOARD"))
    print data

Bob




From wheelege@hotmail.com  Sat Dec 22 08:21:57 2001
From: wheelege@hotmail.com (Glen Wheeler)
Date: Sat, 22 Dec 2001 19:21:57 +1100
Subject: [Tutor] hash table
References: <Pine.LNX.4.21.0112211203540.14101-100000@hkn.eecs.berkeley.edu>
Message-ID: <DAV37UDMLx0ryCtZFKO00004560@hotmail.com>

> My impression was that a Python dictionary is the same thing as a
> "hashtable".  All things that can be used as keys in a dictionary need to
> support the hash() function:
> 

  Yep...  I just wasn't absolutely sure.  So I kinda left it open :)


From lonetwin@yahoo.com  Sat Dec 22 07:52:22 2001
From: lonetwin@yahoo.com (lonetwin)
Date: Sat, 22 Dec 2001 13:22:22 +0530
Subject: [Tutor] printing out the definition of a func
In-Reply-To: <EHEPLGFHKAPDEDKIBONMMEEECCAA.bwinton@tor.dhs.org>
References: <EHEPLGFHKAPDEDKIBONMMEEECCAA.bwinton@tor.dhs.org>
Message-ID: <01122213222200.04031@mercury.worli>

Hi Blake, Danny,
        Thanx !! ....thanx a lot.....I simply love this language !!! :)
(...and this list)

Blake replied :
> > the idea is, I fire up the intepreter as a sub process to
> > my program, connect the stdin/stdout to the sub-process,
> > with the stdin/stdout of my program
>
> Oh, that sounds really complicated...

     Oh yeah....I realised that today morn, after returning to do what I 
wanted to (btw, that "I won't get sleep" was all just to grab some attention 
and replies....I slept soundly :)).

> Why don't you use something like the "code" module to
> process the Python lines?
>
> http://www.python.org/doc/current/lib/module-code.html
        That looks nice ........but could someone post an example ...I just 
can't figure the "how" or rather the "what-is-it-for" of it.

> I wrote something similar for Jython.  You can find my
> code at: http://tor.dhs.org/~bwinton/Jython.jar
      Never used Jython.......but I will check what it's all about 
........sometime  ;o)

And finally Danny :
> Wait, wait, I spoke too soon.  It is possible!  Take a look at:
>    http://www.python.org/doc/lib/inspect-source.html
      U cool mann !! ......I mean although I'm using python 2.0, I guess even 
if I was using 2.1, I'm sure I wouldn't have found it without help, you sure 
do go out of your way to help. 

> Hope this helps,
> Blake & Danny
Sure does, not what I was hoping to do....but I learned a lot !!!

Thanx
Steve

-- 
----------------------------------------------
I get up each morning, gather my wits.
Pick up the paper, read the obits.
If I'm not there I know I'm not dead.
So I eat a good breakfast and go back to bed.

Oh, how do I know my youth is all spent?
My get-up-and-go has got-up-and-went.
But in spite of it all, I'm able to grin,
And think of the places my get-up has been.
                -- Pete Seeger
----------------------------------------------


From lha2@columbia.edu  Sat Dec 22 16:01:03 2001
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Sat, 22 Dec 2001 11:01:03 -0500
Subject: [Tutor] unpickling a class
References: <Pine.GSO.4.21.0112211106100.6665-100000@isis.visi.com> <003301c18a45$13b8f6f0$0300a8c0@sun>
Message-ID: <3C24AE3F.658C394A@mail.verizon.net>

Andy W wrote:
>     if pickle_file is not None:

Can this be abbreviated to

     if pickle_file:

?


From toodles@yifan.net  Sat Dec 22 16:29:13 2001
From: toodles@yifan.net (Andy W)
Date: Sun, 23 Dec 2001 00:29:13 +0800
Subject: [Tutor] unpickling a class
References: <Pine.GSO.4.21.0112211106100.6665-100000@isis.visi.com> <003301c18a45$13b8f6f0$0300a8c0@sun> <3C24AE3F.658C394A@mail.verizon.net>
Message-ID: <000501c18b05$cc3cab70$0300a8c0@sun>

> >     if pickle_file is not None:
>
> Can this be abbreviated to
>
>      if pickle_file:
>
> ?

Yep. I think I gained "is not None" through osmosis...I see it in a lot of
programs, that argue its use for readability/comprehensibility.
It's certainly not necessary though.

Andy

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



From Daniel.Kinnaer@Advalvas.be  Sat Dec 22 17:49:36 2001
From: Daniel.Kinnaer@Advalvas.be (Daniel Kinnaer)
Date: Sat, 22 Dec 2001 18:49:36 +0100
Subject: [Tutor] ExpandFileName
Message-ID: <LPBBLJLBPKOAHOOJGJIJIEPNDBAA.Daniel.Kinnaer@Advalvas.be>

Hello,

In Delphi there's this lovely function called ExpandFileName, which converts
the relative file name into a fully qualified path name by merging in the
current drive and directory. I suppose in Python there's the same kind of
function, but, unfortunately, I cannot find it (using python 2.2).  Can
anyone help me with this?

Thanks,

Daniel



From karthikg@aztec.soft.net  Sat Dec 22 18:12:03 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Sat, 22 Dec 2001 23:42:03 +0530
Subject: [Tutor] ExpandFileName
In-Reply-To: <LPBBLJLBPKOAHOOJGJIJIEPNDBAA.Daniel.Kinnaer@Advalvas.be>
Message-ID: <NEBBJNMDEKBIBCMCNMBDIEDDCMAA.karthikg@aztec.soft.net>

import os.path
os.path.abspath(fileName)

ae you looking for this?

karthik

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Daniel Kinnaer
Sent: Saturday, December 22, 2001 11:20 PM
To: tutor@python.org
Subject: [Tutor] ExpandFileName



Hello,

In Delphi there's this lovely function called ExpandFileName, which converts
the relative file name into a fully qualified path name by merging in the
current drive and directory. I suppose in Python there's the same kind of
function, but, unfortunately, I cannot find it (using python 2.2).  Can
anyone help me with this?

Thanks,

Daniel


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


From gary@stokeson.freeserve.co.uk  Sat Dec 22 10:46:43 2001
From: gary@stokeson.freeserve.co.uk (gary)
Date: Sat, 22 Dec 2001 10:46:43 -0000
Subject: [Tutor] concerned
Message-ID: <006401c18ad5$f3d6eae0$8e80883e@oemcomputer>

This is a multi-part message in MIME format.

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

Hello, I am a  little concerned regarding an email I recieved AND opened =
from a Pijus Virketis SUBJECT: Re: [Tutor]Creating a path for Python to =
walk along (this is the subject title of an email I sent to Python Tutor =
some time ago.
On replying, to the email (Pijus') I recieved this answer:

This message was created automatically by mail delivery software:

A message that you sent could not be delivered to one or more of its
recipients. The following address(es) failed:

  ddjupdate@drdobbs.email-publisher.com:
    This message has been rejected because it has
an apparently executable attachment "NEWS_DOC.DOC.scr"
This is a virus prevention measure.
If you meant to send this file then please
package it up as a zip file and resend it.

Have I let a virus in, then, d'ya think as a result of this.
Please say that Pijus Virketis is a bona fida member of your team!



------=_NextPart_000_0061_01C18AD5.F2228420
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.2462.0" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hello, I am a&nbsp; little concerned =
regarding an=20
email I recieved AND opened from a Pijus Virketis SUBJECT: Re: =
[Tutor]Creating a=20
path for Python to walk along (this is the subject title of an email I =
sent to=20
Python Tutor some time ago.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>On replying, to the email (Pijus') I =
recieved this=20
answer:</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV>This message was created automatically by mail delivery =
software:<BR><BR>A=20
message that you sent could not be delivered to one or more of=20
its<BR>recipients. The following address(es) failed:<BR><BR>&nbsp; <A=20
href=3D"mailto:ddjupdate@drdobbs.email-publisher.com">ddjupdate@drdobbs.e=
mail-publisher.com</A>:<BR>&nbsp;&nbsp;&nbsp;=20
This message has been rejected because it has<BR>an apparently =
executable=20
attachment "NEWS_DOC.DOC.scr"<BR>This is a virus prevention =
measure.<BR>If you=20
meant to send this file then please<BR>package it up as a zip file and =
resend=20
it.</DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Have I let a virus in, then, d'ya think =
as a result=20
of this.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Please say that Pijus Virketis is a =
bona fida=20
member of your team!</FONT><BR><BR></DIV></BODY></HTML>

------=_NextPart_000_0061_01C18AD5.F2228420--



From virketis@fas.harvard.edu  Sat Dec 22 20:15:55 2001
From: virketis@fas.harvard.edu (Pijus Virketis)
Date: Sat, 22 Dec 2001 22:15:55 +0200
Subject: [Tutor] concerned
References: <006401c18ad5$f3d6eae0$8e80883e@oemcomputer>
Message-ID: <001701c18b25$7911b920$100f3bd4@virketis2>

This is a multi-part message in MIME format.

------=_NextPart_000_0014_01C18B36.39F27390
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

   Please say that Pijus Virketis is a bona fida member of your team!

I dunno about "bona fida", but I would like to flatter myself and think =
that I am some sort of a member of the tutor list team (albeit often the =
one most often on the receiving end). :) A few hours ago my new box, on =
which I had not had time to replace Windows with Mandrake, got infected =
with a worm, and it mailed itself out right and left. I appologise for =
this lapse of list security. :( Thankfully, the thing does not seem to =
cause much damage (besides aggravation) and can be caught by any =
anti-virus software updated in the last two weeks.=20

Cheers and happy Xmass!

-P



------=_NextPart_000_0014_01C18B36.39F27390
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>&nbsp;&nbsp;&nbsp;</FONT><FONT =
face=3DArial=20
size=3D2>Please say that Pijus Virketis is a bona fida member of your=20
team!</FONT><BR></DIV>
<DIV><FONT face=3DArial size=3D2>I dunno about "bona fida", but I would =
like to=20
flatter myself and think that I am some sort of a member of the tutor =
list team=20
(albeit often the one most often on the receiving end). :) A few hours =
ago my=20
new box, on which I had not had time to replace Windows with Mandrake, =
got=20
infected with a worm, and it mailed itself out right and left. I =
appologise for=20
this lapse of list security. :(&nbsp;Thankfully, the thing does not seem =
to=20
cause much damage (besides aggravation) and can be caught by any =
anti-virus=20
software updated in the last two weeks. </FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Cheers and happy Xmass!</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>-P</FONT></DIV>
<DIV><BR></DIV></BODY></HTML>

------=_NextPart_000_0014_01C18B36.39F27390--



From jrm@videotron.ca  Sat Dec 22 13:37:19 2001
From: jrm@videotron.ca (Jean Montambeault)
Date: Sat, 22 Dec 2001 15:37:19 +0200
Subject: [Tutor] concerned
References: <006401c18ad5$f3d6eae0$8e80883e@oemcomputer> <001701c18b25$7911b920$100f3bd4@virketis2>
Message-ID: <000e01c18aed$c774fe20$0100c0a8@videotron.ca>

----- Original Message -----
From: "Pijus Virketis" <virketis@fas.harvard.edu>
To: "gary" <gary@stokeson.freeserve.co.uk>
Cc: <tutor@python.org>
Sent: Saturday, December 22, 2001 10:15 PM
Subject: Re: [Tutor] concerned


   Please say that Pijus Virketis is a bona fida member of your team!

I dunno about "bona fida", but I would like to flatter myself and think that
I am some sort of a member of the tutor list team (albeit often the one most
often on the receiving end). :) A few hours ago my new box, on which I had
not had time to replace Windows with Mandrake, got infected with a worm, and
it mailed itself out right and left. I appologise for this lapse of list
security. :( Thankfully, the thing does not seem to cause much damage
(besides aggravation) and can be caught by any anti-virus software updated
in the last two weeks.

Cheers and happy Xmass!

-P

Those things happens but they are preventable.
I got the infected post myself almost at the same time I received another
wormy email, from a personnal friend this time. So it was a massive attack.
The security in Outlook Express is set to a maximum here and .scr file won't
open by themselves. That was protection enough.









From kalle@gnupung.net  Sat Dec 22 23:56:05 2001
From: kalle@gnupung.net (Kalle Svensson)
Date: Sun, 23 Dec 2001 00:56:05 +0100
Subject: [Tutor] ExpandFileName
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDIEDDCMAA.karthikg@aztec.soft.net>
References: <LPBBLJLBPKOAHOOJGJIJIEPNDBAA.Daniel.Kinnaer@Advalvas.be> <NEBBJNMDEKBIBCMCNMBDIEDDCMAA.karthikg@aztec.soft.net>
Message-ID: <20011223005605.B28485@sandra.lysator.liu.se>

[Daniel Kinnaer]
> In Delphi there's this lovely function called ExpandFileName, which converts
> the relative file name into a fully qualified path name by merging in the
> current drive and directory. I suppose in Python there's the same kind of
> function, but, unfortunately, I cannot find it (using python 2.2).  Can
> anyone help me with this?

[Karthik Gurumurthy]
> import os.path
> os.path.abspath(fileName)

os.path is full of nice functions.  shutil is another good module to know
about, as is glob.

The documentation, as always, available on
http://www.python.org/doc/current/lib/

Peace,
  Kalle
-- 
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]


From deliberatus@my995internet.com  Sun Dec 23 00:55:26 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sat, 22 Dec 2001 19:55:26 -0500
Subject: [Tutor] IT is Finished
Message-ID: <3C252B7E.1DE40175@my995internet.com>

Well, maybe a little polishing, but it is a working unit.

http://www.howlermonkey.net/TLpost.shtml

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From kev@sat.net  Sun Dec 23 05:59:34 2001
From: kev@sat.net (Kevin McCormick)
Date: Sat, 22 Dec 2001 23:59:34 -0600
Subject: [Tutor] classes and names
Message-ID: <3C2572C6.2040101@sat.net>

Greetings all!  I am writing a module of spreadsheet type date functions 
and I would like to do some things with the function names.   Some of 
the functions are written really for supporting the actually useful 
functions and I don't quite understand the __function__(arg), 
__function(arg), and _function(arg) conventions. Also, it would be 
useful to set the main date function as a class object, since my design 
copies the time module and puts date information into a tuple.  I want 
all this in the same file too, so I am asking for a lot. Lastly, an 
exceptions class would be really useful.  I have read all the basic 
tutorial stuff on classes, but what would be really cool is a simple 
class that has this tuple and a way of being identified by my module 
level functions.

What I think I want would be something like:

class datefuncExceptions:
     # whatever goes into one of these type classes
     # like invalid argument, function x choked on arg y, etc

class dateObject(date, arg2):
     # call module functions to interpret date argument

     # attributes are tuple (y, m, d, serial, day)

def function(arg):
     #
     # val = __evaluate(arg)
     #
     # perform function tasks with val
     #
     # errors are datefuncExceptions

def __evaluate(arg):
     # if arg is dateObject:
           pass it back
     # else:
           decipher arg and resolve into dateObject
     #
     # return val

The idea is to understand many date formats as arguments and provide 
functions like yearfrac, days360, workdays, daysbetween, weeksbetween, 
eomonth, etc. at the module level so the class objects are small and two 
  can easily be used as function arguments.

Thanks for any comments.
Kevin



From adidas69_59@hotmail.com  Sun Dec 23 07:16:33 2001
From: adidas69_59@hotmail.com (Shawn Long)
Date: Sun, 23 Dec 2001 01:16:33 -0600
Subject: [Tutor] (no subject)
Message-ID: <F921t93Lx9w5dRuYnZl00006ee6@hotmail.com>

Adidas69_59@hotmail.com



_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp.



From taenchiki@hotmail.com  Sun Dec 23 17:04:23 2001
From: taenchiki@hotmail.com (Taenchiki Said)
Date: Sun, 23 Dec 2001 17:04:23
Subject: [Tutor] writing a script file in Python - Help please
Message-ID: <F19lJh0sMv08uhCJ0Mz00008d2a@hotmail.com>


Hi there,

I'm very new in Python and programming in general. I just started a 
self-learning on how to program. I was learning C++ for 3 months now but I 
decided to switch to Python because it appears much easier.

Could you please tell me how to write a simple script, save it and run it in 
Python 2.2 in a windows or DOS environnement?

Thanks in advance for helping me get started.

S. Taenchiki

_________________________________________________________________
Chat with friends online, try MSN Messenger: http://messenger.msn.com



From lkvam@venix.com  Sun Dec 23 17:07:16 2001
From: lkvam@venix.com (Lloyd Kvam)
Date: Sun, 23 Dec 2001 12:07:16 -0500
Subject: [Tutor] classes and names
References: <3C2572C6.2040101@sat.net>
Message-ID: <3C260F44.5060701@venix.com>

For date time processing you should probably look at mxDateTime.  It
is not part of the Python distribution.

http://www.lemburg.com/files/python/mxDateTime.html

It is VERY comprehensive.

Kevin McCormick wrote:

> Greetings all!  I am writing a module of spreadsheet type date functions 
> and I would like to do some things with the function names.   Some of 
> the functions are written really for supporting the actually useful 
> functions and I don't quite understand the __function__(arg), 
> __function(arg), and _function(arg) conventions. Also, it would be 
> useful to set the main date function as a class object, since my design 
> copies the time module and puts date information into a tuple.  I want 
> all this in the same file too, so I am asking for a lot. Lastly, an 
> exceptions class would be really useful.  I have read all the basic 
> tutorial stuff on classes, but what would be really cool is a simple 
> class that has this tuple and a way of being identified by my module 
> level functions.
> 
> What I think I want would be something like:
> 
> class datefuncExceptions:
>     # whatever goes into one of these type classes
>     # like invalid argument, function x choked on arg y, etc
> 
> class dateObject(date, arg2):
>     # call module functions to interpret date argument
> 
>     # attributes are tuple (y, m, d, serial, day)
> 
> def function(arg):
>     #
>     # val = __evaluate(arg)
>     #
>     # perform function tasks with val
>     #
>     # errors are datefuncExceptions
> 
> def __evaluate(arg):
>     # if arg is dateObject:
>           pass it back
>     # else:
>           decipher arg and resolve into dateObject
>     #
>     # return val
> 
> The idea is to understand many date formats as arguments and provide 
> functions like yearfrac, days360, workdays, daysbetween, weeksbetween, 
> eomonth, etc. at the module level so the class objects are small and two 
>  can easily be used as function arguments.
> 
> Thanks for any comments.
> Kevin
> 
> 
> _______________________________________________
> 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  Sun Dec 23 21:05:51 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 23 Dec 2001 13:05:51 -0800 (PST)
Subject: [Tutor] writing a script file in Python - Help please
In-Reply-To: <F19lJh0sMv08uhCJ0Mz00008d2a@hotmail.com>
Message-ID: <Pine.LNX.4.21.0112231300340.21970-100000@hkn.eecs.berkeley.edu>

On Sun, 23 Dec 2001, Taenchiki Said wrote:

> I'm very new in Python and programming in general. I just started a
> self-learning on how to program.

Welcome aboard!  Please feel free to ask questions here; we'll do what we
can to help.


> I was learning C++ for 3 months now but I decided to switch to Python
> because it appears much easier.
> 
> Could you please tell me how to write a simple script, save it and run
> it in Python 2.2 in a windows or DOS environnement?

Sure!  You'll want to use a text editor to write your Python program.  
Notepad is usable, but not recommended, since it isn't really tailored for
programming.  There is another text editor called IDLE that should be
installed when you installed Python 2.2, and it supports Python
programming very well.

I have a small introduction to IDLE here (I hope it isn't obsolete yet!):

    http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro

Good luck to you.



From apython101@yahoo.com  Sun Dec 23 21:18:25 2001
From: apython101@yahoo.com (john public)
Date: Sun, 23 Dec 2001 13:18:25 -0800 (PST)
Subject: [Tutor] books
Message-ID: <20011223211825.3048.qmail@web21103.mail.yahoo.com>

--0-516737577-1009142305=:1253
Content-Type: text/plain; charset=us-ascii


I am a newbie programmer learning Python. I live in Eastern Europe and no books on Python are available in English. My goal is to learn to be a competent programmer in Python in a year. I would also like to be familiar with some Jpython and XML by that time. I am going to America in two weeks and will by some books.

 These books and the Internet will be my only teachers.

Most important in my library will be the books that get me from beggining level to knowing something. Any and all comments welcome from Newbie and advanced progammers alike. 

I am definitely getting:

Progamming Python by Mark Lutz

Learning Python by       Mark Lutz

Python Pocket reference by Mark Lutz

I am thinking of getting:

Python Essential reference by David Beazley 

Python and XML by Christopher Jones

XML processing with Perl,Python, and PHP by Martin Brown

Python pocket reference Mark Lutz

Python standard library by Lundh

 Thanx!!



---------------------------------
Do You Yahoo!?
Send your FREE holiday greetings online at Yahoo! Greetings.
--0-516737577-1009142305=:1253
Content-Type: text/html; charset=us-ascii

<P>I am a newbie programmer learning Python. I live in Eastern Europe and no books on Python are available in English. My goal is to learn to be a competent programmer in Python in a year. I would also like to be familiar with some Jpython and XML by that time. I am going to America in two weeks and will by some books.</P>
<P>&nbsp;These books and the Internet will be my only teachers.</P>
<P>Most important in my library will be the books that get me from beggining level to knowing something. Any and all comments welcome from Newbie and advanced progammers alike. </P>
<P>I am definitely getting:</P>
<P>Progamming Python by Mark Lutz</P>
<P>Learning Python by&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Mark Lutz</P>
<P>Python Pocket reference by Mark Lutz</P>
<P>I am thinking of getting:</P>
<P>Python Essential reference by David Beazley </P>
<P>Python and XML by Christopher Jones</P>
<P>XML processing with Perl,Python, and PHP by Martin Brown</P>
<P>Python pocket reference Mark Lutz</P>
<P>Python standard library by Lundh</P>
<P>&nbsp;Thanx!!</P><p><br><hr size=1><b>Do You Yahoo!?</b><br>
Send your FREE holiday greetings online at <a href="http://rd.yahoo.com/mail_us/tag/?http://greetings.yahoo.com/">Yahoo! Greetings</a>.
--0-516737577-1009142305=:1253--


From dyoo@hkn.eecs.berkeley.edu  Sun Dec 23 21:36:08 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 23 Dec 2001 13:36:08 -0800 (PST)
Subject: [Tutor] classes and names   [__function__(arg)]
In-Reply-To: <3C2572C6.2040101@sat.net>
Message-ID: <Pine.LNX.4.21.0112231306440.21970-100000@hkn.eecs.berkeley.edu>

On Sat, 22 Dec 2001, Kevin McCormick wrote:

> Greetings all!  I am writing a module of spreadsheet type date
> functions and I would like to do some things with the function names.  
> Some of the functions are written really for supporting the actually
> useful functions and I don't quite understand the __function__(arg),

The '__function__(arg)' stuff are "magical" functions --- there are a
preset number of them, described here:

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

The reason they're magical is because they get called when we do unusual
stuff.  For example, let's say that we're trying to represent
Red/Green/Blue color triples in some program:

###
>>> class Color:
...     def __init__(self, r, g, b):
...         self.r, self.g, self.b = r, g, b
...     def add(self, other):
...         return Color(self.r + other.r,
...                      self.g + other.g,
...                      self.b + other.b)
... 
>>> c1 = Color(0, 0, 0)
>>> c2 = Color(3, 4, 7)
>>> c3 = c1.add(c2)
>>> c3.r, c3.g, c3.b
(3, 4, 7)
###

It might be nice to be able to say something like:

###
>>> c3 = c1 + c2
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: __add__ nor __radd__ defined for these operands
###

but, as the error message suggests, Python doesn't know what it means to
'+' two things together... that is, until we define an __add__ method:

###
>>> class Color:
...     def __init__(self, r, g, b):
...         self.r, self.g, self.b = r, g, b
...     def add(self, other):
...         return Color(self.r + other.r,
...                      self.g + other.g,
...                      self.b + other.b)
...     def __add__(self, other): return self.add(other)
... 
>>> c1 = Color(1, 2, 3)
>>> c2 = Color(4, 5, 6)
>>> c3 = c1 + c2
>>> c3.r, c3.g, c3.b
(5, 7, 9)
###

And now it works!  "__function__(arg)" functions are hooks to make things
like addition look more natural.  Take a look at the documentation on the
link above, and you'll see a bunch of interesting stuff.  (In the C++
language, we're "overloading operators".)


> __function(arg), and _function(arg) conventions.

The single underscore '_function(arg)', is meant to tell someone reading
the code to not fiddle around with it too much --- a '_function(arg)'
implies to a person that it's supposed to be for internal use only by the
class.

For example, if we were to write a Fraction class:

###
def gcd(a, b):
    if b == 0: return a
    return gcd(b, a % b)

class Fraction:                                                             
    def __init__(self, n, d):
        self.n, self.d = n, d
        self._reduce()

    def __add__(self, other):
        return Fraction(self.n * other.d + other.n*self.d,
                        self.d * other.d)
    def _reduce(self):
        denom = gcd(self.n, self.d)
        self.n = self.n / denom
        self.d = self.d / denom
###

The single leading underscore in '_reduce' tells someone not to call
_reduce() explicitly; it's a small utility member of the Fraction class,
and we shouldn't have to call it ourselves when using a Fraction.

'__function(arg)" implies the same kind of protection, but doubly so: it
gets Python to mangle up the function names so that it becomes very hard
for the outside to directly call '__function(arg)'.  To tell the truth,
I've never reallly felt the need to use this.


Hope this helps!



From glingl@aon.at  Sun Dec 23 22:24:35 2001
From: glingl@aon.at (Gregor Lingl)
Date: Sun, 23 Dec 2001 23:24:35 +0100
Subject: [Tutor] books
References: <20011223211825.3048.qmail@web21103.mail.yahoo.com>
Message-ID: <001701c18c00$9a5820c0$1664a8c0@mega>

Dear Public! (Is this a name from Eastern Europe?)

I'd like to direct you towards two or three online-resources:

First, study the descriptions and links to turorials at
the Python Website: http://www.python.org/doc/Intros.html

I consider

How to Think Like a Computer Scientist
at http://www.ibiblio.org/obp/

to be especially valuable.

You also may have a look at

http://www.python.org/doc/NonEnglish.html

which contains links to several online-publications in
non-English, also slavic languages. For instance

Jak se nauèit programovat is a translation of Alan Gauld's Learning to
Program.
at http://www.freenetpages.co.uk/hp/alan.gauld/czech/


----- Original Message -----
From: john public
To: tutor@python.org
Sent: Sunday, December 23, 2001 10:18 PM
Subject: [Tutor] books


I am a newbie programmer learning Python. ....
Most important in my library will be the books that get me from beggining
level to knowing something.

Besides the certainly good books you mention below,
I recommend you strongly ta have a look at

Python: Visual QuickStart Guide by Chris Fehily

I had a look at it in a bookstore an I found it
- despite its somewhat strange title (a series?) -
very thoroughly guiding the reader to develop
the habit of exploring the Python language
interactively.

It covers 'Core-Python' only, that means only the
fundamentals of the language, but this in a very
complete, readable way.

In my opinion books always are at least to 50% a
matter of taste and reading habits - so you always
have to decide yourself if you could learn and
work with it well.

Hav a nice trip to America (and its book stores)

Gregor




From apython101@yahoo.com  Mon Dec 24 01:07:12 2001
From: apython101@yahoo.com (john public)
Date: Sun, 23 Dec 2001 17:07:12 -0800 (PST)
Subject: [Tutor] more-books and Zope
Message-ID: <20011224010712.43933.qmail@web21104.mail.yahoo.com>

--0-1935548789-1009156032=:43239
Content-Type: text/plain; charset=us-ascii


I had a look at it in a bookstore an I found it
- despite its somewhat strange title (a series?) -
very thoroughly guiding the reader to develop
the habit of exploring the Python language
interactively.

It covers 'Core-Python' only, that means only the
fundamentals of the language, but this in a very
complete, readable way.
*************************************************************************
EXACTLY WHAT I WAS LOOOKING 4!

And of the two customers who reviewed it on Amazon both gave it  five stars and ranted about how good and readable it was. 

Thanx Gregor! Do U know anything about Zope? My goal with in a year is to make at least $10 an hour  programming never leaving my home and have fun doing it. I figure one thing I might end up doing is building web pages. I noticed a book on Zope when I looked up Fehily's book. If I am programming in Python is Zope a good thing to learn for building web pages? If so what books do you recommend for Newbies? 

 I am an American. I am in the witness protection program. They put me in suspended animation for 20 years and then I woke up in Bulgaria. At least this is what my landlord tells me. I figure it is true since I get a monthly check from the State Department. I can't remember much. I wish I knew who I testified against. I hate it when that happens!

John Q. Public



---------------------------------
Do You Yahoo!?
Send your FREE holiday greetings online at Yahoo! Greetings.
--0-1935548789-1009156032=:43239
Content-Type: text/html; charset=us-ascii

<P>I had a look at it in a bookstore an I found it<BR>- despite its somewhat strange title (a series?) -<BR>very thoroughly guiding the reader to develop<BR>the habit of exploring the Python language<BR>interactively.<BR><BR>It covers 'Core-Python' only, that means only the<BR>fundamentals of the language, but this in a very<BR>complete, readable way.<BR>*************************************************************************<BR>EXACTLY WHAT I WAS LOOOKING 4!</P>
<P>And of the two customers who reviewed it on Amazon both gave it&nbsp; five stars and ranted about how good and readable it was. </P>
<P>Thanx Gregor! Do U know anything about Zope? My goal with in a year is to make at least $10 an hour&nbsp; programming never leaving my home and have fun doing it. I figure one thing I might end up doing is building web pages. I noticed a book on Zope when I looked up Fehily's book. If I am programming in Python is Zope a good thing to learn for building web pages? If so what books do you recommend for Newbies? </P>
<P>&nbsp;I am an American. I&nbsp;am in the witness protection program. They put me in suspended animation for 20 years and then I woke up in Bulgaria. At least this is what my landlord tells me. I figure it is true since I get a monthly check from the&nbsp;State Department. I can't remember much. I wish I knew who I testified against. I hate it when that happens!</P>
<P>John Q. Public</P><p><br><hr size=1><b>Do You Yahoo!?</b><br>
Send your FREE holiday greetings online at <a href="http://rd.yahoo.com/mail_us/tag/?http://greetings.yahoo.com/">Yahoo! Greetings</a>.
--0-1935548789-1009156032=:43239--


From alan.gauld@bt.com  Mon Dec 24 10:51:00 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 24 Dec 2001 10:51:00 -0000
Subject: [Tutor] An hour's talk on python...Suggestions required
 (fro m a newbie)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1F9@mbtlipnt02.btlabs.bt.co.uk>

> Ours is mainly a java shop.

So definitely include Jython and how you can use all 
those familiar Java class libraries while writing the 
code in the much higher level Python...

Some examples should quite easily show a 30-50% code 
reduction in Jython vv Java... Thus a perfect prototyping 
language for Java heads.

> I was planning to take an introductory session on python.

There are several slide presentations on the python web site
that you could 'learn from' - ie plagiarise...

> w'd want to try it out unless and otherwise they can see lots of
> supporting tools and libraries.

How about all the Java stuff plus the 100+ standard modules 
plus another 100 or so on the web?

> 1. functional programming in python

Good article on the IBM site

> 2. about new features that have been included in 2.2?

Read the 'whats new papers'

> 3. threading as for as tools/libraries are concerned,

Not quite sure what you mean here...

> 4. GUI : Tkinter

Yes, Or AWT if they want to keep with Java
Or pyQt/PyGTK if they are Linux fans.

Or even all three to show how easy core functionality 
can be ported over different GUIs. - a bit more work 
there tho'

> 5. xml?? : the one which ships with standard module or something else?
> 6. cgi:

If you must, but web stuff is a bit passe now.
Might be better looking at SOAP or XML/RPC.
Python is blindingly good at the latter compared to Java!

> But i want to develop some interest here @ my place.
> Any suggestion w'd be of great help to me.

IMHO The real advantages of Python are that it is a 
scripting tool that can handle large projects so you 
get all the advantages of scripting languages like Perl
but with the control and organisation of compiled 
languages like C++/Java/Delphi etc.

Its brilliant for prototyping and for tool building.
And as your list of topics proves, extremely versatile.

Alan G.


From alan.gauld@bt.com  Mon Dec 24 11:47:49 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 24 Dec 2001 11:47:49 -0000
Subject: [Tutor] printing out the definition of a func [dis/inspect]
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1FA@mbtlipnt02.btlabs.bt.co.uk>

> Wait, wait, I spoke too soon.  It is possible!  Take a look at:
> 
>     http://www.python.org/doc/lib/inspect-source.html


Version 2.1 onwards unfortunately but OTOH the fact it's 
possible is amazing. Python blows me away once more.

BTW It's the inspect module you need, and it only works on 
files not the interpreter:

>>> import inspect
>>> import foo
>>> print inspect.getsource(foo)
def foo():
  print 'hello'
  return 42

def bar():
   print 'bar'
   return 42 * 42

>>> print inspect.getsource(foo.foo)
def foo():
  print 'hello'
  return 42

>>>

Well spotted Danny.

Alan G.


From alan.gauld@bt.com  Mon Dec 24 16:19:07 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 24 Dec 2001 16:19:07 -0000
Subject: FW: [Tutor] printing out the definition of a func [dis/inspect]
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C1FD@mbtlipnt02.btlabs.bt.co.uk>

Oops, meant to hit reply-all...

> -----Original Message-----
> To: 'Kirk Bailey';
> Subject: RE: [Tutor] printing out the definition of a func 
> 
> > Pardon this humble novice, but is the interpeter not a file?
> 
> The interpreter itself is a file. What I meant was the code
> that you type at the Python interactive prompt.
> 
> Thus:
> 
> >>> import inspect
> >>> def foo():
> ...    print 'foo'
> ...
> >>> print inspect.getsource(foo)
> 
> will generate an error. It only works if the code for foo is 
> in a file external to the interpreter.
> 
> Alan G.
> 
> > > BTW It's the inspect module you need, and it only works on
> > > files not the interpreter:
> > > 
> > > >>> import inspect
> > > >>> import foo
> > > >>> print inspect.getsource(foo)
> > > def foo():
> > >   print 'hello'
> > >   return 42
> > > 
> > > def bar():
> > >    print 'bar'
> > >    return 42 * 42
> > > 
> > > >>> print inspect.getsource(foo.foo)
> > > def foo():
> > >   print 'hello'
> > >   return 42
> > > 
> > > >>>
> > > 
> > > Well spotted Danny.
> > > 
> > > Alan G.
> > > 
> > > _______________________________________________
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > 
> 


From alan.gauld@bt.com  Mon Dec 24 17:10:29 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 24 Dec 2001 17:10:29 -0000
Subject: [Tutor] books
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C201@mbtlipnt02.btlabs.bt.co.uk>

------_=_NextPart_001_01C18C9D.E37DA160
Content-type: text/plain; charset="iso-8859-1"

>  I am a newbie programmer learning Python. I live in Eastern Europe  
>  and no books on Python are available in English.  
 
Do Amazon not operate in Eastern Europe? They can provide most 
books most anywhere... It takes a few weeks but even including 
postage it usually works out no more than buying in a high 
street bookshop - often less!
 
I am definitely getting:

Progamming Python by Mark Lutz

Learning Python by  Mark Lutz 

Both good books.

Python Pocket reference by Mark Lutz 

This is now seriously out of date and less useful.

Get

 Python Essential reference by David Beazley  

this instead. Its the best reference book on Python 
at the moment IMHO.

Python and XML by Christopher Jones

XML processing with Perl,Python, and PHP by Martin Brown 

I can't comment on these... 

Python standard library by Lundh 

Similar to Beazley in some ways but more cookbook style. 
Personally I just search google news archive... 

Lundh is a fount of knowlege but in do wish he'd 
completed and published his Tkinter stuff instead 
of this one... We are still crying out for a decent 
intro to Tkinter in book form, Grayson not 
withstanding.

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_01C18C9D.E37DA160
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=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>&gt; &nbsp;</FONT></SPAN>I am a newbie programmer learning Python. I live 
in Eastern Europe&nbsp;<SPAN class=160261017-24122001><FONT face="Courier New" 
color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>and no books on Python are available in 
English.&nbsp;<SPAN class=160261017-24122001><FONT face="Courier New" 
color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>Do Amazon not operate in Eastern Europe? They can provide most 
</FONT></SPAN></DIV>
<DIV><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>books most anywhere... It takes a few weeks but even including 
</FONT></SPAN></DIV>
<DIV><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>postage it usually works out no more than buying in a high 
</FONT></SPAN></DIV>
<DIV><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>street bookshop - often less!</FONT></SPAN></DIV>
<DIV><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV>I am definitely getting:</DIV>
<BLOCKQUOTE 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid">
  <P>Progamming Python by Mark Lutz</P>
  <P>Learning Python by&nbsp;&nbsp;Mark Lutz<SPAN class=160261017-24122001><FONT 
  face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></P></BLOCKQUOTE>
<P><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>Both good books.</FONT></SPAN></P>
<BLOCKQUOTE 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid">
  <P>Python Pocket reference by Mark Lutz<SPAN class=160261017-24122001><FONT 
  face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></P></BLOCKQUOTE>
<P><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>This is now seriously out of date and less useful.</FONT></SPAN></P>
<P><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>Get</FONT></SPAN></P>
<BLOCKQUOTE 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid">
  <P><SPAN class=160261017-24122001>&nbsp;</SPAN>Python Essential reference by 
  David Beazley&nbsp;<SPAN class=160261017-24122001><FONT face="Courier New" 
  color=#0000ff size=2>&nbsp;</FONT></SPAN></P></BLOCKQUOTE>
<P><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>this instead. Its the best reference book </FONT></SPAN><SPAN 
class=160261017-24122001><FONT face="Courier New" color=#0000ff size=2>on Python 
<BR>at the moment IMHO.</FONT></SPAN></P>
<BLOCKQUOTE 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid">
  <P>Python and XML by Christopher Jones</P>
  <P>XML processing with Perl,Python, and PHP by Martin Brown<SPAN 
  class=160261017-24122001><FONT face="Courier New" color=#0000ff 
  size=2>&nbsp;</FONT></SPAN></P></BLOCKQUOTE>
<P><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>I&nbsp;can't comment on these...</FONT>&nbsp;</SPAN></P>
<BLOCKQUOTE 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid">
  <P>Python standard library by Lundh<SPAN class=160261017-24122001><FONT 
  face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></P></BLOCKQUOTE>
<P><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>Similar to Beazley in some ways but more cookbook style. 
<BR></FONT></SPAN><SPAN class=160261017-24122001><FONT face="Courier New" 
color=#0000ff size=2>Personally I just search google news 
archive...</FONT>&nbsp;</SPAN></P>
<P><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>Lundh is a fount of knowlege but in do wish he'd <BR></FONT></SPAN><SPAN 
class=160261017-24122001><FONT face="Courier New" color=#0000ff size=2>completed 
and published his Tkinter stuff instead <BR></FONT></SPAN><SPAN 
class=160261017-24122001><FONT face="Courier New" color=#0000ff size=2>of this 
one... We are still crying out for a decent <BR></FONT></SPAN><SPAN 
class=160261017-24122001><FONT face="Courier New" color=#0000ff size=2>intro to 
Tkinter in book form, Grayson not <BR></FONT></SPAN><SPAN 
class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2>withstanding.</FONT></SPAN></P>
<P><SPAN class=160261017-24122001><FONT face="Courier New" color=#0000ff 
size=2><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>
<P>&nbsp;</FONT></SPAN></P></BODY></HTML>

------_=_NextPart_001_01C18C9D.E37DA160--


From sentinel805@netscape.net  Mon Dec 24 18:22:08 2001
From: sentinel805@netscape.net (nova812)
Date: Mon, 24 Dec 2001 13:22:08 -0500
Subject: [Tutor] Just for fun I wrote
Message-ID: <3C277250.6020809@netscape.net>

I wrote this to help me ( a long time BASIC programmer) convert to python.
In case this helps any one else start programming with python, here is 
what I wrote.
It is some basic BASIC string functions writen in python.  these 
functions are..
left, right, mid, instr, ucase.

Of course I already know about the String lib that already comes with 
python,  this
was a learning exercise for me.  here is the code.


http://www.geocities.com/swinux/bString.html


Ron




From sentinel805@netscape.net  Mon Dec 24 18:30:57 2001
From: sentinel805@netscape.net (nova812)
Date: Mon, 24 Dec 2001 13:30:57 -0500
Subject: [Tutor] A little help please
Message-ID: <3C277461.2010401@netscape.net>

I'm in need of a function that will work on both a linux box and a 
windows box that,
from the command line, will detect a key hit on the keyboard.  the 
function should return
-1 for no key hit detected and the ascii code for any other key hit.  I 
realize the limitation
of this function would be function keys.  But something this simple( to 
use, maybe not to
write) would really be handy for me.  Will any one help me write this or 
perhaps tell me what I
need to study to make this happen??  I need this function to work 
'command line'.  Gui programming
won't be helpfull for this project.

Ron




From ehoute@zeelandnet.nl  Mon Dec 24 19:14:46 2001
From: ehoute@zeelandnet.nl (Ewald van Houte)
Date: Mon, 24 Dec 2001 20:14:46 +0100
Subject: [Tutor] Re: Tutor digest, Vol 1 #1245 - 11 msgs
Message-ID: <20011224191312.CF66D568C1@mail.zeelandnet.nl>

PlNlbmQgVHV0b3IgbWFpbGluZyBsaXN0IHN1Ym1pc3Npb25zIHRvDQo+CXR1dG9yQHB5dGhvbi5v
cmcNCj4NCj5UbyBzdWJzY3JpYmUgb3IgdW5zdWJzY3JpYmUgdmlhIHRoZSBXb3JsZCBXaWRlIFdl
YiwgdmlzaXQNCj4JaHR0cDovL21haWwucHl0aG9uLm9yZy9tYWlsbWFuL2xpc3RpbmZvL3R1dG9y
DQo+b3IsIHZpYSBlbWFpbCwgc2VuZCBhIG1lc3NhZ2Ugd2l0aCBzdWJqZWN0IG9yIGJvZHkgJ2hl
bHAnIHRvDQo+CXR1dG9yLXJlcXVlc3RAcHl0aG9uLm9yZw0KPg0KPllvdSBjYW4gcmVhY2ggdGhl
IHBlcnNvbiBtYW5hZ2luZyB0aGUgbGlzdCBhdA0KPgl0dXRvci1hZG1pbkBweXRob24ub3JnDQo+
DQo+V2hlbiByZXBseWluZywgcGxlYXNlIGVkaXQgeW91ciBTdWJqZWN0IGxpbmUgc28gaXQgaXMg
bW9yZSBzcGVjaWZpYw0KPnRoYW4gIlJlOiBDb250ZW50cyBvZiBUdXRvciBkaWdlc3QuLi4iDQo+
DQo+DQo+VG9kYXkncyBUb3BpY3M6DQo+DQo+ICAgMS4gUmU6IFB5dGhvbiAtIGh0bWwgdGFibGVz
IC0gY2dpIHF1ZXN0aW9uIChEYW5ueSBZb28pDQo+ICAgMi4gUmU6IG1lbWJlcnNoaXAgKEthbGxl
IFN2ZW5zc29uKQ0KPiAgIDMuIERvIFRraW50ZXIncyB3aW5kb3dzIGFsd2F5cyBkZWZhdWx0IHRv
IGEgY2VydGFpbiBzaXplID8gKEplYW4gTW9udGFtYmVhdWx0KQ0KPiAgIDQuIChubyBzdWJqZWN0
KSAoam9obiBwdWJsaWMpDQo+ICAgNS4gbG9vcHMgKGpvaG4gcHVibGljKQ0KPiAgIDYuIG1lbWJl
cnNoaXAgKGpvaG4gcHVibGljKQ0KPiAgIDcuIFJlOiBtZW1iZXJzaGlwIChQaWp1cyBWaXJrZXRp
cykNCj4gICA4LiBSZTogbG9vcHMgKEdyZWdvciBMaW5nbCkNCj4gICA5LiBmaW5kIChqb2huIHB1
YmxpYykNCj4gIDEwLiBSZTogZmluZCAoUGlqdXMgVmlya2V0aXMpDQo+ICAxMS4gUmU6IGZpbmQg
KGRtYW4pDQo+DQo+LS1fXy0tX18tLQ0KPg0KPk1lc3NhZ2U6IDENCj5EYXRlOiBUdWUsIDQgRGVj
IDIwMDEgMTQ6MTI6MDkgLTA4MDAgKFBTVCkNCj5Gcm9tOiBEYW5ueSBZb28gPGR5b29AaGtuLmVl
Y3MuYmVya2VsZXkuZWR1Pg0KPlRvOiBSb3NzIFlhaG5rZSA8cmN5YWhua2VAZG9pdC53aXNjLmVk
dT4NCj5jYzogdHV0b3JAcHl0aG9uLm9yZw0KPlN1YmplY3Q6IFJlOiBbVHV0b3JdIFB5dGhvbiAt
IGh0bWwgdGFibGVzIC0gY2dpIHF1ZXN0aW9uDQo+DQo+T24gVHVlLCA0IERlYyAyMDAxLCBSb3Nz
IFlhaG5rZSB3cm90ZToNCj4NCj4+IEhpIEFsbCAtIFN0cmljdGx5IHNwZWFraW5nIHRoaXMgaXMg
bW9yZSBvZiBhIGh0bWwvY2dpIHF1ZXN0aW9uIGJ1dCBJDQo+PiByZWFsbHkgd2FudCB0byB1c2Ug
UHl0aG9uIHRvIGRvIGl0IQ0KPj4gDQo+PiBJIGhhdmUgYSB0ZXh0IGZpbGUgd2l0aCB0YWIgZGVs
aW1pdGVkIGRhdGEgaW4gaXQuIEkgd2FudCB0byBwcmVzZW50IGl0IGFzIGFuDQo+PiBodG1sIHRh
YmxlIHRoYXQncyBpbiBzb3J0ZWQgb3JkZXIuIEVhY2ggY29sdW1uIGhlYWRpbmcgSSdkIGxpa2Ug
dG8gYmUgYQ0KPj4gY2xpY2thYmxlIGxpbmsgc28gdGhhdCB3aGVuIEkgY2xpY2sgb24gaXQsIHRo
ZSB0YWJsZSByZWdlbmVyYXRlcyByZXNvcnRlZA0KPj4gdW5kZXIgdGhlIGNvbHVtbiBjbGlja2Vk
IG9uLg0KPj4gDQo+PiBJIGNhbiBnZXQgUHl0aG9uIGNnaSB0byBkaXNwbGF5IGEgc3RhdGljIGxp
c3Qgd2l0aCBubyBsaW5rcyBvbmx5IHNvcnRlZCBieSBhDQo+PiBwcmUtY2hvc2VuIGNvbHVtbi4g
SG93IGRvIEkgZ28gZG8gdGhlIG5leHQgc3RlcCB0byBsZXQgdGhlIHZpZXdlciBkZWNpZGUgaG93
DQo+PiB0aGUgdGFibGUgaXMgdG8gYmUgc29ydGVkPw0KPg0KPkhtbW0uLi4gWW91IG1pZ2h0IGJl
IGFibGUgdG8gZG8gdGhpcyBieSBhbGxvd2luZyB0aGUgY29sdW1uIHRpdGxlcyBpdHNlbGYNCj50
byBiZSBjbGlja2FibGUsIGFuZCBhZGRpbmcgYW4gb3B0aW9uYWwgInNvcnRfYnkiIHBhcmFtZXRl
ciB0byB5b3VyIENHSQ0KPnByb2dyYW0uICBUaGlzIHdheSwgeW91IGNhbiBhbGxvdyB1c2VycyB0
aGUgb3B0aW9uIHRvIGNob29zZSB0aGUgc29ydGluZw0KPm9yZGVyIGluIGEgd2F5IHRoYXQncyBz
b21ld2hhdCBjb25zaXN0YW50IHdpdGggYSBzcHJlYWRzaGVldCB1c2VyDQo+aW50ZXJmYWNlLg0K
Pg0KPkdyYWJiaW5nIHBhcmFtZXRlcnMgZnJvbSBhIENHSSBpbnZvbHZlcyB1c2luZyB0aGUgJ2Nn
aScgbW9kdWxlOg0KPg0KPiAgICBodHRwOi8vd3d3LnB5dGhvbi5vcmcvZG9jL2xpYi9tb2R1bGUt
Y2dpLmh0bWwNCj4NCj4NCj5JZiB5b3UgaGF2ZSBxdWVzdGlvbnMsIHBsZWFzZSBmZWVsIGZyZWUg
dG8gYXNrIHRoZW0gb24gVHV0b3IuICBXZSdsbCBiZQ0KPmhhcHB5IHRvIGhlbHAgeW91IGdldCB5
b3VyIHByb2dyYW0gZ29pbmchICBHb29kIGx1Y2shDQo+DQo+DQo+DQo+LS1fXy0tX18tLQ0KPg0K
Pk1lc3NhZ2U6IDINCj5EYXRlOiBUdWUsIDQgRGVjIDIwMDEgMjM6MjA6NTkgKzAxMDANCj5Gcm9t
OiBLYWxsZSBTdmVuc3NvbiA8a2FsbGVAZ251cHVuZy5uZXQ+DQo+VG86IHR1dG9yQHB5dGhvbi5v
cmcNCj5TdWJqZWN0OiBSZTogW1R1dG9yXSBtZW1iZXJzaGlwDQo+DQo+W2pvaG4gcHVibGljXQ0K
Pj4gZG9lcyB0aGUgbWVtYmVyc2hpcCAoaW4pIGZ1bmN0aW9uIHdvcmsgZm9yIGxpc3RzIGFuZA0K
Pj4gc3RyaW5ncyBsaWtlIGl0IGRvZXMgZm9yIFR1cGxlcz8NCj4NCj5ZZXMsIGl0IGRvZXM6DQo+
IjEiIGluIFsiMSIsICIyIl0NCj5pcyB0cnVlLCBhcyBpcw0KPiIxIiBpbiAiMTIiDQo+YW5kDQo+
IjEiIGluICgiMSIsICIyIikNCj4NCj4+ICBpcyB0aGUgdGhlcmUgYSBnb3QgbGluZSBYIGZ1bmN0
aW9uIGluIFB5dGhvbiBmb3INCj4+IGNyZWF0aW5nIGxvb3BzPw0KPg0KPkknbSBub3Qgc3VyZSB3
aGF0IHlvdSdyZSBhc2tpbmcgYWJvdXQgaGVyZS4gIFRoZSBjYW5vbmljYWwgbG9vcCBpbiBQeXRo
b24gaXMNCj50aGUgZm9yIGxvb3Agb3ZlciBhIHNlcXVlbmNlOg0KPg0KPmZvciB4IGluIFsxLCAi
Zm9vIiwgM106DQo+ICAgIHByaW50IHgNCj4NCj53aWxsIHByaW50DQo+DQo+MQ0KPmZvbw0KPjMN
Cj4NCj5BIHdoaWxlIGxvb3AgaXMgYWxzbyBhdmFpbGFibGU6DQo+DQo+eCA9IDANCj53aGlsZSB4
IDwgMzoNCj4gICAgcHJpbnQgeA0KPiAgICB4ID0geCArIDENCj4NCj53aWxsIHByaW50DQo+DQo+
MA0KPjENCj4yDQo+DQo+PiAgSG93IGRvIEkgdW5zdWJzY3JpYmUgZnJvbSB0aGUgZGFpbHkgZGln
ZXN0PyBUSUENCj4NCj5HbyB0byB0aGUgVVJJDQo+aHR0cDovL21haWwucHl0aG9uLm9yZy9tYWls
bWFuL2xpc3RpbmZvL3R1dG9yDQo+YW5kIGVudGVyIHlvdXIgZW1haWwgYWRkcmVzcyBpbiB0aGUg
Zm9ybSBhdCB0aGUgYm90dG9tIG9mIHRoZSBwYWdlIGFuZCBzdWJtaXQuDQo+RnJvbSB0aGUgZm9s
bG93aW5nIHBhZ2UgeW91IGNhbiBlZGl0IHlvdXIgbWVtYmVyc2hpcCBpbmZvcm1hdGlvbiBhbmQN
Cj51bnN1YnNjcmliZS4NCj4NCj5QZWFjZSwNCj4gIEthbGxlDQo+LS0gDQo+WyAgTGF6aW5lc3Ms
IGltcGF0aWVuY2UsIGh1YnJpczogIFBpY2sgdHdvISAgXQ0KPlsgICBJbnRlcm5hdGlvbmFsOiBo
dHRwOi8vd3d3LmdudXB1bmcubmV0LyAgIF0NCj5bIFN2ZW5za2E6IGh0dHA6Ly93d3cubHlzYXRv
ci5saXUuc2UvfmthbGxlLyBdDQo+DQo+DQo+LS1fXy0tX18tLQ0KPg0KPk1lc3NhZ2U6IDMNCj5G
cm9tOiAiSmVhbiBNb250YW1iZWF1bHQiIDxqcm1AdmlkZW90cm9uLmNhPg0KPlRvOiA8dHV0b3JA
cHl0aG9uLm9yZz4NCj5EYXRlOiBUdWUsIDQgRGVjIDIwMDEgMTc6MzQ6NTggKzAyMDANCj5TdWJq
ZWN0OiBbVHV0b3JdIERvIFRraW50ZXIncyB3aW5kb3dzIGFsd2F5cyBkZWZhdWx0IHRvIGEgY2Vy
dGFpbiBzaXplID8NCj4NCj4gICAgV2hlbiBydW5uaW5nIGEgVGtpbnRlciBiYXNlZCBwcm9ncmFt
IEkganVzdCBkaWQgZnJvbSBJRExFLCBjb21tZW50aW5nDQo+b3V0IHRoaXNfd2luZG93Lm1haW5s
b29wKCkgb2YgY291cnNlLCB0aGUgd2luZG93IGFwcGVhcnMganVzdCB0aGUgc2l6ZSBJDQo+d291
bGQgZXhwZWN0LiBCdXQgd2hlbiBydW5uaW5nIHRoZSBzYW1lIHByb2dyYW0gKHdpdGggdGhpc193
aW5kb3cubWFpbmxvb3AoKQ0KPmFjdGl2ZSB0aGlzIHRpbWUpIGZyb20gRXhwbG9yZXIgb3IgYSBE
T1MgcHJvbXB0IHRoZSB3aW5kb3cgYWx3YXlzIGRlZmF1bHQgdG8NCj50aGUgc2FtZSBzaXplIGFu
ZCBpdCBnb2VzIGZvciBJRExFIGl0c2VsZiA6IGxvb2tzIGxpa2UgNjQweDQwMCBiZXN0IGd1ZXNz
Lg0KPkNhbiB0aGlzIGJlaGF2aW9yIGJlIGNoYW5nZWQgPyBJIGNhbid0IGJlIHRoZSBvbmx5IG9u
ZSBleHBlcmllbmNpbmcgdGhpcyBhbmQNCj5pdCBoYXMgdG8gYmUgYSBGQVEgYnV0IEkgZGlkbid0
IGZpbmQgaXQuIDooDQo+DQo+SmVhbiBNLg0KPg0KPg0KPg0KPi0tX18tLV9fLS0NCj4NCj5NZXNz
YWdlOiA0DQo+RGF0ZTogVHVlLCA0IERlYyAyMDAxIDE1OjIzOjE2IC0wODAwIChQU1QpDQo+RnJv
bTogam9obiBwdWJsaWMgPGFweXRob24xMDFAeWFob28uY29tPg0KPlRvOiB0dXRvckBweXRob24u
b3JnDQo+U3ViamVjdDogW1R1dG9yXSAobm8gc3ViamVjdCkNCj4NCj5JIGFtIGEgYmVnaW5uaW5n
IHByb2dyYW1tZXIuIEhlcmUgaXMgbXkgbXkgZmlyc3QNCj5wcm9ncmFtIGZvciB0aWMgdGFjIHRv
ZS4gSXQgd29ya3MgQlVULCBhIHNpbXBsZSBsb29wDQo+d291bGQgc2hvcnRlbiB0aGlzIGNvZGUg
Y29uc2lkZXJhYmx5LiAgSXMgdGhlcmUgYSB3YXkNCj50byB0ZWxsIHRoZSBwcm9ncmFtIHRvIGdv
IHRvIHRoZSBsaW5lOg0KPg0KPiBuID0gaW5wdXQoIndoaWNoIHNxYXVyZSIpDQo+DQo+b25jZSBp
dCBnZXRzIHRvIHRoZSBlbmQgb2YgdGhlIGZpcnN0IGN5Y2xlPw0KPg0KPiBUaGFua3MhIQ0KPg0K
PmEsYixjLGQsZSxmLGcsaCxpID0xLDIsMyw0LDUsNiw3LDgsOQ0KPg0KPnNxdWFyZSA9IFsnYScs
J2InLCdjJywnZCcsJ2UnLCdmJywnZycsJ2gnLCdpJ10NCj4NCj5wcmludCBzcXVhcmVbMF0sc3F1
YXJlWzFdLHNxdWFyZVsyXQ0KPnByaW50IHNxdWFyZVszXSxzcXVhcmVbNF0sc3F1YXJlWzVdDQo+
cHJpbnQgc3F1YXJlWzZdLHNxdWFyZVs3XSxzcXVhcmVbOF0NCj4NCj5uID0gaW5wdXQoIndoaWNo
IHNxdWFyZT8iKQ0KPg0KPg0KPg0KPnMgPSByYXdfaW5wdXQoIndobyBnZXRzIHRoZSBzcXVhcmU/
IikNCj5zcXVhcmVbbi0xXSA9IHMgDQo+DQo+cHJpbnQgc3F1YXJlWzBdLHNxdWFyZVsxXSxzcXVh
cmVbMl0NCj5wcmludCBzcXVhcmVbM10sc3F1YXJlWzRdLHNxdWFyZVs1XQ0KPnByaW50IHNxdWFy
ZVs2XSxzcXVhcmVbN10sc3F1YXJlWzhdDQo+IyBlbmQgb2YgZmlyc3QgcGFydCwgY2FuIHdlIGxv
b3AgaGVyZT8NCj4jIGNhbiB3ZSBjcmVhdGUgZnVuY3Rpb25zIGFuZCBtb2R1bGVzIHRvIHNob3J0
ZW4gdGhlDQo+Y29kZT8NCj5uID0gaW5wdXQoIndoaWNoIHNxdWFyZT8iKQ0KPg0KPg0KPg0KPnMg
PSByYXdfaW5wdXQoIndobyBnZXRzIHRoZSBzcXVhcmU/IikNCj5zcXVhcmVbbi0xXSA9IHMgDQo+
DQo+cHJpbnQgc3F1YXJlWzBdLHNxdWFyZVsxXSxzcXVhcmVbMl0NCj5wcmludCBzcXVhcmVbM10s
c3F1YXJlWzRdLHNxdWFyZVs1XQ0KPnByaW50IHNxdWFyZVs2XSxzcXVhcmVbN10sc3F1YXJlWzhd
DQo+DQo+biA9IGlucHV0KCJ3aGljaCBzcXVhcmU/IikNCj4NCj4NCj4NCj5zID0gcmF3X2lucHV0
KCJ3aG8gZ2V0cyB0aGUgc3F1YXJlPyIpDQo+c3F1YXJlW24tMV0gPSBzIA0KPg0KPnByaW50IHNx
dWFyZVswXSxzcXVhcmVbMV0sc3F1YXJlWzJdDQo+cHJpbnQgc3F1YXJlWzNdLHNxdWFyZVs0XSxz
cXVhcmVbNV0NCj5wcmludCBzcXVhcmVbNl0sc3F1YXJlWzddLHNxdWFyZVs4XQ0KPg0KPm4gPSBp
bnB1dCgid2hpY2ggc3F1YXJlPyIpDQo+DQo+DQo+DQo+cyA9IHJhd19pbnB1dCgid2hvIGdldHMg
dGhlIHNxdWFyZT8iKQ0KPnNxdWFyZVtuLTFdID0gcyANCj4NCj5wcmludCBzcXVhcmVbMF0sc3F1
YXJlWzFdLHNxdWFyZVsyXQ0KPnByaW50IHNxdWFyZVszXSxzcXVhcmVbNF0sc3F1YXJlWzVdDQo+
cHJpbnQgc3F1YXJlWzZdLHNxdWFyZVs3XSxzcXVhcmVbOF0NCj4NCj4NCj4gDQo+biA9IGlucHV0
KCJ3aGljaCBzcXVhcmU/IikNCj4NCj4NCj4NCj5zID0gcmF3X2lucHV0KCJ3aG8gZ2V0cyB0aGUg
c3F1YXJlPyIpDQo+c3F1YXJlW24tMV0gPSBzIA0KPg0KPnByaW50IHNxdWFyZVswXSxzcXVhcmVb
MV0sc3F1YXJlWzJdDQo+cHJpbnQgc3F1YXJlWzNdLHNxdWFyZVs0XSxzcXVhcmVbNV0NCj5wcmlu
dCBzcXVhcmVbNl0sc3F1YXJlWzddLHNxdWFyZVs4XQ0KPg0KPm4gPSBpbnB1dCgid2hpY2ggc3F1
YXJlPyIpDQo+DQo+DQo+DQo+cyA9IHJhd19pbnB1dCgid2hvIGdldHMgdGhlIHNxdWFyZT8iKQ0K
PnNxdWFyZVtuLTFdID0gcyANCj4NCj5wcmludCBzcXVhcmVbMF0sc3F1YXJlWzFdLHNxdWFyZVsy
XQ0KPnByaW50IHNxdWFyZVszXSxzcXVhcmVbNF0sc3F1YXJlWzVdDQo+cHJpbnQgc3F1YXJlWzZd
LHNxdWFyZVs3XSxzcXVhcmVbOF0NCj4NCj5uID0gaW5wdXQoIndoaWNoIHNxdWFyZT8iKQ0KPg0K
Pg0KPg0KPnMgPSByYXdfaW5wdXQoIndobyBnZXRzIHRoZSBzcXVhcmU/IikNCj5zcXVhcmVbbi0x
XSA9IHMgDQo+DQo+cHJpbnQgc3F1YXJlWzBdLHNxdWFyZVsxXSxzcXVhcmVbMl0NCj5wcmludCBz
cXVhcmVbM10sc3F1YXJlWzRdLHNxdWFyZVs1XQ0KPnByaW50IHNxdWFyZVs2XSxzcXVhcmVbN10s
c3F1YXJlWzhdDQo+DQo+DQo+biA9IGlucHV0KCJ3aGljaCBzcXVhcmU/IikNCj4NCj4NCj4NCj5z
ID0gcmF3X2lucHV0KCJ3aG8gZ2V0cyB0aGUgc3F1YXJlPyIpDQo+c3F1YXJlW24tMV0gPSBzIA0K
Pg0KPnByaW50IHNxdWFyZVswXSxzcXVhcmVbMV0sc3F1YXJlWzJdDQo+cHJpbnQgc3F1YXJlWzNd
LHNxdWFyZVs0XSxzcXVhcmVbNV0NCj5wcmludCBzcXVhcmVbNl0sc3F1YXJlWzddLHNxdWFyZVs4
XQ0KPg0KPg0KPm4gPSBpbnB1dCgid2hpY2ggc3F1YXJlPyIpDQo+DQo+DQo+DQo+cyA9IHJhd19p
bnB1dCgid2hvIGdldHMgdGhlIHNxdWFyZT8iKQ0KPnNxdWFyZVtuLTFdID0gcyANCj4NCj5wcmlu
dCBzcXVhcmVbMF0sc3F1YXJlWzFdLHNxdWFyZVsyXQ0KPnByaW50IHNxdWFyZVszXSxzcXVhcmVb
NF0sc3F1YXJlWzVdDQo+cHJpbnQgc3F1YXJlWzZdLHNxdWFyZVs3XSxzcXVhcmVbOF0NCj4NCj4N
Cj4gDQo+DQo+DQo+X19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19f
X19fX18NCj5EbyBZb3UgWWFob28hPw0KPkJ1eSB0aGUgcGVyZmVjdCBob2xpZGF5IGdpZnRzIGF0
IFlhaG9vISBTaG9wcGluZy4NCj5odHRwOi8vc2hvcHBpbmcueWFob28uY29tDQo+DQo+DQo+LS1f
Xy0tX18tLQ0KPg0KPk1lc3NhZ2U6IDUNCj5EYXRlOiBUdWUsIDQgRGVjIDIwMDEgMTU6MjU6MDIg
LTA4MDAgKFBTVCkNCj5Gcm9tOiBqb2huIHB1YmxpYyA8YXB5dGhvbjEwMUB5YWhvby5jb20+DQo+
VG86IHR1dG9yQHB5dGhvbi5vcmcNCj5TdWJqZWN0OiBbVHV0b3JdIGxvb3BzDQo+DQo+SSBhbSBh
IGJlZ2lubmluZyBwcm9ncmFtbWVyLiBIZXJlIGlzIG15IG15IGZpcnN0DQo+cHJvZ3JhbSBmb3Ig
dGljIHRhYyB0b2UuIEl0IHdvcmtzIEJVVCwgYSBzaW1wbGUgbG9vcA0KPndvdWxkIHNob3J0ZW4g
dGhpcyBjb2RlIGNvbnNpZGVyYWJseS4gIElzIHRoZXJlIGEgd2F5DQo+dG8gdGVsbCB0aGUgcHJv
Z3JhbSB0byBnbyB0byB0aGUgbGluZToNCj4NCj4gbiA9IGlucHV0KCJ3aGljaCBzcWF1cmUiKQ0K
Pg0KPm9uY2UgaXQgZ2V0cyB0byB0aGUgZW5kIG9mIHRoZSBmaXJzdCBjeWNsZT8NCj4NCj4gVGhh
bmtzISENCj4NCj5hLGIsYyxkLGUsZixnLGgsaSA9MSwyLDMsNCw1LDYsNyw4LDkNCj4NCj5zcXVh
cmUgPSBbJ2EnLCdiJywnYycsJ2QnLCdlJywnZicsJ2cnLCdoJywnaSddDQo+DQo+cHJpbnQgc3F1
YXJlWzBdLHNxdWFyZVsxXSxzcXVhcmVbMl0NCj5wcmludCBzcXVhcmVbM10sc3F1YXJlWzRdLHNx
dWFyZVs1XQ0KPnByaW50IHNxdWFyZVs2XSxzcXVhcmVbN10sc3F1YXJlWzhdDQo+DQo+biA9IGlu
cHV0KCJ3aGljaCBzcXVhcmU/IikNCj4NCj4NCj4NCj5zID0gcmF3X2lucHV0KCJ3aG8gZ2V0cyB0
aGUgc3F1YXJlPyIpDQo+c3F1YXJlW24tMV0gPSBzIA0KPg0KPnByaW50IHNxdWFyZVswXSxzcXVh
cmVbMV0sc3F1YXJlWzJdDQo+cHJpbnQgc3F1YXJlWzNdLHNxdWFyZVs0XSxzcXVhcmVbNV0NCj5w
cmludCBzcXVhcmVbNl0sc3F1YXJlWzddLHNxdWFyZVs4XQ0KPiMgZW5kIG9mIGZpcnN0IHBhcnQs
IGNhbiB3ZSBsb29wIGhlcmU/DQo+IyBjYW4gd2UgY3JlYXRlIGZ1bmN0aW9ucyBhbmQgbW9kdWxl
cyB0byBzaG9ydGVuIHRoZQ0KPmNvZGU/DQo+biA9IGlucHV0KCJ3aGljaCBzcXVhcmU/IikNCj4N
Cj4NCj4NCj5zID0gcmF3X2lucHV0KCJ3aG8gZ2V0cyB0aGUgc3F1YXJlPyIpDQo+c3F1YXJlW24t
MV0gPSBzIA0KPg0KPnByaW50IHNxdWFyZVswXSxzcXVhcmVbMV0sc3F1YXJlWzJdDQo+cHJpbnQg
c3F1YXJlWzNdLHNxdWFyZVs0XSxzcXVhcmVbNV0NCj5wcmludCBzcXVhcmVbNl0sc3F1YXJlWzdd
LHNxdWFyZVs4XQ0KPg0KPm4gPSBpbnB1dCgid2hpY2ggc3F1YXJlPyIpDQo+DQo+DQo+DQo+cyA9
IHJhd19pbnB1dCgid2hvIGdldHMgdGhlIHNxdWFyZT8iKQ0KPnNxdWFyZVtuLTFdID0gcyANCj4N
Cj5wcmludCBzcXVhcmVbMF0sc3F1YXJlWzFdLHNxdWFyZVsyXQ0KPnByaW50IHNxdWFyZVszXSxz
cXVhcmVbNF0sc3F1YXJlWzVdDQo+cHJpbnQgc3F1YXJlWzZdLHNxdWFyZVs3XSxzcXVhcmVbOF0N
Cj4NCj5uID0gaW5wdXQoIndoaWNoIHNxdWFyZT8iKQ0KPg0KPg0KPg0KPnMgPSByYXdfaW5wdXQo
IndobyBnZXRzIHRoZSBzcXVhcmU/IikNCj5zcXVhcmVbbi0xXSA9IHMgDQo+DQo+cHJpbnQgc3F1
YXJlWzBdLHNxdWFyZVsxXSxzcXVhcmVbMl0NCj5wcmludCBzcXVhcmVbM10sc3F1YXJlWzRdLHNx
dWFyZVs1XQ0KPnByaW50IHNxdWFyZVs2XSxzcXVhcmVbN10sc3F1YXJlWzhdDQo+DQo+DQo+IA0K
Pm4gPSBpbnB1dCgid2hpY2ggc3F1YXJlPyIpDQo+DQo+DQo+DQo+cyA9IHJhd19pbnB1dCgid2hv
IGdldHMgdGhlIHNxdWFyZT8iKQ0KPnNxdWFyZVtuLTFdID0gcyANCj4NCj5wcmludCBzcXVhcmVb
MF0sc3F1YXJlWzFdLHNxdWFyZVsyXQ0KPnByaW50IHNxdWFyZVszXSxzcXVhcmVbNF0sc3F1YXJl
WzVdDQo+cHJpbnQgc3F1YXJlWzZdLHNxdWFyZVs3XSxzcXVhcmVbOF0NCj4NCj5uID0gaW5wdXQo
IndoaWNoIHNxdWFyZT8iKQ0KPg0KPg0KPg0KPnMgPSByYXdfaW5wdXQoIndobyBnZXRzIHRoZSBz
cXVhcmU/IikNCj5zcXVhcmVbbi0xXSA9IHMgDQo+DQo+cHJpbnQgc3F1YXJlWzBdLHNxdWFyZVsx
XSxzcXVhcmVbMl0NCj5wcmludCBzcXVhcmVbM10sc3F1YXJlWzRdLHNxdWFyZVs1XQ0KPnByaW50
IHNxdWFyZVs2XSxzcXVhcmVbN10sc3F1YXJlWzhdDQo+DQo+biA9IGlucHV0KCJ3aGljaCBzcXVh
cmU/IikNCj4NCj4NCj4NCj5zID0gcmF3X2lucHV0KCJ3aG8gZ2V0cyB0aGUgc3F1YXJlPyIpDQo+
c3F1YXJlW24tMV0gPSBzIA0KPg0KPnByaW50IHNxdWFyZVswXSxzcXVhcmVbMV0sc3F1YXJlWzJd
DQo+cHJpbnQgc3F1YXJlWzNdLHNxdWFyZVs0XSxzcXVhcmVbNV0NCj5wcmludCBzcXVhcmVbNl0s
c3F1YXJlWzddLHNxdWFyZVs4XQ0KPg0KPg0KPm4gPSBpbnB1dCgid2hpY2ggc3F1YXJlPyIpDQo+
DQo+DQo+DQo+cyA9IHJhd19pbnB1dCgid2hvIGdldHMgdGhlIHNxdWFyZT8iKQ0KPnNxdWFyZVtu
LTFdID0gcyANCj4NCj5wcmludCBzcXVhcmVbMF0sc3F1YXJlWzFdLHNxdWFyZVsyXQ0KPnByaW50
IHNxdWFyZVszXSxzcXVhcmVbNF0sc3F1YXJlWzVdDQo+cHJpbnQgc3F1YXJlWzZdLHNxdWFyZVs3
XSxzcXVhcmVbOF0NCj4NCj4NCj5uID0gaW5wdXQoIndoaWNoIHNxdWFyZT8iKQ0KPg0KPg0KPg0K
PnMgPSByYXdfaW5wdXQoIndobyBnZXRzIHRoZSBzcXVhcmU/IikNCj5zcXVhcmVbbi0xXSA9IHMg
DQo+DQo+cHJpbnQgc3F1YXJlWzBdLHNxdWFyZVsxXSxzcXVhcmVbMl0NCj5wcmludCBzcXVhcmVb
M10sc3F1YXJlWzRdLHNxdWFyZVs1XQ0KPnByaW50IHNxdWFyZVs2XSxzcXVhcmVbN10sc3F1YXJl
WzhdDQo+DQo+DQo+IA0KPg0KPg0KPl9fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19f
X19fX19fX19fX19fX19fDQo+RG8gWW91IFlhaG9vIT8NCj5CdXkgdGhlIHBlcmZlY3QgaG9saWRh
eSBnaWZ0cyBhdCBZYWhvbyEgU2hvcHBpbmcuDQo+aHR0cDovL3Nob3BwaW5nLnlhaG9vLmNvbQ0K
Pg0KPg0KPi0tX18tLV9fLS0NCj4NCj5NZXNzYWdlOiA2DQo+RGF0ZTogVHVlLCA0IERlYyAyMDAx
IDE2OjUyOjQ5IC0wODAwIChQU1QpDQo+RnJvbTogam9obiBwdWJsaWMgPGFweXRob24xMDFAeWFo
b28uY29tPg0KPlRvOiB0dXRvckBweXRob24ub3JnDQo+U3ViamVjdDogW1R1dG9yXSBtZW1iZXJz
aGlwDQo+DQo+dDEgPSAiYSBsaXR0bGUgcmVkIG1vb24iDQo+dDIgPSB0MQ0KPnQzID0gInJlZG1v
bmQgd2FzaGluZ3RvbiINCj4NCj5pZiAoInIiIGluIHQyKToNCj4gICAgcHJpbnQgInQyIg0KPiAg
ICBwcmludCB0Mg0KPg0KPiB0aGlzIHNob3J0IHBpZWNlIG9mIGNvZGUgd29ya3MgdXNpbmcgdGhl
IG1lbWJlcnNoaXANCj5mdW5jdGlvbi4gSG93ZXZlciBhZGRpbmcgd2hhdCBpcyBiZWxvdzoNCj4N
Cj50MSA9ICJhIGxpdHRsZSByZWQgbW9vbiINCj50MiA9IHQxDQo+dDMgPSAicmVkbW9uZCB3YXNo
aW5ndG9uIg0KPg0KPmlmICgiciIgaW4gdDIpOg0KPiAgICBwcmludCAidDIiDQo+ICAgIHByaW50
IHQyDQo+ICAgDQo+aWYgKCJyZSIgaW4gdDIpOg0KPiAgIHByaW50ICJ0MiINCj4gICBwcmludCAg
dDINCj5pZiAoInJlIiBpbiB0Myk6DQo+ICAgcHJpbnQgInQzIg0KPiAgIHByaW50ICB0Mw0KPg0K
Pg0KPnJlc3VsdHMgaW4gdGhpcyBlcnJvciBtZXNzYWdlOg0KPg0KPg0KPnQyDQo+YSBsaXR0bGUg
cmVkIG1vb24NCj5UcmFjZWJhY2sgKG1vc3QgcmVjZW50IGNhbGwgbGFzdCk6DQo+ICBGaWxlICJD
OlxQeXRob24yMVxUb29sc1xpZGxlXGFtZW1iZXJzaGlwLnB5IiwgbGluZQ0KPjEwLCBpbiA/DQo+
ICAgIGlmICgicmUiIGluIHQyKToNCj5UeXBlRXJyb3I6ICdpbiA8c3RyaW5nPicgcmVxdWlyZXMg
Y2hhcmFjdGVyIGFzIGxlZnQNCj5vcGVyYW5kDQo+DQo+Q2FuIHNvbWVvbmUgdGVsbCBtZSB3aHkg
dGhpcyBoYXBwZW5zPyBJIGFtIGEgYmVnaW5uaW5nDQo+cHJvZ3JhbW1lci4gSSBzdGFydGVkIGlu
IEMrKyB0aHJlZSB3ZWVrcyBhZ28uIEkNCj5zd2l0Y2hlZCB0byBweXRob24gdHdvIHdlZWtzIGFn
byB3aGVuIEkgcmVhbGl6ZWQgaXQNCj53YXMgdXNlciBmcmllbmRseS4gTXkgZmlyc3QgcHJvZ3Jh
bSB3YXMgYSB0aWMgdGFjIHRvZQ0KPmdhbWUuIEkgYW0gbm93IHRyeWluZyB0byB3cml0ZSBhIHBy
b2dyYW0gdGhhdCBzdG9yZXMNCj5ub3RlcyBpbiBsaXN0cyx0dXBsZXMgb3Igc3RyaW5ncy4gVGhl
IGluZm9ybWF0aW9uIGlzDQo+d3JpdHRlbiB3b3JkLiBTdWNoIGFzICJsaXR0bGUgcmVkIG1vb24i
DQo+InJlZG1vbmQgd2FzaGluZ3RvbiIsICJjdXRlIHJlZGhlYWQgSSBtZXQgYXQgdGhlIGJhciIu
DQo+SSB3YW50IHRvIGJlIGFibGUgdG8gc2VhcmNoIHRoZSBsaXN0cywgdHVwbGUncyBvcg0KPnN0
cmluZ3Mgc3VjY2VzaXZlbHkgZm9yIHRoZSBsZXR0ZXIgInIiLCB3aGljaCB3b3VsZA0KPmJyaW5n
IHVwIGFsbCB0aHJlZSBub3Rlcy4gVGhlbiAicmUiIHdoaWNoIHdvdWxkIGJyaW5nDQo+dXAgYWxs
IHRocmVlLiBUaGVuICJyZWQiIHdoaWNoIHdvdWxkIHN0aWxsIGJyaW5nIHVwDQo+YWxsIHRocmVl
LiBUaGVuIHJlZG0sIHdoaWNoIHdvdWxkIGJyaW5nIHVwIG9ubHkgdGhlDQo+bGlzdCBbcmVkbW9u
ZCB3YXNoaW5ndG9uXSwgYW5kIHJlZGggd2hpY2ggd291bGQgYnJpbmcNCj51cCBvbmx5IHRoZSBs
aXN0IFtjdXRlIHJlZGhlYWQgSSBtZXQgYXQgdGhlIGJhcl0uIElzDQo+dGhlIG1lbWJlcnNoaXAg
ZnVuY3Rpb24gd2hhdCBJIHNob3VsZCBiZSB1c2luZyB0byBkbw0KPnRoaXM/IEkgYW0gb25seSBh
IGJlZ2dpbmVyIGFuZCBtb3N0IG9mIHdoYXQgaXMgc2FpZCBvbg0KPnRoaXMgdGhyZWFkIGlzIHdh
eSBvdmVyIG15IGhlYWQuIEkgc2VlbSB0byBiZSBhYmxlIHRvDQo+cmVhZCBhbmQgdW5kZXJzdGFu
ZCBjb2RlIGRpcmVjdGx5IGJldHRlciB0aGFuIHJlYWQgYW5kDQo+dW5kZXJzdGFuZCB3aGF0IGlz
IHNhaWQgYWJvdXQgY29kZS4gT25jZSBJIGNhbiBzZWUNCj5jb2RlIEkgY2FuIHJ1biBpdC4gVGhl
biBtYWtlIHN1YnN0aXR1dGlvbnMgYW5kDQo+Y2hhbmdlcy4gU28gZmFyIHRoaXMgc2VlbXMgdG8g
YmUgdGhlIGJlc3Qgd2F5IGZvciBtZQ0KPnRvIGxlYXJuIGZyb20gb3RoZXJzLiBJIHdpbGwgYmUg
cG9zdGluZyB0aGUgdGljIHRhYw0KPnRvZSBwcm9ncmFtIGFmdGVyIHRoaXMuIFRoYW5rcyBmb3Ig
YWxsIHRoZSBoZWxwDQo+ZXZlcmJhd2R5IQ0KPg0KPiBKb2huIFB1YmxpYyAoIHJlYWxseSBteSBy
ZWFsIG5hbWUgOylyZWFsbHkhDQo+DQo+DQo+DQo+DQo+X19fX19fX19fX19fX19fX19fX19fX19f
X19fX19fX19fX19fX19fX19fX19fX19fX18NCj5EbyBZb3UgWWFob28hPw0KPkJ1eSB0aGUgcGVy
ZmVjdCBob2xpZGF5IGdpZnRzIGF0IFlhaG9vISBTaG9wcGluZy4NCj5odHRwOi8vc2hvcHBpbmcu
eWFob28uY29tDQo+DQo+DQo+LS1fXy0tX18tLQ0KPg0KPk1lc3NhZ2U6IDcNCj5EYXRlOiBUdWUs
IDA0IERlYyAyMDAxIDIwOjA1OjMyIC0wNTAwDQo+VG86IGpvaG4gcHVibGljIDxhcHl0aG9uMTAx
QHlhaG9vLmNvbT4NCj5Gcm9tOiBQaWp1cyBWaXJrZXRpcyA8dmlya2V0aXNAZmFzLmhhcnZhcmQu
ZWR1Pg0KPlN1YmplY3Q6IFJlOiBbVHV0b3JdIG1lbWJlcnNoaXANCj5DYzogdHV0b3JAcHl0aG9u
Lm9yZw0KPg0KPkpvaG4sDQo+DQo+PnQyDQo+PmEgbGl0dGxlIHJlZCBtb29uDQo+PlRyYWNlYmFj
ayAobW9zdCByZWNlbnQgY2FsbCBsYXN0KToNCj4+ICBGaWxlICJDOlxQeXRob24yMVxUb29sc1xp
ZGxlXGFtZW1iZXJzaGlwLnB5IiwgbGluZQ0KPj4xMCwgaW4gPw0KPj4gICAgaWYgKCJyZSIgaW4g
dDIpOg0KPj5UeXBlRXJyb3I6ICdpbiA8c3RyaW5nPicgcmVxdWlyZXMgY2hhcmFjdGVyIGFzIGxl
ZnQNCj4+b3BlcmFuZA0KPg0KPkFzIHRoZSBlcnJvciBtZXNzYWdlIHN0YXRlcywgdGhlIHRoaW5n
IGZvciB3aGljaCB5b3UgYXJlIGFza2luZyAiaW4iIHRvDQo+bG9vayBmb3IgaW4gc29tZSBzdHJp
bmcgbXVzdCBiZSBhIGNoYXJhY3Rlciwgb3IgZXF1aXZhbGVudGx5IGEgc3RyaW5nIG9mDQo+bGVu
Z2h0IG9uZS4gU28sIHlvdSBjYW4gYXNrOiAiaXMgbGV0dGVyICdyJyBpbiB0aGlzIHN0cmluZz8i
IGJ1dCBub3QgImlzDQo+d29yZCAncmUnIGluIHRoaXMgc3RyaW5nPyIgT2YgY291cnNlLCBQeXRo
b24gaGFzIHdheXMgdG8gbG9vayBmb3Igd29yZHMgaW4NCj5zdHJpbmdzIGFzIHdlbGwuIENoZWNr
IG91dCB0aGUgc3RyaW5nIG1vZHVsZSBoZXJlOg0KPmh0dHA6Ly93d3cucHl0aG9uLm9yZy9kb2Mv
Y3VycmVudC9saWIvbW9kdWxlLXN0cmluZy5odG1sIGFuZCBpbiBwYXJ0aWN1bGFyDQo+bG9vayBh
dCBzdHJpbmcuZmluZCgpIGFuZCAocGVyaGFwcykgc3RyaW5nLmNvdW50KCkuDQo+DQo+Q2hlZXJz
LCANCj4NCj4tUA0KPi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0t
LS0tLS0tLS0tLS0tLS0tLQ0KPlBHUCBQVUJMSUMgS0VZOiB3d3cuZmFzLmhhcnZhcmQuZWR1L352
aXJrZXRpcy9saW5rcw0KPk15IHdlYmxvZzogd3d3LmZhcy5oYXJ2YXJkLmVkdS9+dmlya2V0aXMN
Cj4NCj4NCj4NCj4tLV9fLS1fXy0tDQo+DQo+TWVzc2FnZTogOA0KPkZyb206ICJHcmVnb3IgTGlu
Z2wiIDxnbGluZ2xAYW9uLmF0Pg0KPlRvOiAiam9obiBwdWJsaWMiIDxhcHl0aG9uMTAxQHlhaG9v
LmNvbT4sDQo+CTx0dXRvckBweXRob24ub3JnPg0KPlN1YmplY3Q6IFJlOiBbVHV0b3JdIGxvb3Bz
DQo+RGF0ZTogV2VkLCA1IERlYyAyMDAxIDAyOjA4OjI5ICswMTAwDQo+DQo+DQo+LS0tLS0gT3Jp
Z2luYWwgTWVzc2FnZSAtLS0tLSANCj5Gcm9tOiAiam9obiBwdWJsaWMiIDxhcHl0aG9uMTAxQHlh
aG9vLmNvbT4NCj5UbzogPHR1dG9yQHB5dGhvbi5vcmc+DQo+U2VudDogV2VkbmVzZGF5LCBEZWNl
bWJlciAwNSwgMjAwMSAxMjoyNSBBTQ0KPlN1YmplY3Q6IFtUdXRvcl0gbG9vcHMNCj4NCj4NCj4+
IEkgYW0gYSBiZWdpbm5pbmcgcHJvZ3JhbW1lci4gSGVyZSBpcyBteSBteSBmaXJzdA0KPj4gcHJv
Z3JhbSBmb3IgdGljIHRhYyB0b2UuIEl0IHdvcmtzIEJVVCwgYSBzaW1wbGUgbG9vcA0KPj4gd291
bGQgc2hvcnRlbiB0aGlzIGNvZGUgY29uc2lkZXJhYmx5LiAgSXMgdGhlcmUgYSB3YXkNCj4+IHRv
IHRlbGwgdGhlIHByb2dyYW0gdG8gZ28gdG8gdGhlIGxpbmU6DQo+PiANCj4+ICBuID0gaW5wdXQo
IndoaWNoIHNxYXVyZSIpDQo+PiANCj4+IG9uY2UgaXQgZ2V0cyB0byB0aGUgZW5kIG9mIHRoZSBm
aXJzdCBjeWNsZT8NCj4+IA0KPj4gIFRoYW5rcyEhDQo+PiANCj4+IGEsYixjLGQsZSxmLGcsaCxp
ID0xLDIsMyw0LDUsNiw3LDgsOQ0KPj4gDQo+PiBzcXVhcmUgPSBbJ2EnLCdiJywnYycsJ2QnLCdl
JywnZicsJ2cnLCdoJywnaSddDQo+PiANCj4+IHByaW50IHNxdWFyZVswXSxzcXVhcmVbMV0sc3F1
YXJlWzJdDQo+PiBwcmludCBzcXVhcmVbM10sc3F1YXJlWzRdLHNxdWFyZVs1XQ0KPj4gcHJpbnQg
c3F1YXJlWzZdLHNxdWFyZVs3XSxzcXVhcmVbOF0NCj4+IA0KPj4gbiA9IGlucHV0KCJ3aGljaCBz
cXVhcmU/IikNCj4+IA0KPj4gDQo+PiANCj4+IHMgPSByYXdfaW5wdXQoIndobyBnZXRzIHRoZSBz
cXVhcmU/IikNCj4+IHNxdWFyZVtuLTFdID0gcyANCj4+IA0KPj4gcHJpbnQgc3F1YXJlWzBdLHNx
dWFyZVsxXSxzcXVhcmVbMl0NCj4+IHByaW50IHNxdWFyZVszXSxzcXVhcmVbNF0sc3F1YXJlWzVd
DQo+PiBwcmludCBzcXVhcmVbNl0sc3F1YXJlWzddLHNxdWFyZVs4XQ0KPj4gIyBlbmQgb2YgZmly
c3QgcGFydCwgY2FuIHdlIGxvb3AgaGVyZT8NCj4NCj5DZXJ0YWlubHk6DQo+DQo+YSxiLGMsZCxl
LGYsZyxoLGkgPTEsMiwzLDQsNSw2LDcsOCw5DQo+DQo+c3F1YXJlID0gWydhJywnYicsJ2MnLCdk
JywnZScsJ2YnLCdnJywnaCcsJ2knXQ0KPg0KPnByaW50IHNxdWFyZVswXSxzcXVhcmVbMV0sc3F1
YXJlWzJdDQo+cHJpbnQgc3F1YXJlWzNdLHNxdWFyZVs0XSxzcXVhcmVbNV0NCj5wcmludCBzcXVh
cmVbNl0sc3F1YXJlWzddLHNxdWFyZVs4XQ0KPg0KPmZvciBpIGluIHJhbmdlKDkpOg0KPiAgICBu
ID0gaW5wdXQoIndoaWNoIHNxdWFyZT8iKQ0KPiAgICBzID0gcmF3X2lucHV0KCJ3aG8gZ2V0cyB0
aGUgc3F1YXJlPyIpDQo+ICAgIHNxdWFyZVtuLTFdID0gcyANCj4NCj4gICAgcHJpbnQgc3F1YXJl
WzBdLHNxdWFyZVsxXSxzcXVhcmVbMl0NCj4gICAgcHJpbnQgc3F1YXJlWzNdLHNxdWFyZVs0XSxz
cXVhcmVbNV0NCj4gICAgcHJpbnQgc3F1YXJlWzZdLHNxdWFyZVs3XSxzcXVhcmVbOF0NCj4NCj4N
Cj5BbmQgdGhlIG5leHQgcHJvYmxlbSB3b3VsZCBiZTogaG93IHRvDQo+ZmluZCBvdXQsIGlmIHRo
ZSBnYW1lIGlzIG92ZXIgYmVmb3JlIHRoZQ0KPm5pbnRoIGRyYXc/DQo+DQo+R3JlZ29yDQo+DQo+
UC5TLjogSGF2IGEgbG9vayBhdCBodHRwOi8vd3d3LnB5dGhvbi5vcmcvZG9jL05ld2JpZXMuaHRt
bA0KPg0KPg0KPg0KPi0tX18tLV9fLS0NCj4NCj5NZXNzYWdlOiA5DQo+RGF0ZTogVHVlLCA0IERl
YyAyMDAxIDE4OjA5OjE4IC0wODAwIChQU1QpDQo+RnJvbTogam9obiBwdWJsaWMgPGFweXRob24x
MDFAeWFob28uY29tPg0KPlRvOiB0dXRvckBweXRob24ub3JnDQo+Q2M6IHZpcmtldGlzQGZhcy5o
YXJ2YXJkLmVkdQ0KPlN1YmplY3Q6IFtUdXRvcl0gZmluZA0KPg0KPi0tMC0xODU1OTcxMzgxLTEw
MDc1MTgxNTg9OjQ3OTc4DQo+Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PXVzLWFz
Y2lpDQo+DQo+DQo+DQo+DQo+Sm9obiwgDQo+DQo+PnQyIA0KPj5hIGxpdHRsZSByZWQgbW9vbiAN
Cj4+VHJhY2ViYWNrIChtb3N0IHJlY2VudCBjYWxsIGxhc3QpOiANCj4+IEZpbGUgIkM6XFB5dGhv
bjIxXFRvb2xzXGlkbGVcYW1lbWJlcnNoaXAucHkiLCBsaW5lIA0KPj4xMCwgaW4gPyANCj4+IGlm
ICgicmUiIGluIHQyKTogDQo+PlR5cGVFcnJvcjogJ2luIDxzdHJpbmc+JyByZXF1aXJlcyBjaGFy
YWN0ZXIgYXMgbGVmdCANCj4+b3BlcmFuZCANCj4NCj5BcyB0aGUgZXJyb3IgbWVzc2FnZSBzdGF0
ZXMsIHRoZSB0aGluZyBmb3Igd2hpY2ggeW91IGFyZSBhc2tpbmcgImluIiB0byANCj5sb29rIGZv
ciBpbiBzb21lIHN0cmluZyBtdXN0IGJlIGEgY2hhcmFjdGVyLCBvciBlcXVpdmFsZW50bHkgYSBz
dHJpbmcgDQo+b2YgDQo+bGVuZ2h0IG9uZS4gU28sIHlvdSBjYW4gYXNrOiAiaXMgbGV0dGVyICdy
JyBpbiB0aGlzIHN0cmluZz8iIGJ1dCBub3QgDQo+ImlzIA0KPndvcmQgJ3JlJyBpbiB0aGlzIHN0
cmluZz8iIE9mIGNvdXJzZSwgUHl0aG9uIGhhcyB3YXlzIHRvIGxvb2sgZm9yIHdvcmRzIA0KPmlu
IA0KPnN0cmluZ3MgYXMgd2VsbC4gQ2hlY2sgb3V0IHRoZSBzdHJpbmcgbW9kdWxlIGhlcmU6IA0K
Pmh0dHA6Ly93d3cucHl0aG9uLm9yZy9kb2MvY3VycmVudC9saWIvbW9kdWxlLXN0cmluZy5odG1s
IGFuZCBpbiANCj5wYXJ0aWN1bGFyIA0KPmxvb2sgYXQgc3RyaW5nLmZpbmQoKSBhbmQgKHBlcmhh
cHMpIHN0cmluZy5jb3VudCgpLiANCj4NCj4NCj5vayBzbyB0aGUgbWVtYmVyc2hpcCBmdW5jdGlv
biBvbmx5IGxvb2tzIGZvciBzaW5nbGUgY2hhcmVjdG9ycy4gU28gSSB3YXMgdXNpbmcgdGhlIHdy
b25nIHRvb2wgZm9yIHRoZSBqb2IuDQo+DQo+YWZ0ZXIgbG9va2luZyBhdCB0aGUgUHl0aG9uIGxp
YnJhcnkgcmVmZXJlbmNlIDQuMSBJIHRvb2sgYSBuZXdiaWUgZ3Vlc3MgYW5kIHRob3VnaHQgdGhh
dDoNCj4NCj5maW5kKHMsIHN1YlssIHN0YXJ0WyxlbmRdXSkgDQo+ICAgUmV0dXJuIHRoZSBsb3dl
c3QgaW5kZXggaW4gcyB3aGVyZSB0aGUgc3Vic3RyaW5nIHN1YiBpcyBmb3VuZCBzdWNoIHRoYXQg
c3ViIGlzIHdob2xseSBjb250YWluZWQgaW4gc1tzdGFydDplbmRdLiBSZXR1cm4gLTEgb24gZmFp
bHVyZS4gRGVmYXVsdHMgZm9yIHN0YXJ0IGFuZCBlbmQgYW5kIGludGVycHJldGF0aW9uIG9mIG5l
Z2F0aXZlIHZhbHVlcyBpcyB0aGUgc2FtZSBhcyBmb3Igc2xpY2VzLiANCj53YXMgdGhlIHJpZ2h0
IHRvb2wgZm9yIHRoZSBqb2IuDQo+DQo+SSBpbnRlcnByZXRlZCBhbmQgYXBwbGllZCBhcyBiZWxv
dzoNCj4NCj4NCj50MSA9ICJhIGxpdHRsZSByZWQgbW9vbiINCj50MiA9ICJjdXRlIHJlZGhlYWQi
DQo+dDMgPSAicmVkbW9uZCB3YXNoaW5ndG9uIg0KPg0KPmlmICgiciIgaW4gdDIpOg0KPiAgICBw
cmludCAidDIiDQo+ICAgIHByaW50IHQyDQo+DQo+ZmluZCh0MixyZWRbMFsxXV0pICANCj4NCj5h
bmQgZ290Og0KPg0KPlB5dGhvbiAyLjEuMSAoIzIwLCBKdWwgMjAgMjAwMSwgMDE6MTk6MjkpIFtN
U0MgMzIgYml0IChJbnRlbCldIG9uIHdpbjMyDQo+VHlwZSAiY29weXJpZ2h0IiwgImNyZWRpdHMi
IG9yICJsaWNlbnNlIiBmb3IgbW9yZSBpbmZvcm1hdGlvbi4NCj5JRExFIDAuOCAtLSBwcmVzcyBG
MSBmb3IgaGVscA0KPj4+PiANCj50Mg0KPmN1dGUgcmVkaGVhZA0KPlRyYWNlYmFjayAobW9zdCBy
ZWNlbnQgY2FsbCBsYXN0KToNCj4gIEZpbGUgIkM6XFB5dGhvbjIxXFRvb2xzXGlkbGVcYW1lbWJl
cnNoaXAucHkiLCBsaW5lIDEwLCBpbiA/DQo+ICAgIGZpbmQodDIscmVkWzBbMV1dKQ0KPk5hbWVF
cnJvcjogbmFtZSAnZmluZCcgaXMgbm90IGRlZmluZWQNCj4NCj4NCj5hbSBJIGJhcmtpbmcgdXAg
dGhlIHJpZ2h0IHRyZWU/DQo+DQo+dGhhbmtzIA0KPg0KPg0KPg0KPi0tLS0tLS0tLS0tLS0tLS0t
LS0tLS0tLS0tLS0tLS0tLQ0KPkRvIFlvdSBZYWhvbyE/DQo+QnV5IHRoZSBwZXJmZWN0IGhvbGlk
YXkgZ2lmdHMgYXQgWWFob28hIFNob3BwaW5nLg0KPi0tMC0xODU1OTcxMzgxLTEwMDc1MTgxNTg9
OjQ3OTc4DQo+Q29udGVudC1UeXBlOiB0ZXh0L2h0bWw7IGNoYXJzZXQ9dXMtYXNjaWkNCj4NCj48
UD48QlI+PEJSPjxGT05UIGNvbG9yPWRhcmtyZWQ+PEVNPkpvaG4sIDxCUj48QlI+Jmd0O3QyIDxC
Uj4mZ3Q7YSBsaXR0bGUgcmVkIG1vb24gPEJSPiZndDtUcmFjZWJhY2sgKG1vc3QgcmVjZW50IGNh
bGwgbGFzdCk6IDxCUj4mZ3Q7IEZpbGUgIkM6XFB5dGhvbjIxXFRvb2xzXGlkbGVcYW1lbWJlcnNo
aXAucHkiLCBsaW5lIDxCUj4mZ3Q7MTAsIGluID8gPEJSPiZndDsgaWYgKCJyZSIgaW4gdDIpOiA8
QlI+Jmd0O1R5cGVFcnJvcjogJ2luICZsdDtzdHJpbmcmZ3Q7JyByZXF1aXJlcyBjaGFyYWN0ZXIg
YXMgbGVmdCA8QlI+Jmd0O29wZXJhbmQgPEJSPjxCUj5BcyB0aGUgZXJyb3IgbWVzc2FnZSBzdGF0
ZXMsIHRoZSB0aGluZyBmb3Igd2hpY2ggeW91IGFyZSBhc2tpbmcgImluIiB0byA8QlI+bG9vayBm
b3IgaW4gc29tZSBzdHJpbmcgbXVzdCBiZSBhIGNoYXJhY3Rlciwgb3IgZXF1aXZhbGVudGx5IGEg
c3RyaW5nIDxCUj5vZiA8QlI+bGVuZ2h0IG9uZS4gU28sIHlvdSBjYW4gYXNrOiAiaXMgbGV0dGVy
ICdyJyBpbiB0aGlzIHN0cmluZz8iIGJ1dCBub3QgPEJSPiJpcyA8QlI+d29yZCAncmUnIGluIHRo
aXMgc3RyaW5nPyIgT2YgY291cnNlLCBQeXRob24gaGFzIHdheXMgdG8gbG9vayBmb3Igd29yZHMg
PEJSPmluIDxCUj5zdHJpbmdzIGFzIHdlbGwuIENoZWNrIG91dCB0aGUgc3RyaW5nIG1vZHVsZSBo
ZXJlOiA8QlI+aHR0cDovL3d3dy5weXRob24ub3JnL2RvYy9jdXJyZW50L2xpYi9tb2R1bGUtc3Ry
aW5nLmh0bWwgYW5kIGluIDxCUj5wYXJ0aWN1bGFyIDxCUj5sb29rIGF0IHN0cmluZy5maW5kKCkg
YW5kIChwZXJoYXBzKSBzdHJpbmcuY291bnQoKS4gPEJSPjxCUj48QlI+PC9FTT48L0ZPTlQ+PFNU
Uk9ORz48Rk9OVCBjb2xvcj1ibGFjaz5vayBzbyB0aGUgbWVtYmVyc2hpcCBmdW5jdGlvbiBvbmx5
IGxvb2tzIGZvciBzaW5nbGUgY2hhcmVjdG9ycy4gU28gSSB3YXMgdXNpbmcgdGhlIHdyb25nIHRv
b2wgZm9yIHRoZSBqb2IuPC9GT05UPjwvU1RST05HPjwvUD4NCj48UD48U1RST05HPmFmdGVyJm5i
c3A7bG9va2luZyBhdCB0aGUgUHl0aG9uIGxpYnJhcnkgcmVmZXJlbmNlIDQuMSBJIHRvb2sgYSBu
ZXdiaWUgZ3Vlc3MgYW5kIHRob3VnaHQgdGhhdDo8L1NUUk9ORz48L1A+DQo+PERMPg0KPjxEVD48
Qj48QSBuYW1lPWwyaC02MzI+PFRUIGNsYXNzPWZ1bmN0aW9uPmZpbmQ8L1RUPjwvQT48L0I+KDxW
QVI+cywgc3ViPC9WQVI+PEJJRz5bPC9CSUc+PFZBUj4sIHN0YXJ0PC9WQVI+PEJJRz5bPC9CSUc+
PFZBUj4sZW5kPC9WQVI+PEJJRz5dPC9CSUc+PEJJRz5dPC9CSUc+KSANCj48REQ+UmV0dXJuIHRo
ZSBsb3dlc3QgaW5kZXggaW4gPFZBUj5zPC9WQVI+IHdoZXJlIHRoZSBzdWJzdHJpbmcgPFZBUj5z
dWI8L1ZBUj4gaXMgZm91bmQgc3VjaCB0aGF0IDxWQVI+c3ViPC9WQVI+IGlzIHdob2xseSBjb250
YWluZWQgaW4gPENPREU+PFZBUj5zPC9WQVI+WzxWQVI+c3RhcnQ8L1ZBUj46PFZBUj5lbmQ8L1ZB
Uj5dPC9DT0RFPi4gUmV0dXJuIDxDT0RFPi0xPC9DT0RFPiBvbiBmYWlsdXJlLiBEZWZhdWx0cyBm
b3IgPFZBUj5zdGFydDwvVkFSPiBhbmQgPFZBUj5lbmQ8L1ZBUj4gYW5kIGludGVycHJldGF0aW9u
IG9mIG5lZ2F0aXZlIHZhbHVlcyBpcyB0aGUgc2FtZSBhcyBmb3Igc2xpY2VzLiA8L0REPjwvREw+
DQo+PFA+PFNUUk9ORz53YXMgdGhlIHJpZ2h0IHRvb2wgZm9yIHRoZSBqb2IuPC9TVFJPTkc+PC9Q
Pg0KPjxQPjxTVFJPTkc+SSBpbnRlcnByZXRlZCBhbmQgYXBwbGllZCBhcyBiZWxvdzo8L1NUUk9O
Rz48L1A+DQo+PFA+PEJSPnQxID0gImEgbGl0dGxlIHJlZCBtb29uIjxCUj50MiA9ICJjdXRlIHJl
ZGhlYWQiPEJSPnQzID0gInJlZG1vbmQgd2FzaGluZ3RvbiI8L1A+DQo+PFA+aWYgKCJyIiBpbiB0
Mik6PEJSPiZuYnNwOyZuYnNwOyZuYnNwOyBwcmludCAidDIiPEJSPiZuYnNwOyZuYnNwOyZuYnNw
OyBwcmludCB0MjwvUD4NCj48UD5maW5kKHQyLHJlZFswWzFdXSkmbmJzcDsgPC9QPg0KPjxQPjxT
VFJPTkc+YW5kIGdvdDo8L1NUUk9ORz48L1A+DQo+PFA+UHl0aG9uIDIuMS4xICgjMjAsIEp1bCAy
MCAyMDAxLCAwMToxOToyOSkgW01TQyAzMiBiaXQgKEludGVsKV0gb24gd2luMzI8QlI+VHlwZSAi
Y29weXJpZ2h0IiwgImNyZWRpdHMiIG9yICJsaWNlbnNlIiBmb3IgbW9yZSBpbmZvcm1hdGlvbi48
QlI+SURMRSAwLjggLS0gcHJlc3MgRjEgZm9yIGhlbHA8QlI+Jmd0OyZndDsmZ3Q7IDxCUj50MjxC
Uj5jdXRlIHJlZGhlYWQ8QlI+VHJhY2ViYWNrIChtb3N0IHJlY2VudCBjYWxsIGxhc3QpOjxCUj4m
bmJzcDsgRmlsZSAiQzpcUHl0aG9uMjFcVG9vbHNcaWRsZVxhbWVtYmVyc2hpcC5weSIsIGxpbmUg
MTAsIGluID88QlI+Jm5ic3A7Jm5ic3A7Jm5ic3A7IGZpbmQodDIscmVkWzBbMV1dKTxCUj5OYW1l
RXJyb3I6IG5hbWUgJ2ZpbmQnIGlzIG5vdCBkZWZpbmVkPEJSPjwvUD4NCj48UD48U1RST05HPmFt
IEkgYmFya2luZyB1cCB0aGUgcmlnaHQgdHJlZT88L1NUUk9ORz48L1A+DQo+PFA+dGhhbmtzIDwv
UD48cD48YnI+PGhyIHNpemU9MT48Yj5EbyBZb3UgWWFob28hPzwvYj48YnI+DQo+QnV5IHRoZSBw
ZXJmZWN0IGhvbGlkYXkgZ2lmdHMgYXQgPGENCj5ocmVmPSJodHRwOi8vcmQueWFob28uY29tL089
MS9JPWJyYW5kci1tYWlsZm9vdGVyLypodHRwOi8vc2hvcHBpbmcueWFob28uY29tIj5ZYWhvbyEg
U2hvcHBpbmc8L2E+Lg0KPi0tMC0xODU1OTcxMzgxLTEwMDc1MTgxNTg9OjQ3OTc4LS0NCj4NCj4N
Cj4tLV9fLS1fXy0tDQo+DQo+TWVzc2FnZTogMTANCj5EYXRlOiBUdWUsIDA0IERlYyAyMDAxIDIx
OjQzOjI3IC0wNTAwDQo+VG86IGpvaG4gcHVibGljIDxhcHl0aG9uMTAxQHlhaG9vLmNvbT4NCj5G
cm9tOiBQaWp1cyBWaXJrZXRpcyA8dmlya2V0aXNAZmFzLmhhcnZhcmQuZWR1Pg0KPlN1YmplY3Q6
IFJlOiBbVHV0b3JdIGZpbmQNCj5DYzogdHV0b3JAcHl0aG9uLm9yZw0KPg0KPi0tPT09PT09PT09
PT09PT09PT09PT09XzE3MjE2MDE5Nj09Xy5BTFQNCj5Db250ZW50LVR5cGU6IHRleHQvcGxhaW47
IGNoYXJzZXQ9InVzLWFzY2lpIg0KPg0KPg0KPj4NCj4+IGN1dGUgcmVkaGVhZA0KPj4gVHJhY2Vi
YWNrIChtb3N0IHJlY2VudCBjYWxsIGxhc3QpOg0KPj4gICBGaWxlICJDOlxQeXRob24yMVxUb29s
c1xpZGxlXGFtZW1iZXJzaGlwLnB5IiwgbGluZSAxMCwgaW4gPw0KPj4gICAgIGZpbmQodDIscmVk
WzBbMV1dKQ0KPj4gTmFtZUVycm9yOiBuYW1lICdmaW5kJyBpcyBub3QgZGVmaW5lZA0KPj4NCj4+
IGFtIEkgYmFya2luZyB1cCB0aGUgcmlnaHQgdHJlZT8NCj4NCj4NCj5XZWxsLCBpZiBJIHdlcmUg
eW91LCBJJ2QgYmUgYmFya2luZyB1cCB0aGF0IHZlcnkgc2FtZSB0cmVlIGFzIHdlbGwsIEpvaG4u
IDopDQo+SG93ZXZlciwgeW91ciBiYXJraW5nIHdvdWxkIGJlIG11Y2ggbW9yZSBmcnVpdGZ1bCwg
aWYgeW91IGltcG9ydGVkIHRoZSBzdHJpbmcNCj5tb2R1bGUgYmVmb3JlIHVzaW5nIGZpbmQoKS4g
U28sIGF0IHRoZSBiZWdpbm5pbmcgb2YgeW91ciBjb2RlLCBhZGQgdGhlDQo+Zm9sbG93aW5nOg0K
Pg0KPmltcG9ydCBzdHJpbmcNCj4NCj5UaGVuLCB5b3UgY2FuIHNheSBzb21ldGhpbmcgbGlrZSB0
aGlzOg0KPg0KPnN0cmluZy5maW5kKCJ0cmVlIiwgInJlIikgICAgICAgICAgICAgICAjY2hlY2tz
IGlmICJyZSIgaXMgaW4gInRyZWUiDQo+DQo+RG8gbm90IGZvcmdldCB0aGUgbW9kdWxlIG5hbWUg
YW5kIHRoZSBkb3QgYmVmb3JlIGZpbmQoKSEgWW91IG5lZWQgaXQsIGJlY2F1c2UNCj5maW5kKCkg
aXMgaW4gdGhlIHN0cmluZyBtb2R1bGUgbmFtZXNwYWNlLCBzbyBpZiB5b3Ugd2VyZSBvbWl0IHN0
cmluZy4qLCBQeXRob24NCj53b3VsZCBsb29rIGluIHRoZSBnbG9iYWwgbmFtZXNwYWNlIGZvciAi
ZmluZCIgYW5kIGl0IChwcm9iYWJseSkgd291bGQgbm90IGJlDQo+dGhlcmUuIEhlbmNlIHRoZSBl
cnJvciBtZXNzYWdlOiAibmFtZSAnZmluZCcgaXMgbm90IGRlZmluZWQuIiBUaGlzIGNvbWVzIGlu
DQo+cGFydGljdWxhcmx5IGhhbmR5IHdoZW4geW91IERPIGFjdHVhbGx5IGRlZmluZSBzb21lICJm
aW5kIiBvYmplY3Qgb2YgeW91ciBvd24sDQo+YW5kIHRoZW4gaW1wb3J0IHRoZSBzdHJpbmcgbW9k
dWxlLiBQeXRob24ga2VlcHMgeW91ciBmaW5kIGFuZCB0aGUNCj5zdHJpbmcuZmluZCgpDQo+Y29t
cGxldGVseSBzZXBhcmF0ZS4gVGhlIHRlcm0gZm9yIGl0IGlzIG5hbWVzcGFjZSBzZXBhcmF0aW9u
LiBUaGVyZSdzDQo+ZGVmaW5pdGVseSBtb3JlIHRvIGl0LCBidXQgSSB0aGluayB0aGlzIHNob3Vs
ZCBnZXQgeW91IHN0YXJ0ZWQuDQo+DQo+Q2hlZXJzLCANCj4NCj4tUA0KPi0tLS0tLS0tLS0tLS0t
LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLQ0KPlBHUCBQVUJM
SUMgS0VZOiB3d3cuZmFzLmhhcnZhcmQuZWR1L352aXJrZXRpcy9saW5rcw0KPk15IHdlYmxvZzog
d3d3LmZhcy5oYXJ2YXJkLmVkdS9+dmlya2V0aXMNCj4NCj4tLT09PT09PT09PT09PT09PT09PT09
PV8xNzIxNjAxOTY9PV8uQUxUDQo+Q29udGVudC1UeXBlOiB0ZXh0L2h0bWw7IGNoYXJzZXQ9InVz
LWFzY2lpIg0KPg0KPjxodG1sPg0KPjxibG9ja3F1b3RlIHR5cGU9Y2l0ZSBjaXRlPmN1dGUgcmVk
aGVhZDxicj4NCj5UcmFjZWJhY2sgKG1vc3QgcmVjZW50IGNhbGwgbGFzdCk6PGJyPg0KPiZuYnNw
OyBGaWxlICZxdW90O0M6XFB5dGhvbjIxXFRvb2xzXGlkbGVcYW1lbWJlcnNoaXAucHkmcXVvdDss
IGxpbmUgMTAsDQo+aW4gPzxicj4NCj4mbmJzcDsmbmJzcDsmbmJzcDsgZmluZCh0MixyZWRbMFsx
XV0pPGJyPg0KPk5hbWVFcnJvcjogbmFtZSAnZmluZCcgaXMgbm90IGRlZmluZWQ8YnI+DQo+PGJy
Pg0KPjxiPmFtIEkgYmFya2luZyB1cCB0aGUgcmlnaHQgdHJlZT88L2I+PC9ibG9ja3F1b3RlPjxi
cj4NCj5XZWxsLCBpZiBJIHdlcmUgeW91LCBJJ2QgYmUgYmFya2luZyB1cCB0aGF0IHZlcnkgc2Ft
ZSB0cmVlIGFzIHdlbGwsIEpvaG4uDQo+OikgSG93ZXZlciwgeW91ciBiYXJraW5nIHdvdWxkIGJl
IG11Y2ggbW9yZSBmcnVpdGZ1bCwgaWYgeW91IGltcG9ydGVkIHRoZQ0KPnN0cmluZyBtb2R1bGUg
YmVmb3JlIHVzaW5nIGZpbmQoKS4gU28sIGF0IHRoZSBiZWdpbm5pbmcgb2YgeW91ciBjb2RlLCBh
ZGQNCj50aGUgZm9sbG93aW5nOjxicj4NCj48YnI+DQo+aW1wb3J0IHN0cmluZzxicj4NCj48YnI+
DQo+VGhlbiwgeW91IGNhbiBzYXkgc29tZXRoaW5nIGxpa2UgdGhpczo8YnI+DQo+PGJyPg0KPnN0
cmluZy5maW5kKCZxdW90O3RyZWUmcXVvdDssDQo+JnF1b3Q7cmUmcXVvdDspPHgtdGFiPiZuYnNw
OyZuYnNwOyZuYnNwOyZuYnNwOyZuYnNwOyZuYnNwOyZuYnNwOzwveC10YWI+PHgtdGFiPiZuYnNw
OyZuYnNwOyZuYnNwOyZuYnNwOyZuYnNwOyZuYnNwOyZuYnNwOyZuYnNwOzwveC10YWI+I2NoZWNr
cw0KPmlmICZxdW90O3JlJnF1b3Q7IGlzIGluICZxdW90O3RyZWUmcXVvdDs8YnI+DQo+PGJyPg0K
PkRvIG5vdCBmb3JnZXQgdGhlIG1vZHVsZSBuYW1lIGFuZCB0aGUgZG90IGJlZm9yZSBmaW5kKCkh
IFlvdSBuZWVkIGl0LA0KPmJlY2F1c2UgZmluZCgpIGlzIGluIHRoZSBzdHJpbmcgbW9kdWxlIG5h
bWVzcGFjZSwgc28gaWYgeW91IHdlcmUgb21pdA0KPnN0cmluZy4qLCBQeXRob24gd291bGQgbG9v
ayBpbiB0aGUgZ2xvYmFsIG5hbWVzcGFjZSBmb3IgJnF1b3Q7ZmluZCZxdW90Ow0KPmFuZCBpdCAo
cHJvYmFibHkpIHdvdWxkIG5vdCBiZSB0aGVyZS4gSGVuY2UgdGhlIGVycm9yIG1lc3NhZ2U6ICZx
dW90O25hbWUNCj4nZmluZCcgaXMgbm90IGRlZmluZWQuJnF1b3Q7IFRoaXMgY29tZXMgaW4gcGFy
dGljdWxhcmx5IGhhbmR5IHdoZW4geW91IERPDQo+YWN0dWFsbHkgZGVmaW5lIHNvbWUgJnF1b3Q7
ZmluZCZxdW90OyBvYmplY3Qgb2YgeW91ciBvd24sIGFuZCB0aGVuIGltcG9ydA0KPnRoZSBzdHJp
bmcgbW9kdWxlLiBQeXRob24ga2VlcHMgeW91ciBmaW5kIGFuZCB0aGUgc3RyaW5nLmZpbmQoKQ0K
PmNvbXBsZXRlbHkgc2VwYXJhdGUuIFRoZSB0ZXJtIGZvciBpdCBpcyBuYW1lc3BhY2Ugc2VwYXJh
dGlvbi4gVGhlcmUncw0KPmRlZmluaXRlbHkgbW9yZSB0byBpdCwgYnV0IEkgdGhpbmsgdGhpcyBz
aG91bGQgZ2V0IHlvdSBzdGFydGVkLjxicj4NCj48YnI+DQo+Q2hlZXJzLCA8YnI+DQo+PGJyPg0K
Pi1QPGJyPg0KPjxkaXY+LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0t
LS0tLS0tLS0tLS0tLS0tLS0tPC9kaXY+DQo+PGRpdj5QR1AgUFVCTElDIEtFWToNCj48YSBocmVm
PSJodHRwOi8vd3d3LmZhcy5oYXJ2YXJkLmVkdS9+dmlya2V0aXMvbGlua3MiIEVVRE9SQT1BVVRP
VVJMPnd3dy5mYXMuaGFydmFyZC5lZHUvfnZpcmtldGlzL2xpbmtzPC9hPjwvZGl2Pg0KPjxkaXY+
TXkgd2VibG9nOg0KPjxhIGhyZWY9Imh0dHA6Ly93d3cuZmFzLmhhcnZhcmQuZWR1L352aXJrZXRp
cyIgRVVET1JBPUFVVE9VUkw+d3d3LmZhcy5oYXJ2YXJkLmVkdS9+dmlya2V0aXM8L2E+PC9kaXY+
DQo+PC9odG1sPg0KPg0KPi0tPT09PT09PT09PT09PT09PT09PT09XzE3MjE2MDE5Nj09Xy5BTFQt
LQ0KPg0KPg0KPg0KPi0tX18tLV9fLS0NCj4NCj5NZXNzYWdlOiAxMQ0KPkRhdGU6IFR1ZSwgNCBE
ZWMgMjAwMSAyMjoxNDo1OCAtMDUwMA0KPkZyb206IGRtYW4gPGRzaDgyOTBAcml0LmVkdT4NCj5U
bzogdHV0b3JAcHl0aG9uLm9yZw0KPlN1YmplY3Q6IFJlOiBbVHV0b3JdIGZpbmQNCj4NCj5PbiBU
dWUsIERlYyAwNCwgMjAwMSBhdCAwNjowOToxOFBNIC0wODAwLCBqb2huIHB1YmxpYyB3cm90ZToN
Cj4uLi4uDQo+fCBmaW5kKHQyLHJlZFswWzFdXSkgIA0KPg0KPmltcG9ydCBzdHJpbmcNCj5zdHJp
bmcuZmluZCggdDIgLCByZWRbMF1bMV0gKQ0KPg0KPndvdWxkIGJlIHdoYXQgeW91IG1lYW50Lg0K
Pg0KPkFzIG9mIHB5dGhvbiAyLjAgKG9yIHdhcyBpdCAyLjE/IEkgdGhpbmsgMi4wKSB5b3UgY2Fu
IHVzZSB0aGUgbWV0aG9kDQo+ZGlyZWN0bHkgb24gdGhlIHN0cmluZyBvYmplY3QgOg0KPg0KPnQy
LmZpbmQoIHJlZFswXVsxXSApDQo+DQo+SFRILA0KPi1EDQo+DQo+LS0gDQo+DQo+SWYgYW55IG9m
IHlvdSBsYWNrcyB3aXNkb20sIGhlIHNob3VsZCBhc2sgR29kLCB3aG8gZ2l2ZXMgZ2VuZXJvdXNs
eSB0bw0KPmFsbCB3aXRob3V0IGZpbmRpbmcgZmF1bHQsIGFuZCBpdCB3aWxsIGJlIGdpdmVuIHRv
IGhpbS4gIEJ1dCB3aGVuIGhlDQo+YXNrcyBoZSBtdXN0IGJlbGlldmUgYW5kIG5vdCBkb3VidCwg
YmVjYXVzZSBoZSB3aG8gZG91YnRzIGlzIGxpa2UgYSB3YXZlDQo+b2YgdGhlIHNlYSwgYmxvd24g
YW5kIHRvc3NlZCBieSB0aGUgd2luZC4NCj4gICAgICAgIEphbWVzIDE6NS02DQo+DQo+DQo+DQo+
DQo+LS1fXy0tX18tLQ0KPg0KPl9fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19f
X19fX19fX19fDQo+VHV0b3IgbWFpbGxpc3QgIC0gIFR1dG9yQHB5dGhvbi5vcmcNCj5odHRwOi8v
bWFpbC5weXRob24ub3JnL21haWxtYW4vbGlzdGluZm8vdHV0b3INCj4NCj4NCj5FbmQgb2YgVHV0
b3IgRGlnZXN0DQo=




From karshi.hasanov@utoronto.ca  Mon Dec 24 20:17:07 2001
From: karshi.hasanov@utoronto.ca (Karshi Hasanov)
Date: Mon, 24 Dec 2001 15:17:07 -0500
Subject: [Tutor] wxPython?
Message-ID: <20011224201809Z234648-13237+2@bureau8.utcc.utoronto.ca>

Hi all,

 I wanna use python GUI's , like wxPython or Tkinter. 
Which one would be easy to learn, or what 's advantage of using wxPython
than Tkinter?
Thanks


From egorbrandt@hotmail.com  Mon Dec 24 21:05:22 2001
From: egorbrandt@hotmail.com (Egor Brandt)
Date: Mon, 24 Dec 2001 22:05:22 +0100
Subject: [Tutor] unsuscribe
Message-ID: <OE671Gj03oHMwVN7miR00003f3b@hotmail.com>

------=_NextPart_001_0000_01C18CC7.150F7680
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable



Every hour wounds. The last one kills.
- Old SayingGet more from the Web.  FREE MSN Explorer download : http://e=
xplorer.msn.com

------=_NextPart_001_0000_01C18CC7.150F7680
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<HTML><BODY STYLE=3D"font:10pt verdana; border:none;"><DIV><BR><BR>Every =
hour wounds. The last one kills.<BR>- Old Saying</DIV></BODY></HTML><br c=
lear=3Dall><hr>Get more from the Web.  FREE MSN Explorer download : <a hr=
ef=3D'http://explorer.msn.com'>http://explorer.msn.com</a><br></p>

------=_NextPart_001_0000_01C18CC7.150F7680--


From shalehperry@attbi.com  Mon Dec 24 20:50:09 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 24 Dec 2001 12:50:09 -0800 (PST)
Subject: [Tutor] wxPython?
In-Reply-To: <20011224201809Z234648-13237+2@bureau8.utcc.utoronto.ca>
Message-ID: <XFMail.20011224125009.shalehperry@attbi.com>

On 24-Dec-2001 Karshi Hasanov wrote:
> Hi all,
> 
>  I wanna use python GUI's , like wxPython or Tkinter. 
> Which one would be easy to learn, or what 's advantage of using wxPython
> than Tkinter?

wxPython is newer and snazzy.  It also uses nicer looking widgets.  However it
is more likely to change and grow as it is still be actively developed.

Either one is fairly easy although there are more docs for tkinter. 


From ilflexi2@hotmail.com  Mon Dec 24 03:11:38 2001
From: ilflexi2@hotmail.com (Iain Long)
Date: Mon, 24 Dec 2001 03:11:38 +0000
Subject: [Tutor] (no subject)
Message-ID: <F17a0ZkfzDskqC5EtrU000001b8@hotmail.com>


I was reading about instant hacking so i clicked the windows icon and run 
and typed in notepad... and did an example that was shown...
   radius = 30

   print radius*radius*3.14 .... i don't know what to do next


_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp.



From civic525@hotmail.com  Mon Dec 24 17:21:41 2001
From: civic525@hotmail.com (Ted R.)
Date: Mon, 24 Dec 2001 11:21:41 -0600
Subject: [Tutor] pyhton
Message-ID: <OE51Wwr2UAaTzvb5YI900007307@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_000A_01C18C6D.29B164E0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

hello my name is ted and i have a few questions about pyhton. i have =
never worked with programing but i have worked with computers for a =
while. i am 15 so i have done more jovinial "cracking" like gameshark =
codes and gameshark hacking etc. after a while i got bored so i dicided =
to go into somthing were i could expand to a future carrier, so i =
started to look at computer programing, and a herd that python was the =
easieats and all around best. but to my question do you know any were it =
gives more "hands on traingin" and more in depth help.

also i cannot get this program to work maby you can tell me whats wrong?


>>>input("what is your name?") if ted print"hello ted" else: print"who =
are you?"



thank you   =20
               TeD

------=_NextPart_000_000A_01C18C6D.29B164E0
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#fffbf0>
<DIV><FONT face=3DArial size=3D2>hello my name is ted and i have a few =
questions=20
about pyhton. i have never worked with programing but i have worked with =

computers for a while. i am 15 so i have done more jovinial "cracking" =
like=20
gameshark codes and gameshark hacking etc. after a while i got bored so =
i=20
dicided to go into somthing were i could expand to a future carrier, so =
i=20
started to look at computer programing, and a herd that python was the =
easieats=20
and all around best. but to my question do you know any were it gives =
more=20
"hands on traingin" and more in depth help.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>also i cannot get this program to work =
maby you can=20
tell me whats wrong?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt;input("what is your name?") =
if ted=20
print"hello ted" else: print"who are you?"</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>thank you&nbsp;&nbsp;&nbsp; =
</FONT></DIV>
<DIV><FONT face=3DArial=20
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;=20
TeD</FONT></DIV></BODY></HTML>

------=_NextPart_000_000A_01C18C6D.29B164E0--


From deliberatus@my995internet.com  Mon Dec 24 23:12:28 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Mon, 24 Dec 2001 18:12:28 -0500
Subject: [Tutor] (no subject)
References: <F17a0ZkfzDskqC5EtrU000001b8@hotmail.com>
Message-ID: <3C27B65C.2834299E@my995internet.com>

WEll, try this:

def square(x)
	x*x

Then, try this:

pi = 3.1415926


def areacircle(x)
	return pi * square(x)

then, after you type those in, try this:

R = input("Please input the radius of the circle please?")
# That input will BOMB if you input anything but a number!
print areacircle(R)

Try it. Are we having fun yet?


 
Iain Long wrote:
> 
> I was reading about instant hacking so i clicked the windows icon and run
> and typed in notepad... and did an example that was shown...
>    radius = 30
> 
>    print radius*radius*3.14 .... i don't know what to do next
> 
> _________________________________________________________________
> Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp.
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From glingl@aon.at  Tue Dec 25 08:39:09 2001
From: glingl@aon.at (Gregor Lingl)
Date: Tue, 25 Dec 2001 09:39:09 +0100
Subject: [Tutor] (no subject)
References: <F17a0ZkfzDskqC5EtrU000001b8@hotmail.com> <3C27B65C.2834299E@my995internet.com>
Message-ID: <002b01c18d1f$9f8412a0$1664a8c0@mega>

----- Original Message -----
From: "Kirk Bailey" <deliberatus@my995internet.com>
To: "Iain Long" <ilflexi2@hotmail.com>
Cc: <tutor@python.org>
Sent: Tuesday, December 25, 2001 12:12 AM
Subject: Re: [Tutor] (no subject)

Unfortunately there are several flaws
concerning sytax as well as logic
in the code below, so it will not work:


> WEll, try this:
>
> def square(x)
> x*x

1. firsdt line needs an ":" at the end
2. second line has to be idented
3. This line will return  the special object
   None instead of the desired square of x
   Therefore the codeline in areacircle
   will raise an error

Correctly it should read:

def square(x):
    return x*x

>
> Then, try this:
>
> pi = 3.1415926

This is ok, but
Remark: instead of this you could also write

from math import pi

(just in case you cannot remember the desired
number of decimals of pi)
>
>
> def areacircle(x)
> return pi * square(x)
>

Again:
1. add ":" in the  def-line
2. indent second line

def areacircle(x):
   return pi * square(x)


> then, after you type those in, try this:
>
> R = input("Please input the radius of the circle please?")
> # That input will BOMB if you input anything but a number!
> print areacircle(R)
>
> Try it. Are we having fun yet?
>
>
>
> Iain Long wrote:
> >
> > I was reading about instant hacking so i clicked the windows icon and
run
> > and typed in notepad... and did an example that was shown...
> >    radius = 30
> >
> >    print radius*radius*3.14 .... i don't know what to do next
> >


I suppose, Iain, your problem is another one:
You want to know how to execute those two statements above.
It does not suffice to type it into an editor.
You may use either of two ways:

In any case you have to have installed you Python-interpreter. (You can
get it from http://www.python.org)


1. way:
-------
If you start it, you will see a prompt:

>>>

There you can input Python statements

>>> radius = 30
>>>

(If you doubt, that this changes something in your computer,
you may type:

>>> radius
30
>>>

So this value 30 is stored in a variable called radius)

Then continue:

>>> print radius*radius*4.14
2826.0

... prints the interpreter


2. way:
-------

Youo save, what you typed into notepad as a Python-script,
for instance as circle.py

Then you ask your interpreter to execute it:

open the MSDOS-prompt (or a terminal, a shell or whatever if you
doesn't use Windows) and type

c:\Python21>python circle.py

This will result in displaying

2826.0


Hope that helps
Gregor

_________________________________________________________________
> > Get your FREE download of MSN Explorer at
http://explorer.msn.com/intl.asp.
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
> --
> Respectfully,
>              -Kirk D Bailey (C)2001
>               Addme! icq #27840081
> end
>
>
> Within the sweep of his sword, Each man is an Ubar.
>
> http://www.howlermonkey.net/
> http://www.sacredelectron.org/
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From dyoo@hkn.eecs.berkeley.edu  Tue Dec 25 19:13:27 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 25 Dec 2001 11:13:27 -0800 (PST)
Subject: [Tutor] (no subject)   [Starting Python]
In-Reply-To: <F17a0ZkfzDskqC5EtrU000001b8@hotmail.com>
Message-ID: <Pine.LNX.4.21.0112241344040.3459-100000@hkn.eecs.berkeley.edu>

On Mon, 24 Dec 2001, Iain Long wrote:

> I was reading about instant hacking so i clicked the windows icon and
> run and typed in notepad... and did an example that was shown...
>
>    radius = 30
> 
>    print radius*radius*3.14 .... i don't know what to do next

Hi Iain,

Glad to hear that you're starting to learn Python.  Please feel free to
ask questions here on Tutor; we'll try to answer them as well as we can!


About your question: it depends on what you want to do.  It sounds like
you'd like to start fiddling around with Python.  You can take a tour
through Python with this link:

    http://python.org/doc/Newbies.html

This link is connected to many good Python tutorials, and you'll get a
better feeling for what we can do with Python here.


If you haven't been able to get:

>    radius = 30
> 
>    print radius*radius*3.14

working yet, you might find this introduction useful:

    http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro

It shows, step by step, how to use the text editor that comes with Python.


Best of wishes to you.



From dyoo@hkn.eecs.berkeley.edu  Tue Dec 25 19:28:10 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 25 Dec 2001 11:28:10 -0800 (PST)
Subject: [Tutor] pyhton
In-Reply-To: <OE51Wwr2UAaTzvb5YI900007307@hotmail.com>
Message-ID: <Pine.LNX.4.21.0112251120560.14019-100000@hkn.eecs.berkeley.edu>

On Mon, 24 Dec 2001, Ted R. wrote:

> hello my name is ted and i have a few questions about pyhton. i have

Hi Ted, welcome to Tutor!


> never worked with programing but i have worked with computers for a
> while. i am 15 so i have done more jovinial "cracking" like gameshark
> codes and gameshark hacking etc. after a while i got bored so i
> dicided to go into somthing were i could expand to a future carrier,
> so i started to look at computer programing, and a herd that python
> was the easieats and all around best. but to my question do you know
> any were it gives more "hands on traingin" and more in depth help.


We'll do what we can to help you; please feel free to ask questions
anytime.


> also i cannot get this program to work maby you can tell me whats
> wrong?
> 
> 
> >>>input("what is your name?") if ted print"hello ted" else: print"who
> are you?"


Hmmm...  can you try this from the IDLE editor?  Here's a web site that
might help you get started:

    http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro


Also, is that command all on one line?  You might want to do this instead:


###
name = raw_input("what is your name?")
if name == "ted":
    print "hello ted"
else:
    print "who are you?"
###

(I'm putting pound signs here to separate it from the message here; you
don't have to type them)  I've changed some of the commands so that they
work better --- raw_input() is easier to get working right than input(),
and we can talk about this more when you want.

Also, in Python, indentation matters, so it does make a difference when we
put things in lines and columns.  Tell us if this works for you.



Good luck!  Again, if you have questions, please feel free to talk to us.  
We might be a little less responsive than usual since it's the holidays,
but we'll try to reply quickly.



From dyoo@hkn.eecs.berkeley.edu  Tue Dec 25 19:32:52 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 25 Dec 2001 11:32:52 -0800 (PST)
Subject: [Tutor] wxPython?
In-Reply-To: <20011224201809Z234648-13237+2@bureau8.utcc.utoronto.ca>
Message-ID: <Pine.LNX.4.21.0112251128160.14019-100000@hkn.eecs.berkeley.edu>

On Mon, 24 Dec 2001, Karshi Hasanov wrote:

>  I wanna use python GUI's , like wxPython or Tkinter. 
> Which one would be easy to learn, or what 's advantage of using wxPython
> than Tkinter?

Both are pretty nice.  I think that Tkinter is easier to learn, but many
people feel that Tkinter looks ugly.  *grin*


Tkinter is also installed by default when we install Python, so it's used
quite a lot.  Have you seen Fredrik Lungh's 'An Introduction to Tkinter'
web site?

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

It's a great tutorial on Tkinter programming.  Take a look at it, and see
if Tkinter is a good fit.

Good luck!



From dyoo@hkn.eecs.berkeley.edu  Tue Dec 25 20:02:31 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 25 Dec 2001 12:02:31 -0800 (PST)
Subject: [Tutor] A little help please
In-Reply-To: <3C277461.2010401@netscape.net>
Message-ID: <Pine.LNX.4.21.0112251150420.14019-100000@hkn.eecs.berkeley.edu>

On Mon, 24 Dec 2001, nova812 wrote:

> I'm in need of a function that will work on both a linux box and a
> windows box that, from the command line, will detect a key hit on the
> keyboard.

If it were only Linux, I'd recommend the "curses" module:

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

However, I'm not sure how successfully the 'curses' module works on
Windows systems.  There's an introductory article on curses here:

    http://www-106.ibm.com/developerworks/linux/library/l-python6.html


> the function should return -1 for no key hit detected and the ascii
> code for any other key hit.

This is possible to do.  By default, if no key hasn't been hit yet, the
getch() function raises an exception, but we can write a small wrapper
function that does something more reasonable.


###
import curses
stdscr = curses.initscr()
curses.cbreak()

def getKey():
    try:
        return stdscr.getch()
    except:
        return -1
###


Good luck!



From karthikg@aztec.soft.net  Wed Dec 26 06:44:17 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Wed, 26 Dec 2001 12:14:17 +0530
Subject: [Tutor] list as a first class citizen in python?
In-Reply-To: <20011224201809Z234648-13237+2@bureau8.utcc.utoronto.ca>
Message-ID: <NEBBJNMDEKBIBCMCNMBDAEEFCMAA.karthikg@aztec.soft.net>

I found this quote on the web..regarding python...

>>>>>>>
    Because everything is a reference, and there's no way to dereference
    that reference, it turns out that there is no trivial way to copy
    a list!  This fails:
	x = [1,2]
	y = x
    Because you don't get a new list there, just a copy to an
    old one.  Suggested work-arounds include
	y = x[0:]
	y = x[:]
	y = x + []
	y = x * 1
    This forces people to think about references, again.
    So much for lists being first class citizens!  Compare
    this with Perl's
	@x = (1,2);
	@y = @x;
    Or even with references:
	$x = [1,2];
	$y = [ @$x ];
    or
	@y = @$x;
>>>>>>>>

what's wrong with working with a reference.
can someone explain the argument here?
java does a similar thing. In java i would do a clone() to get a copy of an
arraylist and in python i will

import copy
copy.deepcopy(l)

if something is a first class citizen , should it support "copying" using
simple assignments ? / how are first class citizens expected to behave ? :-)

thanks,
karthik.




From dyoo@hkn.eecs.berkeley.edu  Wed Dec 26 08:16:41 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 26 Dec 2001 00:16:41 -0800 (PST)
Subject: [Tutor] list as a first class citizen in python? [language
 comparisons!]
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDAEEFCMAA.karthikg@aztec.soft.net>
Message-ID: <Pine.LNX.4.21.0112252326410.20439-100000@hkn.eecs.berkeley.edu>

[Warning; this message has quite a bit of Perl code in it.  It also
borders on silly language war stuff.  My apologies!]



On Wed, 26 Dec 2001, Karthik Gurumurthy wrote:

>     Because everything is a reference, and there's no way to dereference
>     that reference, it turns out that there is no trivial way to copy
>     a list!  This fails:
> 	x = [1,2]
> 	y = x
>     Because you don't get a new list there, just a copy to an
>     old one.

The wording is getting REALLY loose here.  There is no "copy" to talk
about: 'y' and 'x' are refering to the same list.  For example:

###
>>> x = [1, 2]
>>> y = x
>>> id(x)
135040592
>>> id(y)
135040592
###

id() is something of a low-level function, so it's not really important in
casual Python use.  id() tells us where in memory an object is located.  
In the example above, we can see that 'x' and 'y' are just names for the
list value '[1, 2]', because they have the same "id".


>     Suggested work-arounds include
> 	y = x[0:]
> 	y = x[:]
> 	y = x + []
> 	y = x * 1
>     This forces people to think about references, again.

Python doesn't automatically create new lists until we tell it to.  This
can be both an advantage and a disadvantage.  I consider it a design
decision, not a flaw as the word 'work-around' suggests... *grin*


I'm not quite sure what they mean about not being able to copy a list
"trivially" though.  The 'copy' module,

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

is a nice way of abstracting the shallow copying of a data structure:

###
>>> y = copy.copy(x)
>>> id(y)
135041912
>>> id(x)
135040592
###

and works uniformly on the standard Python data types.



>     So much for lists being first class citizens!

Again, I'm not quite sure what they mean here.  If they mean "first class"
as in:

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

then I personally don't see anything about Python lists that doesn't make
it "first class".



>  Compare
>     this with Perl's
> 	@x = (1,2);
> 	@y = @x;
>     Or even with references:
> 	$x = [1,2];
> 	$y = [ @$x ];
>     or
> 	@y = @$x;
> >>>>>>>>
> 
> what's wrong with working with a reference.
>
> can someone explain the argument here?


I don't think it's an argument; I think it's more of a language preference
thing.

Perl does make it nice to work with flat data structures, but as soon as
we get into nested data structures, Perl programmers have to worry about
the exact same details about copying that Python programmers think about.  
Here's an example in Perl that's similar to the situation the author was
pointing out:

### # Perl code
use Data::Dumper;
@x = ([1,2], [3, 4]);
@y = @x;
$x[0][0] = 42;
print Dumper(@x);
print Dumper(@y);
###

This shows that Perl programmers do need to deal with the same issues as
Python programmers.  There is no magical cure here, nor just one best way
to approach things.



One other advantage of having everything as a "reference" in Python is
that Python functions don't need to do anything special when taking in
many lists as parameters:

###
def myzip(l1, l2):
    results = []
    for i in range(len(l1)):
        results.append(l1[i])
        results.append(l2[i])
    return results
###

###
>>> myzip([1, 2, 3], [4, 5, 6])
[1, 4, 2, 5, 3, 6]
###


But to get the same thing to work in Perl, we have to think twice.  A
first attempt:

###
## test.pl.
sub buggy_myzip {
    my (@l1, @l2) = @_;
    my @results;
    for my $i (0..scalar(@l1)) {
        push(@results, $l1[$i]);
        push(@results, $l2[$i]);
    }
    return @results;
}

@l1 = (1, 2, 3);
@l2 = (4, 5, 6);
print join " ", buggy_myzip(@l1, @l2), "\n";
###


won't work the way a beginner might expect!  Take a look:

###
[dyoo@hkn dyoo]$ perl test.pl
1  2  3  4  5  6
###


Here's a fixed version:

###
sub myzip {
    my ($l1, $l2) = @_;
    my @results;
    for my $i (0..scalar(@$l1)) {
        push(@results, $l1->[$i]);
        push(@results, $l2->[$i]);
    }
    return @results;
}

@l1 = (1, 2, 3);
@l2 = (4, 5, 6);
print join " ", myzip(\@l1, \@l2), "\n";
###

And this works.  But to make this "simple" function work, a Perl
programmer does need to be aware of array references.  I'd better stop
before I offend the Python and Perl Gods any further.  *grin*

Hope this helps!



From dyoo@hkn.eecs.berkeley.edu  Wed Dec 26 08:29:59 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 26 Dec 2001 00:29:59 -0800 (PST)
Subject: [Tutor] list as a first class citizen in python? [language
 comparisons!]
In-Reply-To: <Pine.LNX.4.21.0112252326410.20439-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.21.0112260026100.20439-100000@hkn.eecs.berkeley.edu>

> But to get the same thing to work in Perl, we have to think twice.  A
> first attempt:
> 
> ###
> ## test.pl.
> sub buggy_myzip {
>     my (@l1, @l2) = @_;
>     my @results;
>     for my $i (0..scalar(@l1)) {
                    ^^^^^^^^^^

Yikes.  This is buggy for another reason.  Python's range() function is
exclusive: it goes up to, but doesn't include the right endpoint:

###
>>> range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
###



However, Perl's equivlant expression does include that right endpoint.  
Sorry, I forgot!  This line should have been:

### Perl
      for my $i (0..#@l1)) {
###



From dyoo@hkn.eecs.berkeley.edu  Wed Dec 26 08:36:53 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 26 Dec 2001 00:36:53 -0800 (PST)
Subject: [Tutor] list as a first class citizen in python? [language
 comparisons!]
In-Reply-To: <Pine.LNX.4.21.0112260026100.20439-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.21.0112260030570.20439-100000@hkn.eecs.berkeley.edu>

On Wed, 26 Dec 2001, Danny Yoo wrote:

> However, Perl's equivlant expression does include that right endpoint.  
> Sorry, I forgot!  This line should have been:
> 
> ### Perl
>       for my $i (0..#@l1)) {


Doh.  I meant:

>       for my $i (0..$#l1)) {

My fingers slipped.  When I goof up, I goof up big.  *sigh*


Ok, I'd better stop talking about Perl and get back to Python.



From karthikg@aztec.soft.net  Wed Dec 26 09:05:10 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Wed, 26 Dec 2001 14:35:10 +0530
Subject: [Tutor] list as a first class citizen in python? [languagecomparisons!]
In-Reply-To: <Pine.LNX.4.21.0112252326410.20439-100000@hkn.eecs.berkeley.edu>
Message-ID: <NEBBJNMDEKBIBCMCNMBDIEEGCMAA.karthikg@aztec.soft.net>

thanks ,
from your code snippet, the list thing in perl seems odd though.
everything gets flattened out in the end? unless i do somethign about it.
So this w'd work in perl then??

//function definition
def func(a,b):


//arguments
args = [1,2]
//call function
func(args)

so they don't need an apply as we do in python?
now am not sure which one is better. having learnt java first, i w'd go with
python :-)
am not qualified enough to make comparisons, but i was confused  by these
lines
i found...

>This forces people to think about references, again
>So much for lists being first class citizens!

thanks. have to do a read up on the "first class" things though.

karthik.








From karthikg@aztec.soft.net  Wed Dec 26 09:11:38 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Wed, 26 Dec 2001 14:41:38 +0530
Subject: [Tutor] list as a first class citizen in python? [languagecomparisons!]
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDIEEGCMAA.karthikg@aztec.soft.net>
Message-ID: <NEBBJNMDEKBIBCMCNMBDCEEHCMAA.karthikg@aztec.soft.net>

oops sorry !
am not sure if the code is ok with perl.
i just wanted to ask if a function expects 2 arguments, i can send in a list
w/o using an apply.
they don't have to be specified separately while making the function call.

karthik.


-----Original Message-----
From: karthik Guru [mailto:karthikg@aztec.soft.net]
Sent: Wednesday, December 26, 2001 2:35 PM
To: Danny Yoo
Cc: tutor@python.org
Subject: RE: [Tutor] list as a first class citizen in python?
[languagecomparisons!]
Importance: High


thanks ,
from your code snippet, the list thing in perl seems odd though.
everything gets flattened out in the end? unless i do somethign about it.
So this w'd work in perl then??

//function definition
def func(a,b):


//arguments
args = [1,2]
//call function
func(args)

so they don't need an apply as we do in python?
now am not sure which one is better. having learnt java first, i w'd go with
python :-)
am not qualified enough to make comparisons, but i was confused  by these
lines
i found...

>This forces people to think about references, again
>So much for lists being first class citizens!

thanks. have to do a read up on the "first class" things though.

karthik.








From dyoo@hkn.eecs.berkeley.edu  Wed Dec 26 09:10:32 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 26 Dec 2001 01:10:32 -0800 (PST)
Subject: [Tutor] Pointer to learn.perl.org
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDIEEGCMAA.karthikg@aztec.soft.net>
Message-ID: <Pine.LNX.4.21.0112260052520.21348-100000@hkn.eecs.berkeley.edu>

On Wed, 26 Dec 2001, Karthik Gurumurthy wrote:

> from your code snippet, the list thing in perl seems odd though.
> everything gets flattened out in the end? unless i do somethign about it.

I didn't mean to get into Perl so much here.  Yes, Perl will flatten
arrays automatically when they're passed as arguments.



> am not sure if the code is ok with perl. i just wanted to ask if a
> function expects 2 arguments, i can send in a list w/o using an apply.
> they don't have to be specified separately while making the function
> call.

The way that Perl passes arguments to a function makes something like
Python's apply()... inapplicable in Perl.


If you'd like to learn more about Perl, the Perl folks have a nice web
site with resources:

    http://learn.perl.org

with an equivalent "Beginners" mailing list.  If you want to talk more
about Perl, the people there would be happy to discuss this sort of stuff.  
As it is, I'm feeling very uncomfortable about explaining Perl parameter
passing on Python-Tutor.  *grin*


Happy holidays!



From karthikg@aztec.soft.net  Wed Dec 26 11:04:54 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Wed, 26 Dec 2001 16:34:54 +0530
Subject: [Tutor] my __new__ not getting called before __init__
In-Reply-To: <20011224201809Z234648-13237+2@bureau8.utcc.utoronto.ca>
Message-ID: <NEBBJNMDEKBIBCMCNMBDEEEICMAA.karthikg@aztec.soft.net>

Is something wrong with this code?
when i run it using python2.2 Singleton's __init__ is getting called
and not HoldThis's __init__.

http://www.python.org/2.2/descrintro.html

says the __new__ is always called before __init__.

thanks,
karthik.

<code>
class HoldThis:
    def __init__(self,arg):
        print "KeepThis called with " + arg
        self.val = arg
    def func(self):
        print self.val
        
class Singleton:
    __instance=None

    def __init__(self,arg):
        print "Singleton called"
    def __new__(cls,arg):
        print "__new__ called"
        if not Singleton.__instance:
            Singleton.__instance = HoldThis(arg)
        else:
            Singleton.__instance.val = arg
        return Singleton.__instance
    def __getattr__(self,name):
        return getattr(Singleton.__instance,name)
    def __setattr__(self,name,value):
        setattr(Singleton.__instance,name,value)

</code>



From r.b.rigilink@chello.nl  Wed Dec 26 12:03:42 2001
From: r.b.rigilink@chello.nl (Roeland Rengelink)
Date: Wed, 26 Dec 2001 13:03:42 +0100
Subject: [Tutor] my __new__ not getting called before __init__
References: <NEBBJNMDEKBIBCMCNMBDEEEICMAA.karthikg@aztec.soft.net>
Message-ID: <3C29BC9E.68190A2@chello.nl>

Hi Karthik,

For this to work you must make sure that Singleton is a new style class
by deriving it from object

This works partially:

class HoldThis:
    def __init__(self,arg):
        # note ',' instead of '+' on next line
        print "KeepThis called with ", arg 
        self.val = arg
    def func(self):
        print self.val
        
class Singleton(object):
    __instance=None

    def __init__(self,arg):
        print "Singleton called"
    def __new__(cls,arg):
        print "__new__ called"
        if not Singleton.__instance:
            Singleton.__instance = HoldThis(arg)
        else:
            Singleton.__instance.val = arg
        return Singleton.__instance
    def __getattr__(self,name):
        return getattr(Singleton.__instance,name)
    def __setattr__(self,name,value):
        setattr(Singleton.__instance,name,value)

Singleton(1)
Singleton(1)

It gives the following result:

__new__ called
KeepThis called with  1
__new__ called

HoldThis.__init__ is called because of the line 

Singleton.__instance = HoldThis(arg)

If you also derive HoldThis from 'object' You get the following result:

__new__ called
KeepThis called with  1
KeepThis called with  1
__new__ called
KeepThis called with  1

Which is in line with the descriptor doc (__new__ called before
__init__), although maybe not in the way you might expect
(Holdhis.__init__ is calles, not Singleton.__init__).

Object instantiation (new style) is implemented roughly equivalent to:

def __call__(cls, *args, **kwargs):
    instance = cls.__new__(*args, **kwargs)
    type(instance).__init__(instance, *args, **kwargs)
    return instance

Note that type(HoldThis()) in the classic case is InstanceType, which
has only a default (no-op) __init__ method. In the new style case
type(HoldThis()) is HoldThis

No idea if this works as an explanation. Let me know if you need
additional clarification

Roeland

Karthik Gurumurthy wrote:
> 
> Is something wrong with this code?
> when i run it using python2.2 Singleton's __init__ is getting called
> and not HoldThis's __init__.
> 

That was because Singleton.__new__ was not being called

> http://www.python.org/2.2/descrintro.html
> 
> says the __new__ is always called before __init__.
> 
> thanks,
> karthik.
> 
> <code>
[snip]
> </code>

Roeland 
-- 
r.b.rigilink@chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"



From kp87@lycos.com  Wed Dec 26 13:29:21 2001
From: kp87@lycos.com (kevin parks)
Date: Wed, 26 Dec 2001 22:29:21 +0900
Subject: [Tutor] Re: file filter
Message-ID: <KCBIPIKHFBFDCAAA@mailcity.com>

Hi all,

Happy Holidays. I am trying to write a some python code that will copy a file to a new file but with certain lines filtered out. Let's say that i want the new file to have all lines except those that start with a semicolon or a letter c. So that an input file that has these lines:

;i1 0 1 2 3 2
i1 6 8 7 9 
ci2 99 0 0 0 2
i1 2 3 4
i2 3 4 4 
ci1 3 4 4 5
;i3 929 92 2
i4 2 8 9 1

would yield:

i1 2 3 4
i2 3 4 4 
i4 2 8 9 1

i can get the copy part. It is just the filter part i am confused about. You see, if the line begins with 'c' or ';' i want to ignore the whole line.


cheers,

kevin


def boksa(infilename, outfilename):
	"""this will copy a file exactly, args are: 'infile' and 'outfile'"""
	infile = open(infilename, 'r')
	f = open(outfilename, 'w')
	for aLine in infile.xreadlines() :
		f.write( aLine )
	infile.close()
	f.close()

if __name__ == '__main__':
	boksa()






--
Click here for your very own create-a-date adventure from MatchMaker
Go to http://ecard.matchmaker.com/dating.html


From karthikg@aztec.soft.net  Wed Dec 26 13:49:34 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Wed, 26 Dec 2001 19:19:34 +0530
Subject: [Tutor] my __new__ not getting called before __init__
In-Reply-To: <3C29BC9E.68190A2@chello.nl>
Message-ID: <NEBBJNMDEKBIBCMCNMBDEEEJCMAA.karthikg@aztec.soft.net>

yep it helped! thanks for sending in the code for the way instantiation
works!
i need to admit this group is so helpful!

karthik.

-----Original Message-----
From: roeland@param.aztec.soft.net
[mailto:roeland@param.aztec.soft.net]On Behalf Of Roeland Rengelink
Sent: Wednesday, December 26, 2001 5:34 PM
To: Karthik Gurumurthy
Cc: tutor@python.org
Subject: Re: [Tutor] my __new__ not getting called before __init__


Hi Karthik,

For this to work you must make sure that Singleton is a new style class
by deriving it from object

This works partially:

class HoldThis:
    def __init__(self,arg):
        # note ',' instead of '+' on next line
        print "KeepThis called with ", arg
        self.val = arg
    def func(self):
        print self.val

class Singleton(object):
    __instance=None

    def __init__(self,arg):
        print "Singleton called"
    def __new__(cls,arg):
        print "__new__ called"
        if not Singleton.__instance:
            Singleton.__instance = HoldThis(arg)
        else:
            Singleton.__instance.val = arg
        return Singleton.__instance
    def __getattr__(self,name):
        return getattr(Singleton.__instance,name)
    def __setattr__(self,name,value):
        setattr(Singleton.__instance,name,value)

Singleton(1)
Singleton(1)

It gives the following result:

__new__ called
KeepThis called with  1
__new__ called

HoldThis.__init__ is called because of the line

Singleton.__instance = HoldThis(arg)

If you also derive HoldThis from 'object' You get the following result:

__new__ called
KeepThis called with  1
KeepThis called with  1
__new__ called
KeepThis called with  1

Which is in line with the descriptor doc (__new__ called before
__init__), although maybe not in the way you might expect
(Holdhis.__init__ is calles, not Singleton.__init__).

Object instantiation (new style) is implemented roughly equivalent to:

def __call__(cls, *args, **kwargs):
    instance = cls.__new__(*args, **kwargs)
    type(instance).__init__(instance, *args, **kwargs)
    return instance

Note that type(HoldThis()) in the classic case is InstanceType, which
has only a default (no-op) __init__ method. In the new style case
type(HoldThis()) is HoldThis

No idea if this works as an explanation. Let me know if you need
additional clarification

Roeland

Karthik Gurumurthy wrote:
>
> Is something wrong with this code?
> when i run it using python2.2 Singleton's __init__ is getting called
> and not HoldThis's __init__.
>

That was because Singleton.__new__ was not being called

> http://www.python.org/2.2/descrintro.html
>
> says the __new__ is always called before __init__.
>
> thanks,
> karthik.
>
> <code>
[snip]
> </code>

Roeland
--
r.b.rigilink@chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"


From karthikg@aztec.soft.net  Wed Dec 26 13:55:02 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Wed, 26 Dec 2001 19:25:02 +0530
Subject: [Tutor] Re: file filter
In-Reply-To: <KCBIPIKHFBFDCAAA@mailcity.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDOEEJCMAA.karthikg@aztec.soft.net>

startswith method should help here..

def boksa(infilename, outfilename):
	"""this will copy a file exactly, args are: 'infile' and 'outfile'"""
	infile = open(infilename, 'r')
	f = open(outfilename, 'w')
	for aLine in infile.xreadlines() :
		if not (aLine.startswith(';') or aLine.startswith('c')):
			f.write( aLine )
	infile.close()
	f.close()

string module has lots of helpful methods.

karthik.

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
kevin parks
Sent: Wednesday, December 26, 2001 6:59 PM
To: tutor@python.org
Subject: [Tutor] Re: file filter


Hi all,

Happy Holidays. I am trying to write a some python code that will copy a
file to a new file but with certain lines filtered out. Let's say that i
want the new file to have all lines except those that start with a semicolon
or a letter c. So that an input file that has these lines:

;i1 0 1 2 3 2
i1 6 8 7 9
ci2 99 0 0 0 2
i1 2 3 4
i2 3 4 4
ci1 3 4 4 5
;i3 929 92 2
i4 2 8 9 1

would yield:

i1 2 3 4
i2 3 4 4
i4 2 8 9 1

i can get the copy part. It is just the filter part i am confused about. You
see, if the line begins with 'c' or ';' i want to ignore the whole line.


cheers,

kevin


def boksa(infilename, outfilename):
	"""this will copy a file exactly, args are: 'infile' and 'outfile'"""
	infile = open(infilename, 'r')
	f = open(outfilename, 'w')
	for aLine in infile.xreadlines() :
		f.write( aLine )
	infile.close()
	f.close()

if __name__ == '__main__':
	boksa()






--
Click here for your very own create-a-date adventure from MatchMaker
Go to http://ecard.matchmaker.com/dating.html

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


From i812@iname.com  Wed Dec 26 14:05:07 2001
From: i812@iname.com (Rob McGee)
Date: Wed, 26 Dec 2001 08:05:07 -0600
Subject: [Tutor] Modules/Setup in 2.2 source package
Message-ID: <20011226080507.G3310@hal>

I'm a little confused about Modules/Setup in Python 2.2. If I do nothing
to it, does that mean I get none of those modules? That seems like an
unusual amount of manual labor for configuring a package. :)

I'm upgrading from 2.0.1 which came with Slackware 8. I think I built
2.0 from source before that, and I don't recall having to do so much to
it to make it work. But maybe that was because I didn't do much with it.

Thanks,
    Rob - /dev/rob0


From alan.gauld@bt.com  Wed Dec 26 16:27:06 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 26 Dec 2001 16:27:06 -0000
Subject: [Tutor] A little help please
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C203@mbtlipnt02.btlabs.bt.co.uk>

> I'm in need of a function that will work on both a linux box and a 
> windows box that, from the command line, will detect a key hit 
> on the keyboard.  

There is no portable way of doing this(*) in standard Python but
you can do it by using two distinct modules:

msvcrt for Windows and curses for Linux

They both have similar getch() functions and you could test 
for the OS at the top of the function. Something like:

def getkey():
   if os == windows or NT or DOS:
      return msvcrt.getch()
   elif os == posix:
      return curses.wgetch()
   else: return raw_input()  # don't know how to read instant keys...

I suspect you will need to write an init function for the 
curses stuff to set up the virtual screen that cureses uses.

Note that the functions will wait for input (ie not like 
BASIC INKEY$) but do not wait for an ENTER key.

> -1 for no key hit detected and the ascii code for any other 
> key hit.  

To get the -1 for no key hit you will need to do something 
clever to arrange a timeout.... Maybe launching a thread 
then killing it after a delay, thats getting trickier...

> of this function would be function keys.  

The msvcrt.getch works with function keys etc, I don't 
remember how curses.wgetch works.

You might like to take a peek at my online tutor under 
Event Driven programming to see an example, if you can 
find a copy of my book even better since it shows 
msvcrt.getch in action.


HTH,

Alan G.

(*) Fred Lundh has a console module that tries to be OS 
independant but I can't recall if it has a getch function.


From alan.gauld@bt.com  Wed Dec 26 16:33:57 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 26 Dec 2001 16:33:57 -0000
Subject: [Tutor] wxPython?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C204@mbtlipnt02.btlabs.bt.co.uk>

>  I wanna use python GUI's , like wxPython or Tkinter. 
> Which one would be easy to learn, 

See my online tutor under GUI program for a very gentle intro
to both. For Tkinter theres a full tutor if you follow the 
links from the Tkinter area of the python web site. wxPython 
has a basic tutor on its main site but it requires a bit of 
experience in GUI programming in general IMHO.

> what 's advantage of using wxPython
> than Tkinter?

wxPython looks slightly nicer and has a richer set of widgets.
Tkinter is arguably more portable across both platforms and 
languages and is indisputably better documented in both books 
and online documents.

Alan g.


From alan.gauld@bt.com  Wed Dec 26 16:42:59 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 26 Dec 2001 16:42:59 -0000
Subject: [Tutor] pyhton
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C205@mbtlipnt02.btlabs.bt.co.uk>

------_=_NextPart_001_01C18E2C.60F13410
Content-type: text/plain; charset="iso-8859-1"

>  hello my name is ted and i have a few questions about pyhton. i have
never  
>  worked with programing but i have worked with computers for a while.  
 
Thats my target audience on my web tutor :-)
 
 > do you know any were it gives more "hands on traingin" and more in depth
help. 
 
Visit the Python web site and go to the Intros and Begginers 
sections where several tutors exist, including mine. 

also i cannot get this program to work maby you can tell me whats wrong?
 
>>>input("what is your name?") if ted print"hello ted" else: print"who are
you?"
 

Split it onto several lines:
 
>>> name = raw_input("Whats your name? ")   #use raw_input for characters
Whats your name? ted
>>> if name == "ted":   # must have a colon ':' after the test
...       print "Hello ted"
... else: print "Who are you?"
...
Hello ted
>>>
 
You are very close but there's a few concepts missing. Try one of the tutors
and 
don't rush it, there's a lot of things to pick up at the beginning, if you
miss them 
early on it will just make life harder later on as you have to unlearn bad
habits.
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_01C18E2C.60F13410
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=#fffbf0>
<DIV><FONT face=Arial><FONT size=2><SPAN class=230464116-26122001><FONT 
face="Courier New" color=#0000ff>&gt; &nbsp;</FONT></SPAN>hello my name is ted 
and i have a few questions about pyhton. i have never&nbsp;<SPAN 
class=230464116-26122001><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=230464116-26122001><FONT 
face="Courier New" color=#0000ff>&gt; </FONT>&nbsp;</SPAN>worked with programing 
but i have worked with computers for a while.&nbsp;<SPAN 
class=230464116-26122001><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=230464116-26122001></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=230464116-26122001>Thats my 
target audience on my web tutor :-)</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=230464116-26122001></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=230464116-26122001><FONT 
face="Courier New" color=#0000ff>&nbsp;&gt;&nbsp;</FONT></SPAN>do you know any 
were it gives more "hands on traingin" and more in depth help.<SPAN 
class=230464116-26122001><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=230464116-26122001></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=230464116-26122001><FONT 
face="Courier New" color=#0000ff>Visit the Python web site and go to the Intros 
and Begginers </FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=230464116-26122001><FONT 
face="Courier New" color=#0000ff>sections where several tutors exist, including 
mine.</FONT>&nbsp;</SPAN></FONT></FONT></DIV>
<BLOCKQUOTE dir=ltr 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid; MARGIN-RIGHT: 0px">
  <DIV><FONT face=Arial size=2>also i cannot get this program to work maby you 
  can tell me whats wrong?</FONT></DIV>
  <DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
  <DIV><FONT face=Arial size=2>&gt;&gt;&gt;input("what is your name?") if ted 
  print"hello ted" else: print"who are you?"</FONT></DIV>
  <DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV></BLOCKQUOTE>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face=Arial size=2>Split it 
onto several lines:</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face=Arial 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face="Courier New" 
size=2>&gt;&gt;&gt; name = raw_input("Whats your name? ")&nbsp;&nbsp; #use 
raw_input for characters</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face="Courier New" 
size=2>Whats your name? ted</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face="Courier New" 
size=2>&gt;&gt;&gt; if name == "ted":&nbsp;&nbsp; # must have a colon ':' after 
the test</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face="Courier New" 
size=2>...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print "Hello 
ted"</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face="Courier New" size=2>... 
else: print "Who are you?"</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face="Courier New" 
size=2>...</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face="Courier New" 
size=2>Hello ted</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face="Courier New" 
size=2>&gt;&gt;&gt;</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face=Arial 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face=Arial size=2>You are very 
close but there's a few concepts missing. Try one of the tutors and 
</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face=Arial size=2>don't rush 
it, there's a lot of things to pick up at the beginning, if you miss them 
</FONT></SPAN></DIV>
<DIV dir=ltr><SPAN class=230464116-26122001><FONT face=Arial size=2>early on it 
will just make life harder later on as you have to unlearn bad 
habits.</FONT></SPAN></DIV>
<DIV dir=ltr><FONT face=Arial size=2>
<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></FONT></DIV></BODY></HTML>

------_=_NextPart_001_01C18E2C.60F13410--


From alan.gauld@bt.com  Wed Dec 26 16:53:26 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 26 Dec 2001 16:53:26 -0000
Subject: [Tutor] list as a first class citizen in python?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C206@mbtlipnt02.btlabs.bt.co.uk>

>     So much for lists being first class citizens!  Compare
>     this with Perl's
> ....
>     Or even with references:
> 	$y = [ @$x ];

Looks a lot like y = x[:] to me ;-)

> what's wrong with working with a reference.

Nothing.

> can someone explain the argument here?

When all you've got is Perl every problem looks like a shell 
;-)

Dont worry about it language myopia is not new and
neither is it very productive!

Use what works for you.

Alan G.



From alan.gauld@bt.com  Wed Dec 26 17:02:42 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 26 Dec 2001 17:02:42 -0000
Subject: [Tutor] Re: file filter
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C207@mbtlipnt02.btlabs.bt.co.uk>

> i can get the copy part. It is just the filter part i am 
> confused about. You see, if the line begins with 'c' or ';' i 
> want to ignore the whole line.

> def boksa(infilename, outfilename):
>     ...
> 	for aLine in infile.xreadlines() :
        if aLine[0] not in ';c'  #sequence of tested chars
> 		f.write( aLine )
> 	infile.close()
> 	f.close()

Should do it.

You could do more sophisticated things by using the 
string.find() function or the re module. But the principle 
is the same, just test the line before writing it.

Alan G.


From arcege@speakeasy.net  Wed Dec 26 17:16:40 2001
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Wed, 26 Dec 2001 12:16:40 -0500
Subject: [Tutor] list as a first class citizen in python?
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDAEEFCMAA.karthikg@aztec.soft.net>; from karthikg@aztec.soft.net on Wed, Dec 26, 2001 at 12:14:17PM +0530
References: <20011224201809Z234648-13237+2@bureau8.utcc.utoronto.ca> <NEBBJNMDEKBIBCMCNMBDAEEFCMAA.karthikg@aztec.soft.net>
Message-ID: <20011226121640.C2524@speakeasy.net>

On Wed, Dec 26, 2001 at 12:14:17PM +0530, Karthik Gurumurthy wrote:
> I found this quote on the web..regarding python...
> 
> >>>>>>>
>     Because everything is a reference, and there's no way to dereference
>     that reference, it turns out that there is no trivial way to copy
>     a list!  This fails:
> 	x = [1,2]
> 	y = x
>     Because you don't get a new list there, just a copy to an
>     old one.  Suggested work-arounds include
> 	y = x[0:]
> 	y = x[:]
> 	y = x + []
> 	y = x * 1
>     This forces people to think about references, again.
>     So much for lists being first class citizens!  Compare
>     this with Perl's
> 	@x = (1,2);
> 	@y = @x;
>     Or even with references:
> 	$x = [1,2];
> 	$y = [ @$x ];
>     or
> 	@y = @$x;
> >>>>>>>>
> 
> what's wrong with working with a reference.
> can someone explain the argument here?
> java does a similar thing. In java i would do a clone() to get a copy of an
> arraylist and in python i will
> 
> import copy
> copy.deepcopy(l)
> 
> if something is a first class citizen , should it support "copying" using
> simple assignments ? / how are first class citizens expected to behave ? :-)

Don't think of them as references, think of them as just names.  The key
here is that Python does not have variables, it has name bindings.

Perl has the advantage and the drawback that everything there is
a variable, or more exactly, a memory allocation.  In fact, the
documentation in Perl calls things "lists", which can be cast to either
a hash or an array.  As an object, there is no hash and no array, there
is only memory allocation (variables).  The references are in Perl so
you can pass around references to those variables, and to pass them back
from subroutines.

However with Python, an object is an object.. just with multiple names.
And the object is passed around and manipulated.

The article quoted is wrong in that it applies that you _must_ be able
to deference objects in Python to do things.  Python hides that you even
have a reference to an object, in the classical sense of the term.  Perl,
as you see above, has the problem that you cannot have two names to the
same object.  That you must create a reference to access the same object.

  Python:
    x = [1, 2]
    y = x  # same object
    x[0], y[0]
  Perl:
    @x = (1, 2);
    $y = \@x;  # same memory allocation
    $x[0], $$y[0];

The $y is not an array but a scalar, so now you must do something
different to access it.

My thought is that if you have a first class object, it should be that
you need to do something to copy it (either with the x[:] or x.copy()
or something similar).

After all, the U.S. Congress doesn't want cloning easily. ;)

  -Arcege



From deliberatus@my995internet.com  Wed Dec 26 17:18:09 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 26 Dec 2001 12:18:09 -0500
Subject: [Tutor] subject screw
Message-ID: <3C2A0651.77C76577@my995internet.com>

ok, found a bug!

When a letter has no header field, rfc822 barks like a dog and aborts.

Discovered this when testing TLpost. SOME letters came through, some did
not. The bombes, had no subject field. SO I sent a letter to an alias to
save the incoming letter as a file, and ran the script locally,
redirecting input from the file. This way I could watch error messages
on the console screen. Very informative, I got back:
------------------------------------------------------------------------
ns# ./TLpost.py testlist3 < testfile
Traceback (innermost last):
  File "./TLpost.py", line 159, in ?
    subject= string.strip(Message['Subject'])
  File "/usr/local/lib/python1.5/rfc822.py", line 356, in __getitem__
    return self.dict[string.lower(name)]
KeyError: subject
------------------------------------------------------------------------
Apparently when there is NO subject, no kidding we really mean it, it
omits this header. When rfc822 receives such a leter, it screws the
pooch and crashes, albeit politely.

Reworking rfc822 to handle a non fatal error such as this is WAY beyond
my expertise. Please forward this to the appropriate kahuna.

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From printers@sendme.cz  Wed Dec 26 17:40:58 2001
From: printers@sendme.cz (A)
Date: Wed, 26 Dec 2001 18:40:58 +0100
Subject: [Tutor] How to solve a problem?
Message-ID: <3C2A19BA.17732.1AE6EE@localhost>

Hi,
My program downloads  regularly some files and it takes some 
time so I need to shorten this downloading time. As most of these 
files are the same, many times when the program downloads these 
files, I  would like to  download only those that are not the same or 
are newer. What is the best solution?
Many thanks for help.
Ladislav



From jeff@ccvcorp.com  Wed Dec 26 18:05:38 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed, 26 Dec 2001 10:05:38 -0800
Subject: [Tutor] Re: file filter
References: <E16JE99-0005s7-00@mail.python.org>
Message-ID: <3C2A1171.93EBBF27@ccvcorp.com>

> "kevin parks" <kp87@lycos.com> asked:

> Happy Holidays. I am trying to write a some python code that will copy a file to a new file but with certain lines filtered out. Let's say that i want the new file to have all lines except those that start with a semicolon or a letter c.  ....

> i can get the copy part. It is just the filter part i am confused about. You see, if the line begins with 'c' or ';' i want to ignore the whole line.
>
> cheers,
>
> kevin
>
> def boksa(infilename, outfilename):
>         """this will copy a file exactly, args are: 'infile' and 'outfile'"""
>         infile = open(infilename, 'r')
>         f = open(outfilename, 'w')
>         for aLine in infile.xreadlines() :
>                 f.write( aLine )
>         infile.close()
>         f.close()
>
> if __name__ == '__main__':
>         boksa()

Karthik Gurumurthy already gave you one option, by mentioning the startswith() string method.  You can also use string slicing and 'if something in somelist' to good effect here.

def boksa(infilename, outfilename, filterchars):
    """Reads file infilename, copying each line to file outfilename,
       except for lines that start with characters in the list filterchars."""
    infile = open(infilename, 'r')
    outfile = open(outfilename, 'w')
    for line in infile.xreadlines():
        startchar = line[0]    # assign the first char in line to startchar
        if startchar not in filterchars:
            outfile.write(line)
    infile.close()
    outfile.close()

if __name__ == '__main__':
    myfile = 'test.txt'
    newfile = 'filtered-' + myfile
    boksa( myfile, newfile, [ 'c', ';' ] )

This will let you filter out lines that start with just about any character, and it's really easy to add more filter-characters -- just specify them in the list that you pass to the function.  (Note also that in your original example, when you called boksa() you forgot to pass it any
filenames--I've corrected that in this example.)

Hope that helps...

Jeff Shannon
Technician/Programmer
Credit International




From Benjamin.Schollnick@usa.xerox.com  Wed Dec 26 18:16:42 2001
From: Benjamin.Schollnick@usa.xerox.com (Schollnick, Benjamin)
Date: Wed, 26 Dec 2001 13:16:42 -0500
Subject: [Tutor] RE: How to solve a problem?
Message-ID: <E2D1934575D1D411973D00508BB02F17302523@usa0129ms1.ess.mc.xerox.com>

There's several problems embeded here:

1) How do you tell that the files are the same?
	a) Filename?  - What if you changed the contents but not the name?
	b) Filesize?  - Which one is newer?
	c) Date/Time Stamp - Some transfer methods do not update the 
		date/time stamp.

2) How do you plan on transfering the files?  
	a) Http?
	b) FTP?
	c) Snailmail?
	d) SMB Mount?
	e) NFS Mount?

3) Are these out of a single directory?  Or a directory tree?

To point you part of the way, check the python demos for 
FTPMIRROR.

If you are going to be doing this via FTP then FTP mirror does take
date/time stamp into account.  (That's assuming I'm remembering correctly.)

		- Benjamin

-----Original Message-----
From: A [mailto:printers@sendme.cz]
Sent: Wednesday, December 26, 2001 12:41 PM
To: python-list@python.org; tutor@python.org;
activepython@listserv.ActiveState.com
Subject: How to solve a problem?


Hi,
My program downloads  regularly some files and it takes some 
time so I need to shorten this downloading time. As most of these 
files are the same, many times when the program downloads these 
files, I  would like to  download only those that are not the same or 
are newer. What is the best solution?
Many thanks for help.
Ladislav

_______________________________________________
ActivePython mailing list
ActivePython@listserv.ActiveState.com
http://listserv.ActiveState.com/mailman/listinfo/activepython


From dyoo@hkn.eecs.berkeley.edu  Wed Dec 26 18:57:28 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 26 Dec 2001 10:57:28 -0800 (PST)
Subject: [Tutor] pyhton (fwd)
Message-ID: <Pine.LNX.4.21.0112261055060.28195-100000@hkn.eecs.berkeley.edu>

Hi Ted,

Let me forward this to the rest of Tutor.  Talk to you later!


---------- Forwarded message ----------
Date: Wed, 26 Dec 2001 13:00:48 -0600
From: Ted R. <civic525@hotmail.com>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Cc: civic525@hotmail.com
Subject: Re: [Tutor] pyhton

hello do ou know were i can find a chart or page telling what the different
commands on pyhton do? or better yet do you know wich command "enters" or
goes to the next line on python?


                               thank you
                                              TeD



From dyoo@hkn.eecs.berkeley.edu  Wed Dec 26 19:06:52 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 26 Dec 2001 11:06:52 -0800 (PST)
Subject: [Tutor] subject screw  [exception handling]
In-Reply-To: <3C2A0651.77C76577@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112261052170.28195-100000@hkn.eecs.berkeley.edu>

On Wed, 26 Dec 2001, Kirk Bailey wrote:

> Discovered this when testing TLpost. SOME letters came through, some
> did not. The bombes, had no subject field. SO I sent a letter to an
> alias to save the incoming letter as a file, and ran the script
> locally, redirecting input from the file. This way I could watch error
> messages on the console screen. Very informative, I got back:
>
> ns# ./TLpost.py testlist3 < testfile
> Traceback (innermost last):
>   File "./TLpost.py", line 159, in ?
>     subject= string.strip(Message['Subject'])
>   File "/usr/local/lib/python1.5/rfc822.py", line 356, in __getitem__
>     return self.dict[string.lower(name)]
> KeyError: subject
> ------------------------------------------------------------------------
>
> Apparently when there is NO subject, no kidding we really mean it, it
> omits this header. When rfc822 receives such a leter, it screws the
> pooch and crashes, albeit politely.

Right; the designers of rfc822 felt that missing a header like this
should be a serious error, so that's why we're seeing the KeyError.

To recover gracefully from this, we can use "exception handling".  On your
line:

    subject = string.strip(Message['Subject'])

we can place an "exception handler" to take care of wacky situations (such
as missing Subject lines):


###
    try:
        subject = string.strip(Message['Subject'])
    except KeyError:
        subject = ''
###

which says something like: "Try to assign 'subject' that message headers.  
On the exceptional circumstance of a KeyError, assign 'subject' to the
empty string instead."


It might be good to write a function that automates this exception
handling for us when we grab at headers:


###
def getHeader(msg, header_name):
    try:
        header = string.strip(msg[header_name])
    except KeyError:
        header = ''
    return header
###

This getHeader() function then guarantees that we'll at least get an empty
string out of the situation.


The Python tutorial gives some good information on the idea of exceptions:

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


Good luck to you!



From deliberatus@my995internet.com  Wed Dec 26 19:22:29 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 26 Dec 2001 14:22:29 -0500
Subject: [Tutor] subject screw  [exception handling]
References: <Pine.LNX.4.21.0112261052170.28195-100000@hkn.eecs.berkeley.edu>
Message-ID: <3C2A2375.100DFA37@my995internet.com>

Thank you Danny, the script now reads:

#
# Let's extract the subject for later use!
#
try:
	subject= string.strip(Message['Subject'])
except Keyerror:
	subject="(none provided by sender)"
#
# The information is in the dictionary 'Message', each item keyed with
the
# header's name. The BODY of that dictionary is in the string 'msg'. So
are
# any attachments.

This ought to handle it, and when I come back with wife from registering
her car I will install it and test it. I will let the list know how it
works.


Danny Yoo wrote:
> 
> On Wed, 26 Dec 2001, Kirk Bailey wrote:
> 
> > Discovered this when testing TLpost. SOME letters came through, some
> > did not. The bombes, had no subject field. SO I sent a letter to an
> > alias to save the incoming letter as a file, and ran the script
> > locally, redirecting input from the file. This way I could watch error
> > messages on the console screen. Very informative, I got back:
> >
> > ns# ./TLpost.py testlist3 < testfile
> > Traceback (innermost last):
> >   File "./TLpost.py", line 159, in ?
> >     subject= string.strip(Message['Subject'])
> >   File "/usr/local/lib/python1.5/rfc822.py", line 356, in __getitem__
> >     return self.dict[string.lower(name)]
> > KeyError: subject
> > ------------------------------------------------------------------------
> >
> > Apparently when there is NO subject, no kidding we really mean it, it
> > omits this header. When rfc822 receives such a leter, it screws the
> > pooch and crashes, albeit politely.
> 
> Right; the designers of rfc822 felt that missing a header like this
> should be a serious error, so that's why we're seeing the KeyError.
> 
> To recover gracefully from this, we can use "exception handling".  On your
> line:
> 
>     subject = string.strip(Message['Subject'])
> 
> we can place an "exception handler" to take care of wacky situations (such
> as missing Subject lines):
> 
> ###
>     try:
>         subject = string.strip(Message['Subject'])
>     except KeyError:
>         subject = ''
> ###
> 
> which says something like: "Try to assign 'subject' that message headers.
> On the exceptional circumstance of a KeyError, assign 'subject' to the
> empty string instead."
> 
> It might be good to write a function that automates this exception
> handling for us when we grab at headers:
> 
> ###
> def getHeader(msg, header_name):
>     try:
>         header = string.strip(msg[header_name])
>     except KeyError:
>         header = ''
>     return header
> ###
> 
> This getHeader() function then guarantees that we'll at least get an empty
> string out of the situation.
> 
> The Python tutorial gives some good information on the idea of exceptions:
> 
>     http://python.org/doc/current/tut/node10.html
> 
> Good luck to you!

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From dean@mndsolutions.de  Wed Dec 26 21:49:47 2001
From: dean@mndsolutions.de (dean)
Date: 26 Dec 2001 22:49:47 +0100
Subject: [Tutor] update a window with tkinter
Message-ID: <1009403387.12132.10.camel@thor.mnd>

hi guys,

right, i just wanted to build a little bandwidth monitor to show the
current data rates coming in and out of my machine and to update itself
every few seconds.

after writing the script in php, i spent an unsuccessful day trying to
compile php-gtk.

then i though it would be quicker to learn python.i was right. i wrote
the script in an hour, but i haven't been able to get the gui working.
here's the problem:

i was using this loop (with the external function traffic_rate() which
grabs the data from ifconfig.

try:
	i = 1
	while 1:		
		root.mainloop(3000)
		if i == 1:
			print string.rjust('In (Kb/s)' , 10), string.rjust('Out (Kb/s)', 10)
		rates = traffic_rate(3)
		inrate = rates[0]
		outrate = rates[1]
		inrate = float(inrate / 1024)
		outrate = float(outrate / 1024)
		inrate = fpformat.fix(inrate , 2)
		outrate = fpformat.fix(outrate , 2)
		print string.center(inrate , 10), string.center(outrate, 10)
		output = 'In: '+inrate+'Kb/s  Out: '+outrate+'Kb/s'
		status.set("%s", output)
		i = i + 1
		if i == 10:
			i = 1
		
except KeyboardInterrupt:
	quitme()

i used the following code to build the gui (i lifted the class StatusBar
straight from the tkinter tutorial at www.pythonware.com):

root =Tk()
frame = Frame(root)
frame.bind("<Button-1>", quitme)
frame.pack()
status = StatusBar(root)
status.bind("<Button-1>", quitme)
status.pack(side=BOTTOM, fill=X)
text  = "Dean's bandwidth monitor"
status.set("%s", text)

now, as you probably saw, i used root.mainloop(3000) in my loop to get
it to update every 3 seconds, but none of the bindings work anymore. i
can't even close the window - i have to kill the app or ctrl-c the
console. however, if i use root.mainloop() anywhere, the bindings work
and i can close the app, but my loop doesn't run and the window never
updates.

how might i solve this problem?

dean

p.s. unbelievable that it took me a full 2 days to program myself to an
impasse. what a cool language.






From wilson@visi.com  Wed Dec 26 21:56:21 2001
From: wilson@visi.com (Timothy Wilson)
Date: Wed, 26 Dec 2001 15:56:21 -0600 (CST)
Subject: [Tutor] Law of Demeter example request
Message-ID: <Pine.GSO.4.21.0112261552550.21637-100000@isis.visi.com>

Hi everyone,

I'm looking over the early version of Bruce Eckel's _Thinking in Python_
and I've got a question about the Law of Demeter, or as Bruce puts it,
"Don't talk to strangers."

I *think* I get it, but it would be great if someone would post a brief
example illustrating the concept. Preferably, the example should show
the same short program in two versions, one obeying the law and 2nd
ignoring it.

-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 deliberatus@my995internet.com  Wed Dec 26 21:56:23 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 26 Dec 2001 16:56:23 -0500
Subject: [Tutor] membership management
Message-ID: <3C2A4787.8D5AD989@my995internet.com>

ok. All functions go, all tests complete, it is as bulletproof as these
things ever get. I hammered on it hard, it still ticks. TLpost.py is a
going module, and as soon as Sean polishes for a little more speed it
goes to the public.

Now, we need a membership manager. I invite input and discussion. All
you email hounds, JUMP IN!

If I go both web and email, I want them as seperate modules. CHOICES is
our watchword, and I want toe users to be aboe to go web, email, or
both, as they favor. Therefore, I request suggestions, advice, etc on
any/all. If you preferr to email me direct, go for it.




-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From dyoo@hkn.eecs.berkeley.edu  Wed Dec 26 22:37:34 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 26 Dec 2001 14:37:34 -0800 (PST)
Subject: [Tutor] update a window with tkinter
In-Reply-To: <1009403387.12132.10.camel@thor.mnd>
Message-ID: <Pine.LNX.4.21.0112261433510.30936-100000@hkn.eecs.berkeley.edu>

On 26 Dec 2001, dean wrote:

> right, i just wanted to build a little bandwidth monitor to show the
> current data rates coming in and out of my machine and to update itself
> every few seconds.

Very cool.  You might be interested in the after() and after_idle() alarm
handlers:

http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm

This should allow you to set things up to update every so often.



From bwinton@tor.dhs.org  Wed Dec 26 22:52:18 2001
From: bwinton@tor.dhs.org (Blake Winton)
Date: Wed, 26 Dec 2001 17:52:18 -0500
Subject: [Tutor] Law of Demeter example request
In-Reply-To: <Pine.GSO.4.21.0112261552550.21637-100000@isis.visi.com>
References: <Pine.GSO.4.21.0112261552550.21637-100000@isis.visi.com>
Message-ID: <20011226175218.A11507@tor.dhs.org>

* Timothy Wilson <wilson@visi.com> [011226 16:55]:
> I *think* I get it, but it would be great if someone would post a brief
> example illustrating the Law of Demeter. Preferably, the example should
> show the same short program in two versions, one obeying the law and
> 2nd ignoring it.

The example I saw was
car.accelerate()
and
car.engine.fuelIntake.increaseGasToAirMixture()

The problem with the second one being that if I start driving an
electric car, I'm going to have to change all my code, instead of
just changing the accelerate method (possibly in a subclass of car).

I'm not sure if he notes the downside of the Law, which is that you
might find yourself having _way_ more methods on your containing
objects than you'ld like to.  I'm not sure what, if any, workarounds
people use.

Later,
Blake.
-- 
9:40pm up 52 days, 21:07, 2 users, load average: 0.02, 0.09, 0.07


From michael@exasource.com  Wed Dec 26 22:57:02 2001
From: michael@exasource.com (Michael)
Date: Wed, 26 Dec 2001 15:57:02 -0700
Subject: [Tutor] pyhton
In-Reply-To: <OE51Wwr2UAaTzvb5YI900007307@hotmail.com>
References: <OE51Wwr2UAaTzvb5YI900007307@hotmail.com>
Message-ID: <01122615570200.05241@orion.andromeda>

On Mon, 24 Dec 2001, Ted R. wrote:

> > hello my name is ted and i have a few questions about pyhton. i have never
> worked with programing but i have worked with computers for a while. i am
> 15 so i have done more jovinial "cracking" like gameshark codes and
> gameshark hacking etc. after a while i got bored so i dicided to go into
> somthing were i could expand to a future carrier, so i started to look at
> computer programing, and a herd that python was the easieats and all around
> best. but to my question do you know any were it gives more "hands on
> traingin" and more in depth help.
>
> also i cannot get this program to work maby you can tell me whats wrong?
>
> >>>input("what is your name?") if ted print"hello ted" else: print"who are
> >>> you?"
>
> thank you
>                TeD

Try:  name = raw input("what is your name?")
            if name == ted;
                print "Hello ted"
            else:
                print "who are you"

Make sure you use the proper indentation for your if else statements and use 
"raw input" for a string, "input" for an integer.
-- 
Michael Lewis
Exasource Inc.
Phone: 970.206.4556
Email: mlewis@exasource.com

       "Linux - The final solution"



From arcege@speakeasy.net  Wed Dec 26 23:06:53 2001
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Wed, 26 Dec 2001 18:06:53 -0500
Subject: [Tutor] update a window with tkinter
In-Reply-To: <1009403387.12132.10.camel@thor.mnd>; from dean@mndsolutions.de on Wed, Dec 26, 2001 at 10:49:47PM +0100
References: <1009403387.12132.10.camel@thor.mnd>
Message-ID: <20011226180653.E2524@speakeasy.net>

On Wed, Dec 26, 2001 at 10:49:47PM +0100, dean wrote:
> hi guys,
> 
> right, i just wanted to build a little bandwidth monitor to show the
> current data rates coming in and out of my machine and to update itself
> every few seconds.
> 
> after writing the script in php, i spent an unsuccessful day trying to
> compile php-gtk.
> 
> then i though it would be quicker to learn python.i was right. i wrote
> the script in an hour, but i haven't been able to get the gui working.
> here's the problem:
> 
> i was using this loop (with the external function traffic_rate() which
> grabs the data from ifconfig.
> 
> try:
> 	i = 1
> 	while 1:		
> 		root.mainloop(3000)
> 		if i == 1:
> 			print string.rjust('In (Kb/s)' , 10), string.rjust('Out (Kb/s)', 10)
> 		rates = traffic_rate(3)
> 		inrate = rates[0]
> 		outrate = rates[1]
> 		inrate = float(inrate / 1024)
> 		outrate = float(outrate / 1024)
> 		inrate = fpformat.fix(inrate , 2)
> 		outrate = fpformat.fix(outrate , 2)
> 		print string.center(inrate , 10), string.center(outrate, 10)
> 		output = 'In: '+inrate+'Kb/s  Out: '+outrate+'Kb/s'
> 		status.set("%s", output)
> 		i = i + 1
> 		if i == 10:
> 			i = 1
> 		
> except KeyboardInterrupt:
> 	quitme()
> 
> i used the following code to build the gui (i lifted the class StatusBar
> straight from the tkinter tutorial at www.pythonware.com):
> 
> root =Tk()
> frame = Frame(root)
> frame.bind("<Button-1>", quitme)
> frame.pack()
> status = StatusBar(root)
> status.bind("<Button-1>", quitme)
> status.pack(side=BOTTOM, fill=X)
> text  = "Dean's bandwidth monitor"
> status.set("%s", text)
> 
> now, as you probably saw, i used root.mainloop(3000) in my loop to get
> it to update every 3 seconds, but none of the bindings work anymore. i
> can't even close the window - i have to kill the app or ctrl-c the
> console. however, if i use root.mainloop() anywhere, the bindings work
> and i can close the app, but my loop doesn't run and the window never
> updates.

Depending on what system you are using, a lot of events could be handled
in 3000 milliseconds, maybe too many for you to be seeing.  But that
seems doubtful.

It may be better to put this into a function and use the after method,
which tells Tkinter to run a function every so often.  I'm not sure
what you have for the widget of the StatusBar, i.e. if the "set" method
works correctly.  But try this:

def update_status(status_widget):
    rates = traffic_rate(3)
    inrate = rates[0]
    outrate = rates[1]
    inrate = float(inrate / 1024)
    outrate = float(outrate / 1024)
    inrate = fpformat.fix(inrate , 2)
    outrate = fpformat.fix(outrate , 2)
    print string.center(inrate , 10), string.center(outrate, 10)
    output = 'In: '+inrate+'Kb/s  Out: '+outrate+'Kb/s'
    status_widget.set("%s", output)

root.after(3000, update_status, (status,))
root.mainloop()

It may be possible that traffic_rate takes too long to run.  If that
is the case, then both bits of code won't get back to Tkinter to update
events, including to responding to bindings.

  -Arcege



From deliberatus@my995internet.com  Thu Dec 27 00:37:14 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 26 Dec 2001 19:37:14 -0500
Subject: [Tutor] ok, I want to read a dir.
Message-ID: <3C2A6D3A.CF9BE816@my995internet.com>

I want to read a dir. I spedify a path and a name pattern, such as
'*.info', and read all examples of that pattern into a list.

So, if in /www/cgi-bin/lists there is:

a.info
b.info
c.info

along with many other files, ONLY a.info, b.info, c.info get reported
back to me.

How I do dat?


-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From dyoo@hkn.eecs.berkeley.edu  Thu Dec 27 01:24:26 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 26 Dec 2001 17:24:26 -0800 (PST)
Subject: [Tutor] ok, I want to read a dir.
In-Reply-To: <3C2A6D3A.CF9BE816@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112261723150.32593-100000@hkn.eecs.berkeley.edu>

On Wed, 26 Dec 2001, Kirk Bailey wrote:

> I want to read a dir. I spedify a path and a name pattern, such as
> '*.info', and read all examples of that pattern into a list.

Ah!  Take a look at the glob module:

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

Hope this helps!



From deliberatus@my995internet.com  Thu Dec 27 02:13:56 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 26 Dec 2001 21:13:56 -0500
Subject: [Tutor] ok, I want to read a dir.
References: <Pine.LNX.4.21.0112261723150.32593-100000@hkn.eecs.berkeley.edu>
Message-ID: <3C2A83E4.2C5F1D4E@my995internet.com>

ok, it worked. Too well, it worked.

It returned the file names, and included in the return is the path!

Lookee:
ns# ./TLwebmgr.py
<HTML><HEAD>
 <STYLE TYPE="text/css">
 <!--  A { text-decoration: none; }  A:visited, A:hover, A:active 
text-decoration:none; }
 // --></STYLE>
 <TITLE>TinyList Web Manager</TITLE>
 </HEAD>
 <BODY TEXT="#000000"  BGCOLOR="#FFFFFF"  LINK="#0000FF" ALINK="FF0000"
VLINK="0000FF"><blockq>
 

['./lists/testlist3.info', './lists/tinylist-devlopers.info',
'./lists/evil-humor.info']
Here is the content of 'filelist': ['./lists/testlist3.info',
'./lists/tinylist-devlopers.info 

<P><br>
./lists/testlist3.info - A testing list for devlopment of TinyList
<P>
./lists/tinylist-devlopers.info The Devloper's discussion list for
Tinylist- TECHNICAL!
<P>
./lists/evil-humor.info EVIL HUMOR- sick, cynical, jaded, peverse,
howlingly funny! ADULTS ONL!
<P>
<P><br>Please click a name to read the entire description and to
 access the form to subscribe or subscribe.<P><br>
<P><br>
 </BODY>
 </HTML>

ns# 
See, those lines should be the bare name of the thing, a space, then the
firstline of the info file. Well, ir read the info file pretty slick.
Accessed the riretory structure just fine. Seems I want to massage the
elements in the list, or at least in A list, so everything but the first
part of the file is GONE. Strip off the path, then strip off the .info
part, leaving us with pure NAME. That name is the name of a list. That
btw is in my server now, and those are the info files for 3 lists NOW
working with TLpost.py NOW. snurklechortlegloat...

I love this list.


Danny Yoo wrote:
> 
> On Wed, 26 Dec 2001, Kirk Bailey wrote:
> 
> > I want to read a dir. I spedify a path and a name pattern, such as
> > '*.info', and read all examples of that pattern into a list.
> 
> Ah!  Take a look at the glob module:
> 
>     http://www.python.org/doc/lib/module-glob.html
> 
> Hope this helps!
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From chrislubrecht@home.com  Thu Dec 27 02:27:54 2001
From: chrislubrecht@home.com (ccl)
Date: Wed, 26 Dec 2001 21:27:54 -0500
Subject: [Tutor] IP sorting
Message-ID: <5.1.0.14.0.20011226210936.00a74e60@pop3.norton.antivirus>

This may be somewhere, and I am just being lazy, but its something I need 
to fix...

I am currently writing a script to analyze proxy server logs. One section 
of the script scrubs out the IP addresses, counts them and sorts them and 
prints them in a nice ordered way with the IP, then the number of hits. 
(ie. "192.168.1.5 ----- 356 hits")

Basically, what I am doing is creating a dictionary with the IP as the key, 
and the result of string.count() as the entry.

then I do...

dead_bishop = ip_dictionary.keys()
dead_bishop.sort()
for item in dead_bishop:
  print item," ---- ",ip_dictionary[item]," hits"


All is good, it works well, however it only sorts to the second place of 
the last octet. For example...

192.168.100.118 --- 5 hits
192.168.100.119 --- 10 hits
192.168.100.12 --- 3 hits
192.168.100.120 --- 22 hits

How do I get the 192.168.100.12 to go where it supposed to (at the beginning)?




From arcege@speakeasy.net  Thu Dec 27 02:37:15 2001
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Wed, 26 Dec 2001 21:37:15 -0500
Subject: [Tutor] ok, I want to read a dir.
In-Reply-To: <3C2A83E4.2C5F1D4E@my995internet.com>; from deliberatus@my995internet.com on Wed, Dec 26, 2001 at 09:13:56PM -0500
References: <Pine.LNX.4.21.0112261723150.32593-100000@hkn.eecs.berkeley.edu> <3C2A83E4.2C5F1D4E@my995internet.com>
Message-ID: <20011226213715.F2524@speakeasy.net>

On Wed, Dec 26, 2001 at 09:13:56PM -0500, Kirk Bailey wrote:
> ok, it worked. Too well, it worked.
> 
> It returned the file names, and included in the return is the path!
> 
> Lookee:
[lookee snipped]

> See, those lines should be the bare name of the thing, a space, then the
> firstline of the info file. Well, ir read the info file pretty slick.
> Accessed the riretory structure just fine. Seems I want to massage the
> elements in the list, or at least in A list, so everything but the first
> part of the file is GONE. Strip off the path, then strip off the .info
> part, leaving us with pure NAME. That name is the name of a list. That
> btw is in my server now, and those are the info files for 3 lists NOW
> working with TLpost.py NOW. snurklechortlegloat...

Then you might want to look at what the glob module is doing.  It uses
os.listdir and the fnmatch module.

def nopath_glob(dir, pattern):
  import os, fnmatch

  files = os.listdir(dir)
  results = []
  for fname in files:
    if fnmatch.fnmatch(fname, pattern):
      results.append(fname)
  return results

About the only real difference is that the glob function joins the
directory and file names together first.

This is just the pedantic version.. the same thing is done with
glob.glob1.

  -Arcege



From deliberatus@my995internet.com  Thu Dec 27 03:58:33 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 26 Dec 2001 22:58:33 -0500
Subject: [Tutor] ok, I want to read a dir.
References: <Pine.LNX.4.21.0112261723150.32593-100000@hkn.eecs.berkeley.edu> <3C2A83E4.2C5F1D4E@my995internet.com> <20011226213715.F2524@speakeasy.net>
Message-ID: <3C2A9C69.3D974E25@my995internet.com>

Say, looking this over, FILTER looks like a good candidate for this job.


files=os.listdir('./lists/')            # this creates a raw dir listing
filelist=[]                             # create an empty list
fnmatch.filter(filelist, "*.info")      # return the subset of list
which match!

this is not right, but close. What is the right way to use fnmatch and
filter?
This is the error I get:

ns# ./TLpost.py
Traceback (innermost last):
  File "./TLpost.py", line 189, in ?
    listname = sys.argv[1]
IndexError: list index out of range
ns# 

And that puzzles hell out of me.

"Michael P. Reilly" wrote:
> 
> On Wed, Dec 26, 2001 at 09:13:56PM -0500, Kirk Bailey wrote:
> > ok, it worked. Too well, it worked.
> >
> > It returned the file names, and included in the return is the path!
> >
> > Lookee:
> [lookee snipped]
> 
> > See, those lines should be the bare name of the thing, a space, then the
> > firstline of the info file. Well, ir read the info file pretty slick.
> > Accessed the riretory structure just fine. Seems I want to massage the
> > elements in the list, or at least in A list, so everything but the first
> > part of the file is GONE. Strip off the path, then strip off the .info
> > part, leaving us with pure NAME. That name is the name of a list. That
> > btw is in my server now, and those are the info files for 3 lists NOW
> > working with TLpost.py NOW. snurklechortlegloat...
> 
> Then you might want to look at what the glob module is doing.  It uses
> os.listdir and the fnmatch module.
> 
> def nopath_glob(dir, pattern):
>   import os, fnmatch
> 
>   files = os.listdir(dir)
>   results = []
>   for fname in files:
>     if fnmatch.fnmatch(fname, pattern):
>       results.append(fname)
>   return results
> 
> About the only real difference is that the glob function joins the
> directory and file names together first.
> 
> This is just the pedantic version.. the same thing is done with
> glob.glob1.
> 
>   -Arcege
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Thu Dec 27 04:15:06 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Wed, 26 Dec 2001 23:15:06 -0500
Subject: [Tutor] webmgr part 1 thus far
Message-ID: <3C2AA04A.F19DFD31@my995internet.com>

ok, take a look and tell me where I am wrong:
-----------------------------------------------------------------------
ns# list TLwebmgr.py
Listing of file TLwebmgr.py in
directory:/www/www.howlermonkey.net/cgi-bin

#!/usr/local/bin/python
#
# You must define the next lien for the WEB path to your server's web
directory!
# ALL web scripts must live in the cgi-bin UNDER this dir!
# THAT IS WHERE TL LIVES! /lists lives UNDER that dir in the tree!
#
webpath="http://www.howlermonkey.net"
import string, sys, os, fnmatch, cgi
#
forminput=sys.stdin
f1=open('html.header','r')
header=string.join(f1.readlines())
f1.close()
f1=open('html.footer','r')
footer=string.join(f1.readlines())
f1.close()
filelist=[]
print "<html><head>Content-Type: text/html"     # HTML is following
print header

#
CRLF="\r\n"
#
def descriptor(filename):               # Read 1st line in file named.
        f1=open('./lists/'+filename,'r')        #open the file named,
        info=string.strip(f1.readline())        # read the first line in
the file
        f1.close()                              # close the file
        return info                             # and exit returning the
1 line read
#
files=os.listdir('./lists/')            # this creates a raw dir listing
filelist=[]                             # create an empty list
fnmatch.filter(filelist, "*.info")      # return the subset of list
which match!

print filelist                  # testcode, remove later

index=0                                 # we will now strip any
whitespaces

for x in filelist:                      # filelist lists all the
available info files
        print "<a href="+\"+webpath+"/cgi-bin/commander.py?list=" + x +
\" + ">" + x + "</a> ",
 descriptor(x)+"<P>"

print "<P><br>Please click a name to read the entire description and to"
print " access the form to subscribe or subscribe.<P><br>"
print footer

ns# 
-----------------------------------------------------------------------
-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From karthikg@aztec.soft.net  Thu Dec 27 04:34:26 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Thu, 27 Dec 2001 10:04:26 +0530
Subject: [Tutor] IP sorting
In-Reply-To: <5.1.0.14.0.20011226210936.00a74e60@pop3.norton.antivirus>
Message-ID: <NEBBJNMDEKBIBCMCNMBDEEFACMAA.karthikg@aztec.soft.net>

sort is doing a string comparison of the ip addresses you have
which are infact strings in your list.

so '192.168.100.12' > '192.168.100.110'

because '12' > '110'

you have an option to specify a function object along with sort which would
do the comparison according to your needs
Something along the following lines should work.


def func(a,b):

	l1 = map(int,a.split('.'))
	l2 = map(int,b.split('.'))

	for i in range(len(l1)):
		first = l1[i]
		sec = l2[i]

		if first == sec:
			continue;
		elif first > sec:
			return 1
		else:
			return -1
	else:
		return 0



dead_bishop = ip_dictionary.keys()
dead_bishop.sort(func)

this should work.

karthik.



-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
ccl
Sent: Thursday, December 27, 2001 7:58 AM
To: tutor@python.org
Subject: [Tutor] IP sorting


This may be somewhere, and I am just being lazy, but its something I need
to fix...

I am currently writing a script to analyze proxy server logs. One section
of the script scrubs out the IP addresses, counts them and sorts them and
prints them in a nice ordered way with the IP, then the number of hits.
(ie. "192.168.1.5 ----- 356 hits")

Basically, what I am doing is creating a dictionary with the IP as the key,
and the result of string.count() as the entry.

then I do...

dead_bishop = ip_dictionary.keys()
dead_bishop.sort()
for item in dead_bishop:
  print item," ---- ",ip_dictionary[item]," hits"


All is good, it works well, however it only sorts to the second place of
the last octet. For example...

192.168.100.118 --- 5 hits
192.168.100.119 --- 10 hits
192.168.100.12 --- 3 hits
192.168.100.120 --- 22 hits

How do I get the 192.168.100.12 to go where it supposed to (at the
beginning)?



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


From grimmtoothtoo@yahoo.com  Thu Dec 27 04:23:58 2001
From: grimmtoothtoo@yahoo.com (Grimmtooth)
Date: Wed, 26 Dec 2001 23:23:58 -0500
Subject: [Tutor] IP sorting
In-Reply-To: <5.1.0.14.0.20011226210936.00a74e60@pop3.norton.antivirus>
Message-ID: <NLEIJCOLEACIANLABPOEOECNCDAA.grimmtoothtoo@yahoo.com>

> All is good, it works well, however it only sorts to the second place of
> the last octet. For example...
>
> 192.168.100.118 --- 5 hits
> 192.168.100.119 --- 10 hits
> 192.168.100.12 --- 3 hits
> 192.168.100.120 --- 22 hits
>
> How do I get the 192.168.100.12 to go where it supposed to (at
> the beginning)?

Actually, it *is* sorting to the fourth octet. Look at what you have:

  118
  119
  12
  120

If you asked Python to compare '12' and '120' it would tell you that the
former is 'less' than the latter.  In order to get a true numerical sort,
you need to convert the octets (all of them, not just the fourth) to actual
numbers when sorting.  Or, more kludgey, convert two-digit octets to three
with a leading zero.


_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com



From shalehperry@attbi.com  Thu Dec 27 04:33:55 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 26 Dec 2001 20:33:55 -0800 (PST)
Subject: [Tutor] Law of Demeter example request
In-Reply-To: <Pine.GSO.4.21.0112261552550.21637-100000@isis.visi.com>
Message-ID: <XFMail.20011226203355.shalehperry@attbi.com>

On 26-Dec-2001 Timothy Wilson wrote:
> Hi everyone,
> 
> I'm looking over the early version of Bruce Eckel's _Thinking in Python_
> and I've got a question about the Law of Demeter, or as Bruce puts it,
> "Don't talk to strangers."
> 
> I *think* I get it, but it would be great if someone would post a brief
> example illustrating the concept. Preferably, the example should show
> the same short program in two versions, one obeying the law and 2nd
> ignoring it.
> 

class MoneyJar:
    def __init__(self, value):
        self.__value = value

    def addMoney(self, value):
        self.__value = self.__value + value

    def subtractMoney(self, value):
        self.__value = self.__value - value

    def getTotal(self):
        return self.__value

This class has one variable: __value.  It is accessed by 3 methods.

class MoneyJar:
    def __init__(self, value):
        self.value = value

This too has one variable.  However the only way to access it is directly.

jar = MoneyJar(10) # start with 10 units
jar.value = 5      # steal 5 units

Without a method in the middle the client can do anything to your class.

jar.value = "5 dollars"

amount = jar.value
subtotal = amount - (amount * tax)

What happens when jar.value is not a number?  Using methods lets you define how
each item is accessed.

That was the safety aspect.  However the total gains are less obvious.  What if
you need to keep a running register of each transaction.

def addMoney(self, value):
    self.register.addTransaction(addition, value)
    self.__value = self.__value + value

def subtractMoney(self, value):
    self.register.addTransaction(deletion, value)
    self.__value = self.__value - value

easily done.  Without the methods it is up to the client to remember to call
the register functions each time.  Then you add a database, then there are two
other programs trying to read the jar at the same time, ..... as you can see a
little design up front saves you in the end.  Safety is the obvious gain from
not talking to strangers, but there are many others.


From rnd@onego.ru  Thu Dec 27 06:15:57 2001
From: rnd@onego.ru (Roman Suzi)
Date: Thu, 27 Dec 2001 09:15:57 +0300 (MSK)
Subject: [Tutor] IP sorting
In-Reply-To: <NLEIJCOLEACIANLABPOEOECNCDAA.grimmtoothtoo@yahoo.com>
Message-ID: <Pine.LNX.4.21.BCL.0112270908480.3051-100000@suzi.com.onego.ru>

Nice problem! Here is my solution (for Python 2.x)

iplist = [
          "195.168.1.123",
          "192.168.1.123",
          "192.168.1.111",
          "192.168.1.11",
          ]

lot = [tuple(map(int, ip.split("."))) for ip in iplist]
lot.sort()
iplist1 = [".".join(map(str, addr)) for addr in lot]

print iplist1

Sincerely yours, Roman A.Suzi
-- 
 - Petrozavodsk - Karelia - Russia - mailto:rnd@onego.ru -
 




From dyoo@hkn.eecs.berkeley.edu  Thu Dec 27 06:20:07 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 26 Dec 2001 22:20:07 -0800 (PST)
Subject: [Tutor] IP sorting
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDEEFACMAA.karthikg@aztec.soft.net>
Message-ID: <Pine.LNX.4.21.0112262215360.3235-100000@hkn.eecs.berkeley.edu>

On Thu, 27 Dec 2001, Karthik Gurumurthy wrote:

> you have an option to specify a function object along with sort which
> would do the comparison according to your needs Something along the
> following lines should work.
> 
> def func(a,b):
> 
> 	l1 = map(int,a.split('.'))
> 	l2 = map(int,b.split('.'))
> 
> 	for i in range(len(l1)):
> 		first = l1[i]
> 		sec = l2[i]
> 
> 		if first == sec:
> 			continue;
> 		elif first > sec:
> 			return 1
> 		else:
> 			return -1
> 	else:
> 		return 0


Here's a a simplification of the code:

###
def cmpIPAddresses(a, b):
    l1 = map(int, a.split('.'))
    l2 = map(int, b.split('.'))
    return cmp(l1, l2)
###


This relies on the fact that Python knows how to compare two sequences:


###
>>> cmp([1, 2, 3], [1, 2, 3])
0
>>> cmp([1, 2, 3], [1, 2, 4])
-1
>>> cmp([3, 2, 1], [1, 2, 3])
1
>>> cmp([3, 2, 1], [1, 2, 3])
###

Let Python do the work.  *grin*



From karthikg@aztec.soft.net  Thu Dec 27 06:47:34 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Thu, 27 Dec 2001 12:17:34 +0530
Subject: [Tutor] IP sorting
In-Reply-To: <Pine.LNX.4.21.BCL.0112270908480.3051-100000@suzi.com.onego.ru>
Message-ID: <NEBBJNMDEKBIBCMCNMBDOEFCCMAA.karthikg@aztec.soft.net>

this one is cool and so was danny's.
i have a question here though.

why do we need to convert to a tuple?

lot = [tuple(map(int, ip.split("."))) for ip in iplist]

is there any specific reason. Python does not know to sort a list of lists?

karthik.

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Roman Suzi
Sent: Thursday, December 27, 2001 11:46 AM
To: tutor@python.org
Subject: RE: [Tutor] IP sorting



Nice problem! Here is my solution (for Python 2.x)

iplist = [
          "195.168.1.123",
          "192.168.1.123",
          "192.168.1.111",
          "192.168.1.11",
          ]

lot = [tuple(map(int, ip.split("."))) for ip in iplist]
lot.sort()
iplist1 = [".".join(map(str, addr)) for addr in lot]

print iplist1

Sincerely yours, Roman A.Suzi
-- 
 - Petrozavodsk - Karelia - Russia - mailto:rnd@onego.ru -
 



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


From sentinel805@netscape.net  Thu Dec 27 06:54:11 2001
From: sentinel805@netscape.net (sentinel805)
Date: Thu, 27 Dec 2001 01:54:11 -0500
Subject: [Tutor] more free code and thanks for your help
Message-ID: <3C2AC593.3050508@netscape.net>

Thanks for the help offered to solve my getch( ) problem.  I'm working 
on a all-in-one solution now. wish me luck. In  the mean time ,  here is 
some more free code to any one who can use it.  It shows one way to lay 
out a window.  The window contains 2 Text objects that will resize with 
the window and 3 buttons that will remain centered at the bottom of the 
window.  It has more comment than code, but thats because I did it for 
my own learning/referance.  Coded useing Tkinter.

http://www.geocities.com/swinux/GuiApp.html

Ron



From rnd@onego.ru  Thu Dec 27 07:15:12 2001
From: rnd@onego.ru (Roman Suzi)
Date: Thu, 27 Dec 2001 10:15:12 +0300 (MSK)
Subject: [Tutor] IP sorting
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDOEFCCMAA.karthikg@aztec.soft.net>
Message-ID: <Pine.LNX.4.21.BCL.0112270941390.3051-100000@suzi.com.onego.ru>

On Thu, 27 Dec 2001, Karthik Gurumurthy wrote:

> this one is cool and so was danny's.
> i have a question here though.
> 
> why do we need to convert to a tuple?
> 
> lot = [tuple(map(int, ip.split("."))) for ip in iplist]
> 
> is there any specific reason. Python does not know to sort a list of lists?

Tuple is a constant list. It is slightly faster to deal with tuples. In my
version I am using standard sort() method, which is much faster "as is"
than when it is using ANY cmp function.

"lot" is a list. I am applying .sort() to it to sort it.

IP adresses has sort order different from their string
representation. Another way to sort them is:

----------------------------------------------------
from socket import inet_aton, inet_ntoa

iplist = [
          "195.168.1.123",
          "192.168.1.123",
          "192.168.1.111",
          "192.168.1.11",
          ]

lot = map(inet_aton, iplist)
lot.sort()
iplist1 = map(inet_ntoa, lot)

print iplist1

------------------------------------------------------ 

Of course, it is possible to write cmp function as easy as:

def cmpIPAddresses(a, b):
    return cmp(inet_aton(a), inet_aton(b))


That is, one can use the most compact version of IP-addresses
comparison:

from socket import inet_aton
  iplist.sort(lambda a, b: cmp(inet_aton(a), inet_aton(b)))


Function socket.inet_aton converts symbolical IP-address into 4-byte
string, which can be compared by common rules.

> karthik.

Sincerely yours, Roman A.Suzi
-- 
 - Petrozavodsk - Karelia - Russia - mailto:rnd@onego.ru -
 




From rnd@onego.ru  Thu Dec 27 07:29:40 2001
From: rnd@onego.ru (Roman Suzi)
Date: Thu, 27 Dec 2001 10:29:40 +0300 (MSK)
Subject: [Tutor] IP sorting
In-Reply-To: <Pine.LNX.4.21.BCL.0112270941390.3051-100000@suzi.com.onego.ru>
Message-ID: <Pine.LNX.4.21.BCL.0112271026350.3051-100000@suzi.com.onego.ru>

For those who would like another programming problem:

How to sort domain names AND IP addresses? NB. Domain names better to sort
starting from level 1.

bbb.aa
aaa.bb
ccc.cc
...



Sincerely yours, Roman A.Suzi
-- 
 - Petrozavodsk - Karelia - Russia - mailto:rnd@onego.ru -
 



From dyoo@hkn.eecs.berkeley.edu  Thu Dec 27 09:09:16 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 27 Dec 2001 01:09:16 -0800 (PST)
Subject: [Tutor] Modules/Setup in 2.2 source package
In-Reply-To: <20011226080507.G3310@hal>
Message-ID: <Pine.LNX.4.21.0112270104570.4873-100000@hkn.eecs.berkeley.edu>

On Wed, 26 Dec 2001, Rob McGee wrote:

> I'm a little confused about Modules/Setup in Python 2.2. If I do
> nothing to it, does that mean I get none of those modules? That seems
> like an unusual amount of manual labor for configuring a package. :)

Think of it more like manual override.  The './configure' step on setting
up Python on a Unix system should autodetect everything.  The
Modules/Setup file is for unusual situations where the autodetect isn't
seeing anything.


> I'm upgrading from 2.0.1 which came with Slackware 8. I think I built
> 2.0 from source before that, and I don't recall having to do so much
> to it to make it work. But maybe that was because I didn't do much
> with it.

I remember that on older versions of Python (1.52), I had to uncomment
sections of Modules/Setup when I wanted to get Tkinter working.
Thankfully, Python configuration is a little smarter now, so you probably
don't need to touch Modules/Setup.


Good night!



From dyoo@hkn.eecs.berkeley.edu  Thu Dec 27 09:53:37 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 27 Dec 2001 01:53:37 -0800 (PST)
Subject: [Tutor] Re: file filter    [Python 2.2 iterators]
In-Reply-To: <KCBIPIKHFBFDCAAA@mailcity.com>
Message-ID: <Pine.LNX.4.21.0112270111560.4873-100000@hkn.eecs.berkeley.edu>

On Wed, 26 Dec 2001, kevin parks wrote:

> Happy Holidays.

Hey Kevin, long time no see.  Glad to hear from you again.


> I am trying to write a some python code that will copy a file to a new
> file but with certain lines filtered out. Let's say that i want the
> new file to have all lines except those that start with a semicolon or
> a letter c. So that an input file that has these lines:
> 
> ;i1 0 1 2 3 2
> i1 6 8 7 9 
> ci2 99 0 0 0 2
> i1 2 3 4
> i2 3 4 4 
> ci1 3 4 4 5
> ;i3 929 92 2
> i4 2 8 9 1
> 
> would yield:
> 
> i1 2 3 4
> i2 3 4 4 
> i4 2 8 9 1


Hmmm!  This sounds interesting!  I thought I might brush up on the new
Iterator stuff that's part of Python 2.2.  Here's something that may help
you:


###
class FilterIterator:
    """This wraps a filtering wrapper right on top of an iterator."""

    def __init__(self, filter_func, input_iter):
        """Initializes a filterer of a given input iterator.
        filter_func should be a boolean function that's true on the
        elements that we want to maintain."""
        self.filter_func, self.input_iter = filter_func, input_iter


    def __iter__(self):
        return self


    def next(self):
        while 1:
            next_value = self.input_iter.next()
            if self.filter_func(next_value):
                return next_value
###



In your code before:

> 	for aLine in infile.xreadlines() :

xreadlines() is a function that returns an "iterator" --- some object that
returns lines on-demand whenever we call next().  FilterIterator is meant
to sit right on top of an existing iterator, and act as the gatekeeper.  
If all goes well, it should only let lines that look ok to pass through.

Iterators are explained in gory detail here:

    http://python.sourceforge.net/peps/pep-0234.html

but as a result of its newness, it's very Python 2.2 specific.  (We can
recode the idea to work with older Python versions in another message if
you'd like.)




Let's test to see if it works:

###
>>> lines = ['hello', 'world', 'this', 'is', 'a', 'test']
>>> def isEvenLength(x):
...     return len(x) % 2 == 0
...
>>> myiter = FilterIterator(isEvenLength, iter(lines))
>>> myiter.next()
'this'
>>> myiter.next()
'is'
>>> myiter.next()
'test'
>>> myiter.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/tmp/python-25824Hte", line 17, in next
StopIteration
###


Yes.  *grin*  Wow, that actually worked!



We can train FilterIterator to do something similar to filter out anything
that starts with a 'c' or ';', like this:

###
def isGoodLine(l):
    """A line is "good" if it doesn't begin with 'c' or ';'."""
    return l[0] not in ('c', ';')


def boksa(infilename, outfilename):
    """this will copy a file exactly, args are: 'infile' and 'outfile'"""
    infile = open(infilename, 'r')
    f = open(outfilename, 'w')
    for aLine in FilterIterator(isGoodLine, iter(infile)):
        f.write( aLine )
    infile.close()
    f.close()
###


This allows you to filter out lines in your files with minimal changes to
your code's logic.  I'm still a newbie myself with this iterator stuff, so
FilterIterator could probably be improved.  Still, I hope this helps!



From alan.gauld@bt.com  Thu Dec 27 13:55:06 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 27 Dec 2001 13:55:06 -0000
Subject: [Tutor] Law of Demeter example request
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C20A@mbtlipnt02.btlabs.bt.co.uk>

> and I've got a question about the Law of Demeter, or as Bruce puts it,
> "Don't talk to strangers."

OK, The other way of stating it is that objects 
should 'do it to themselves'...

For example, if we have a diary object that contains 
a list of appointments. Maybe the diary has a method

moveAppointment(self, Appointment, deltaTime)

We could implement it like this:

def moveAppointment(self, Appointment, deltaTime):
    App = self.Appointments.find(Appointment)
    T = App.getTime()
    T = T + deltaTime
    App.setTime(T)

Or we could do:

def moveAppointment(self, Appointment, deltaTime):
    App = self.Appointments.find(Appointment)
    App.changeTime(deltaTime)

Thus the diary knows how to manage appointment objects 
but leaves the Appointments themselves to manage the 
details like their time etc.

Of course we'd be in an even worse state if the diary 
was setting the Appointments internal state variables 
directly! But no one would be daft enough to do that, 
would they? ;-)

It means building more low level methods but the 
end result is much more resilient to change and 
the low level objects more liable to be reusable.

> example illustrating the concept. Preferably, the example should show
> the same short program in two versions, one obeying the law and 2nd
> ignoring it.

I've tried...

Alan G.


From alan.gauld@bt.com  Thu Dec 27 13:57:54 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 27 Dec 2001 13:57:54 -0000
Subject: [Tutor] ok, I want to read a dir.
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C20B@mbtlipnt02.btlabs.bt.co.uk>

> I want to read a dir. I spedify a path and a name pattern, such as
> '*.info', and read all examples of that pattern into a list.

Look at the glob module.

Yeah I know its a silly name and you'd never guess it, 
but its a historical Unix thing....

Alan g.



From arcege@speakeasy.net  Thu Dec 27 14:38:33 2001
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Thu, 27 Dec 2001 09:38:33 -0500
Subject: [Tutor] ok, I want to read a dir.
In-Reply-To: <3C2A9C69.3D974E25@my995internet.com>; from deliberatus@my995internet.com on Wed, Dec 26, 2001 at 10:58:33PM -0500
References: <Pine.LNX.4.21.0112261723150.32593-100000@hkn.eecs.berkeley.edu> <3C2A83E4.2C5F1D4E@my995internet.com> <20011226213715.F2524@speakeasy.net> <3C2A9C69.3D974E25@my995internet.com>
Message-ID: <20011227093833.G2524@speakeasy.net>

On Wed, Dec 26, 2001 at 10:58:33PM -0500, Kirk Bailey wrote:
> Say, looking this over, FILTER looks like a good candidate for this job.
> 
> 
> files=os.listdir('./lists/')            # this creates a raw dir listing
> filelist=[]                             # create an empty list
> fnmatch.filter(filelist, "*.info")      # return the subset of list
> which match!
> 
> this is not right, but close. What is the right way to use fnmatch and
> filter?

filelist = fnmatch.filter(os.listdir('./lists'), "*.info")

or going back to the glob module:

filelist = glob.glob1('./lists', "*.info")


> This is the error I get:
> 
> ns# ./TLpost.py
> Traceback (innermost last):
>   File "./TLpost.py", line 189, in ?
>     listname = sys.argv[1]
> IndexError: list index out of range
> ns# 
> 
> And that puzzles hell out of me.

This is a different error. The sys.argv is a list with the words from
the command line.

$ cat showargs.py
import sys
print sys.argv
$ python showargs.py
['showargs.py']
$ python showargs.py hi there
['showargs.py', 'hi', 'there']
$ python showargs.py "hi there"
['showargs.py', 'hi there']

Your command has only the program name and no other arguments.
So sys.argv[1] would be out of bounds in the list (there is only one
element).  You might want to put a try-except around the statement.

try:
  listname = sys.argv[1]
except IndexError:
  raise SystemExit("list name argument required")

And if you ever want to add command-line options, you might want to look
into the getopt module.

  -Arcege



From i812@iname.com  Thu Dec 27 14:50:32 2001
From: i812@iname.com (Rob McGee)
Date: Thu, 27 Dec 2001 08:50:32 -0600
Subject: [Tutor] Modules/Setup in 2.2 source package [and IDLE in Slackware]
In-Reply-To: <Pine.LNX.4.21.0112270104570.4873-100000@hkn.eecs.berkeley.edu>; from dyoo@hkn.eecs.berkeley.edu on Thu, Dec 27, 2001 at 01:09:16AM -0800
References: <20011226080507.G3310@hal> <Pine.LNX.4.21.0112270104570.4873-100000@hkn.eecs.berkeley.edu>
Message-ID: <20011227085032.A19199@zs>

As always, thanks for the reply, Danny. I'll also be replying to an old
post from Jeff, because I think I may have a clue on what went wrong for
him over a week ago.

On Thu, Dec 27, 2001 at 01:09:16AM -0800, Danny Yoo wrote:
> > I'm a little confused about Modules/Setup in Python 2.2. If I do
> > nothing to it, does that mean I get none of those modules? That seems
> > like an unusual amount of manual labor for configuring a package. :)
> 
> Think of it more like manual override.  The './configure' step on setting
> up Python on a Unix system should autodetect everything.  The
> Modules/Setup file is for unusual situations where the autodetect isn't
> seeing anything.

My Modules/Setup.config didn't have much in it. Only two things: threads
and signals modules. Autodetection seems to be a bit weak on Slackware.
(I guess I'm not surprised. :)

> > I'm upgrading from 2.0.1 which came with Slackware 8. I think I built
> > 2.0 from source before that, and I don't recall having to do so much
> > to it to make it work. But maybe that was because I didn't do much
> > with it.
> 
> I remember that on older versions of Python (1.52), I had to uncomment
> sections of Modules/Setup when I wanted to get Tkinter working.

I went through and uncommented what was appropriate for Tkinter. I got
IDLE to start and thus confirmed that Tkinter was working. However, IDLE
died with a segfault when I tried to close its help ("press F1") window
using the widget from the window manager (IceWM 1.0.8.) I haven't played
with it any more than that so I don't know more yet.

An interesting thing to note: IDLE from 2.0.1 doesn't work with the 2.2
interpreter. It crashed with a SyntaxError:
    import * is not allowed in function 'main' because it contains a
    nested function with free variables

BTW, I don't really expect you or anyone here to know the solution to
the problems Jeff and I are having with IDLE. I'm just posting for the
record and possibly for Jeff's benefit.

> Thankfully, Python configuration is a little smarter now, so you probably
> don't need to touch Modules/Setup.

I really don't know. :) I can't afford to take a chance because I don't
have enough time or CPU power to go recompiling things. I went ahead and
edited mine. Other than Tkinter I also got GNU readline working. I guess
the fact that everything compiled without errors tends to indicate that
I edited things correctly. (Actually I did have one mistake on which
"make" choked, but I fixed that.)

On Wed, Dec 19, 2001 at 04:11:46PM -0500, Jeff Jones wrote:
> I tried ./idle but got this error (retyped from linux to outlook):
>
> Traceback (most recent call last):
>   File "./idle", line 5, in ?
>      from idlelib import idleconf
> ImportError: No module IdleConf

I believe this is a PYTHONPATH problem. The "IdleConf" module it's
trying to load is not in a directory in your $PYTHONPATH variable. I'm
sure you can easily fix this in a number of ways. The way that worked
for me was simply to run "./idle.py" instead of just "idle". Apparently
by doing that I caused it to search the current directory in addition to
my non-existent PYTHONPATH variable.

Other (probably better) ways to fix it include to start IDLE from a
shell script which sets PYTHONPATH before the "idle" command, or to dig
through the Makefile and see if you can compile in some default values.
I think there's something about PYTHONPATH in Modules/Setup, too (it's
actually an extension of the Makefile, I think.)

> Thanks for all your help! I know I have seen people ask similar ?'s. Is
> there an archive of this list somewhere?

I don't know the full URL but I've seen it at www.activestate.com. That
archive isn't completely up-to-date; I think it must only be updated
once a month.

Jeff, let me know if you want me to send my Modules/Setup file. That
might help you restore some other missing functionality. In the meantime
you might want to "make uninstall" and revert to 2.0.1 -- that's what I
plan to do if I can't get IDLE working reliably.

It also might not hurt to ask on the Slackware newsgroup if anyone has
gotten Python 2.2 to work with all the bells and whistles (and the
"batteries included". :) I still don't have my own Usenet access set up,
though. :(

HTH,
    Rob - /dev/rob0


From grimmtoothtoo@yahoo.com  Thu Dec 27 15:31:54 2001
From: grimmtoothtoo@yahoo.com (Grimmtooth)
Date: Thu, 27 Dec 2001 10:31:54 -0500
Subject: [Tutor] IP sorting
In-Reply-To: <Pine.LNX.4.21.BCL.0112271026350.3051-100000@suzi.com.onego.ru>
Message-ID: <NLEIJCOLEACIANLABPOEMEDACDAA.grimmtoothtoo@yahoo.com>


> How to sort domain names AND IP addresses? NB. Domain names better to sort
> starting from level 1.
>
> bbb.aa
> aaa.bb
> ccc.cc

I'm sure someone more familiar with Python than I will have a slicker
solution, but I believe that if you split() the components of such things
into an array of tuples [(bbb,aa), (aaa,bb), (ccc.cc)] then you can compare
each tuple directly, e.g. (bbb,aa) > (aaa,bb). From there it should be a
fairly easy excercise to do the actual sort.




_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com



From ylee12@uiuc.edu  Thu Dec 27 15:30:31 2001
From: ylee12@uiuc.edu (Young-Jin Lee)
Date: Thu, 27 Dec 2001 09:30:31 -0600
Subject: [Tutor] [Q] Installing Python 2.2 on Redhat
Message-ID: <00e901c18eeb$6b7baa90$95757e82@visit2>

Hi, I have a problem installing Python 2.2 on Redhat.
I tried to install Python 2.2 using RPM in the python web site, but it
didn't work.
When I tried to install python2-2.2-2.i386.rpm, I got "python 2 = 2.1.1-2 is
needed by python-devel-2.1.1-2.
I also got "python 2 = 2.2 is needed by python2-devel-2.2-2" error message
when I tried to install python2-devel-2.2-2.i386.rpm.
How can I solve this problem?

TIA.

YJ



From jeff@ccvcorp.com  Thu Dec 27 18:03:19 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu, 27 Dec 2001 10:03:19 -0800
Subject: [Tutor] IP sorting
References: <E16Jdty-0002MM-00@mail.python.org>
Message-ID: <3C2B6267.8C1BCD@ccvcorp.com>

> "Grimmtooth" <grimmtoothtoo@yahoo.com> wrote:
>
> > How to sort domain names AND IP addresses? NB. Domain names better to sort
> > starting from level 1.
> >
> > bbb.aa
> > aaa.bb
> > ccc.cc
>
> I'm sure someone more familiar with Python than I will have a slicker
> solution, but I believe that if you split() the components of such things
> into an array of tuples [(bbb,aa), (aaa,bb), (ccc.cc)] then you can compare
> each tuple directly, e.g. (bbb,aa) > (aaa,bb). From there it should be a
> fairly easy excercise to do the actual sort.

Yes, but it'll sort them in the "wrong" order--you want all *.com names to come
before all *.net names (or so sayeth the spec given by Roman Suzi ;) ).  In order to
do this *just* for symbolic domain names, you could try this:

def sort_domains(domainlist):
    templist = [item.split('.') for item in domainlist]
    for line in templist:
        line.reverse()
    templist.sort()
    for line in templist:
        line.reverse()
    return ['.'.join(line) for line in templist]

This should sort domain names such that 'news.somename.com' will be right next to
'www.somename.com', but likely some distance from 'www.somename.net', which seems to
be the most appropriate sorting order for domain names.

However, this still doesn't fulfill the original spec, which asked to sort a mixed
list of domain names and numeric IP addresses...   I suppose that one could do
something like:

def sort_domains_and_IPs(unsortedlist):
    list1, list2 = segregate_IPs(unsortedlist)
    list1 = sort_IPs(list1)
    list2 = sort_domains(list2)
    list1.extend(list2)
    return list1

wherein I assume that all numeric IP addresses should sort before all named domains
(and use previously discussed sorting for IPs).  The implementation of
segregate_IPs() is the only problem remaining--I suppose that one could try map(int,
addr.split('.')), and if a ValueError is raised, assume it's a named domain...

def segregate_IPs(addresses):
    IPs = []
    domains = []
    for addr in addresses:
        try:
            l = map(int, addr.split('.'))
        except ValueError:
            domains.append(addr)
        else:
            IPs.append(addr)
    return IPs, domains

This looks like it ought to work, but it's untested and strictly off the top of my
head.  It's also probably horribly inefficient.  :)

Jeff Shannon
Technician/Programmer
Credit International




From prjoshi@ntc.net.np  Thu Dec 27 12:55:12 2001
From: prjoshi@ntc.net.np (Pravin Raj Joshi)
Date: Thu, 27 Dec 2001 18:25:12 +0530
Subject: [Tutor] RE...Two Questions.........from PRJoshi
Message-ID: <MABBICBJKOGBBPCNIOOBMEKGCCAA.prjoshi@ntc.net.np>

Hi,
I have a couple of questions.
1. I am currently using the latest realese of Python(Python 2.2). It does
not support the import command for my script i.e. when I divide my program
into a series of classes and keep each class in a new page, I cannot import
the pages to other pages. I get a message which says that module is not
found. I had the same problem with Python 2.2 beta. Can anyone tell me what
am I doing wrong.

2. I want to change the icon of my Tkinter program window. I read somewhere
that the icon in a root window cannot be changed. So I changed all my
windows to a Toplevel window and still I cannot change the icons. I copied
the code that is available for tkSimpleDialog (root/python/lib/lib-tk) and
tried and still it does not work. But the code works in the
SimpleDialog(changes icon to whatever is written in the title).

Please let me know of any solutions.
Thanks.
Pravin



From aleaxit@yahoo.com  Thu Dec 27 13:54:22 2001
From: aleaxit@yahoo.com (Alex Martelli)
Date: Thu, 27 Dec 2001 14:54:22 +0100
Subject: [Tutor] Re: [Python-Help] RE...Two Questions.........from PRJoshi
References: <MABBICBJKOGBBPCNIOOBMEKGCCAA.prjoshi@ntc.net.np>
Message-ID: <006101c18edd$fd74ee60$102b2bc1@cadlab.it>

"Pravin Raj Joshi" <prjoshi@ntc.net.np> writes:
    ...
> 1. I am currently using the latest realese of Python(Python 2.2). It does
> not support the import command for my script i.e. when I divide my program
> into a series of classes and keep each class in a new page, I cannot
import
> the pages to other pages. I get a message which says that module is not
> found. I had the same problem with Python 2.2 beta. Can anyone tell me
what
> am I doing wrong.

Not sure what you mean by "pages", but, anyway, the issue is most likely
that you're placing your whatever.py files in directories that are not
amongst those listed in sys.path.  When one of your modules does
    import whatever
then file whatever.py must be on one of sys.path's directories.  Fix
this either by moving your files to the appropriate directories, ones
that are already on sys.path, or by adding the directories you want to
use to sys.path.  For the latter's purposes, you have many possible
approaches, depending on what control, in detail, you have about your
machine.


> 2. I want to change the icon of my Tkinter program window. I read
somewhere
> that the icon in a root window cannot be changed. So I changed all my
> windows to a Toplevel window and still I cannot change the icons. I copied
> the code that is available for tkSimpleDialog (root/python/lib/lib-tk) and
> tried and still it does not work. But the code works in the
> SimpleDialog(changes icon to whatever is written in the title).

You're saying that SimpleDialog, copied IDENTICALLY, works or fails
to work for you depending on what directory you put it in?  Maybe it's
again a sys.path problem.  But I didn't think SimpleDialog had a
function to change its icon...?  Maybe I haven't looked at it recently
enough.  Anyway, you're not meant to COPY SimpleDialog, and you don't
have to: the best way to reuse its code is to INHERIT from it.


Please keep discussion on both issues on python-help@python.org, NOT
on my personal mailbox, so other volunteer helpers get a chance to
see and help, thanks.


Alex




From dyoo@hkn.eecs.berkeley.edu  Thu Dec 27 19:49:15 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 27 Dec 2001 11:49:15 -0800 (PST)
Subject: [Tutor] [Q] Installing Python 2.2 on Redhat
In-Reply-To: <00e901c18eeb$6b7baa90$95757e82@visit2>
Message-ID: <Pine.LNX.4.21.0112271145540.13759-100000@hkn.eecs.berkeley.edu>

On Thu, 27 Dec 2001, Young-Jin Lee wrote:

> Hi, I have a problem installing Python 2.2 on Redhat.
> I tried to install Python 2.2 using RPM in the python web site, but it
> didn't work.
> When I tried to install python2-2.2-2.i386.rpm, I got "python 2 = 2.1.1-2 is
> needed by python-devel-2.1.1-2.
> I also got "python 2 = 2.2 is needed by python2-devel-2.2-2" error message
> when I tried to install python2-devel-2.2-2.i386.rpm.
> How can I solve this problem?

What happens when you try to install both at the same time?  Try:

    rph -Uvh python2-*.rpm

so that the packaging system can see that both components are being
upgraded.  Redhat's package mangager is trying to make sure that your
system's not in an inconsistant state.

Good luck to you!



From dyoo@hkn.eecs.berkeley.edu  Thu Dec 27 20:01:25 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 27 Dec 2001 12:01:25 -0800 (PST)
Subject: [Tutor] Modules/Setup in 2.2 source package [and IDLE in Slackware]
In-Reply-To: <20011227085032.A19199@zs>
Message-ID: <Pine.LNX.4.21.0112271153080.13759-100000@hkn.eecs.berkeley.edu>

On Thu, 27 Dec 2001, Rob McGee wrote:

> > I remember that on older versions of Python (1.52), I had to uncomment
> > sections of Modules/Setup when I wanted to get Tkinter working.
> 
> I went through and uncommented what was appropriate for Tkinter. I got
> IDLE to start and thus confirmed that Tkinter was working. However,
> IDLE died with a segfault when I tried to close its help ("press F1")

Yikes!  That's a serious problem; IDLE should never segfault that that.  
You might want to see if the same thing happens with the IDLEfork version
of IDLE:

    http://idlefork.sourceforge.net/

and if the same crash occurs, this is something that needs to be reported
to the IDLE developers.



> An interesting thing to note: IDLE from 2.0.1 doesn't work with the 2.2
> interpreter. It crashed with a SyntaxError:
>     import * is not allowed in function 'main' because it contains a
>     nested function with free variables

Yes; this is a result of the new scoping rules that were introduced in
Python 2.1:

    http://www.amk.ca/python/2.1/index.html#SECTION000300000000000000000

"""One side effect of the change is that the from module import * and exec
statements have been made illegal inside a function scope under certain
conditions. The Python reference manual has said all along that from
module import * is only legal at the top level of a module, but the
CPython interpreter has never enforced this before."""


They're enforcing it now.  *grin*


Best of wishes!



From dyoo@hkn.eecs.berkeley.edu  Thu Dec 27 20:13:53 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 27 Dec 2001 12:13:53 -0800 (PST)
Subject: [Tutor] pyhton (fwd)
In-Reply-To: <Pine.LNX.4.21.0112261055060.28195-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.21.0112271207580.13759-100000@hkn.eecs.berkeley.edu>

On Wed, 26 Dec 2001, Danny Yoo wrote:

> hello do ou know were i can find a chart or page telling what the
> different commands on pyhton do?

Hello!  There's a 'Library Reference' that gives a list of the commands
you can use in Python:

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

However, it is very densely packed information, and if you're starting to
learn Python, I'd recommend not going through it like Cliff Notes.


You might find the tutorials at:

    http://python.org/doc/Newbies.html

more useful --- they may have the kind of summary that you're looking for.



> or better yet do you know wich command "enters" or goes to the next
> line on python?

I'm not sure I understand what you mean.  When we run Python programs, we
go from top-down, executing each statement in turn.  For example:

###
print 1
print 2
print 3
###

should print out:

###
1
2
3
###

without having to tell it to run the next line.

Please feel free to ask more questions on Tutor.  Good luck to you!



From grimmtoothtoo@yahoo.com  Thu Dec 27 20:23:06 2001
From: grimmtoothtoo@yahoo.com (Grimmtooth)
Date: Thu, 27 Dec 2001 15:23:06 -0500
Subject: [Tutor] IP sorting
In-Reply-To: <3C2B6267.8C1BCD@ccvcorp.com>
Message-ID: <NLEIJCOLEACIANLABPOEEEDCCDAA.grimmtoothtoo@yahoo.com>

> Yes, but it'll sort them in the "wrong" order--you want all *.com
> names to come
> before all *.net names (or so sayeth the spec given by Roman Suzi
> ;) ).  In order to
> do this *just* for symbolic domain names, you could try this:

Okay, then plan 'B'.  Instead of a simple > < comparison, use a function to
compare and have the function return a value based on a custom comparison
where it first compares the TLD then the actual address octets.

This is by no means a definitive means of doing it, but it works, I've done
it for similar data, yadda yadda. Basically, it's a bubble sort with a
custom comparison function. the variable 'Array' is all the elements that
you want to sort.

swap_flag =  1:

while swap_flag == 1:
  for i in range(0,len(array)-1)
    if compare(array(i), array(i+1)) == 1: # 1 means we want to swap
      x = array(i)
      array(i) = array(i+1)
      array(i+1) = x

def compare(a,b)

  # first, split a and b into tuples using the split() function

  # then compare the TLDs. I don't know what your criteria is here, but
  # you should return '1' if you want to swap, and continue otherwise.

  # then you iterate through the four octet values for the two elements.
  # return '1' if you want to swap, else continue to the next octet
  # until you're out of octets.

  # if you get here, return '0'.

A good candidate for sorting octets would be:

   for j in range(1,4): # assuming element 0 is the TLD and the
                        # remainder are the octets

     if int(a[j]) > int(b[j]:  # if we're sorting ascending, we need to swap
       return(1)
     elif int(a[j]) < int(b[j]:  # No need to swap, but don't continue
       return(-1)

   # if we got through all four iterations and still no difference, return
   # 0 to indicate equality

   return(0)

Those familiar with such things will realize that this is a basic bubble
sort. I am not yet familiar enough with the deep gizzards of Python
libraries to know if there's an inbuilt sorting function that's better or
faster.  If there's something like the ansi C lib's qsort(), the outline of
the compare() function would be perfect.

The above is suitable for an array of elements that are in the format

  tld.octet1.octet2.octet3.octet4

Obviously I haven't sussed the actual format quite yet :-)

> However, this still doesn't fulfill the original spec, which
> asked to sort a mixed
> list of domain names and numeric IP addresses...   I suppose that
> one could do
> something like:
>
> def sort_domains_and_IPs(unsortedlist):
>     list1, list2 = segregate_IPs(unsortedlist)
>     list1 = sort_IPs(list1)
>     list2 = sort_domains(list2)
>     list1.extend(list2)
>     return list1
>
> wherein I assume that all numeric IP addresses should sort before
> all named domains

The above compare function could be altered to prioritiz the octets before
the tlds, of course (by detecting alpha characters), but another -- SLOW --
alternative might be to use Python's internet libraries to RESOLVE the TLD
addresses and then replace them in the array with thier octets. This is
incredibly slow for purposes of analyzing a log in real-time, but might be
well-suited for a background task that kicked off on a copy of the day's
logs.

*** or *** :-)

Create two lists, one with numerics and one without. Do two sorts, and
present them in TWO seperate outputs. If it were me, this is the way I would
do it because it would be far more readable (IMHO).

> This looks like it ought to work, but it's untested and strictly
> off the top of my
> head.  It's also probably horribly inefficient.  :)

Yeah, double for me :-)  But if our primary concern was efficiency, a
different language might be more appropriate anyway, but if it goes along
smartly on my wimpy 400 MHz machine, I'm sure that the only bottleneck on a
more modern machine would be the file I/O anyway. :-)

Big megahertz are a wonderful thing :-D


_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com



From dyoo@hkn.eecs.berkeley.edu  Thu Dec 27 20:25:06 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 27 Dec 2001 12:25:06 -0800 (PST)
Subject: [Tutor] IP sorting
In-Reply-To: <NLEIJCOLEACIANLABPOEEEDCCDAA.grimmtoothtoo@yahoo.com>
Message-ID: <Pine.LNX.4.21.0112271219510.13759-100000@hkn.eecs.berkeley.edu>

On Thu, 27 Dec 2001, Grimmtooth wrote:

> Okay, then plan 'B'.  Instead of a simple > < comparison, use a function to
> compare and have the function return a value based on a custom comparison
> where it first compares the TLD then the actual address octets.


You'll like this one: Python's sort() function works very similarly to C's
qsort() --- we can give sort() a 'comparison function' to make the sort do
things our way.

Once we have something like your compare() function:


> def compare(a,b)
>    for j in range(1,4): # assuming element 0 is the TLD and the
>                         # remainder are the octets
>      if int(a[j]) > int(b[j]:  # if we're sorting ascending, we need to swap
>        return(1)
>      elif int(a[j]) < int(b[j]:  # No need to swap, but don't continue
>        return(-1)
>    return(0)


Python can use this to do the sort:

    ip_addresses.sort(compare)



From grimmtoothtoo@yahoo.com  Thu Dec 27 21:16:53 2001
From: grimmtoothtoo@yahoo.com (Grimmtooth)
Date: Thu, 27 Dec 2001 16:16:53 -0500
Subject: [Tutor] IP sorting
In-Reply-To: <Pine.LNX.4.21.0112271219510.13759-100000@hkn.eecs.berkeley.edu>
Message-ID: <NLEIJCOLEACIANLABPOEIEDDCDAA.grimmtoothtoo@yahoo.com>

> You'll like this one: Python's sort() function works very similarly to C's
> qsort() --- we can give sort() a 'comparison function' to make the sort do
> things our way.

I figured, but I'm too lazy to open another doc window sometimes.

Now if I can only remember when I need it ... :-)



_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com



From deliberatus@my995internet.com  Thu Dec 27 21:53:25 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Thu, 27 Dec 2001 16:53:25 -0500
Subject: [Tutor] WHY IT DI DIS?
Message-ID: <3C2B9855.651AEF8D@my995internet.com>

OK, WHY DOES IT DO THIS?


ns# ./TLwebmgr.py
  File "./TLwebmgr.py", line 35
    print "<a href=" + \" + webpath + "cgi-bin/commander.py?list=" + x +
\" + '>' + x + "</a> ", descriptor(x) + '<P>'
                                                                                                                    
^
SyntaxError: invalid token


-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From chrislubrecht@home.com  Thu Dec 27 23:35:02 2001
From: chrislubrecht@home.com (ccl)
Date: Thu, 27 Dec 2001 18:35:02 -0500
Subject: [Tutor] Config files & getopt()
Message-ID: <5.1.0.14.0.20011227182747.00a71a80@pop3.norton.antivirus>

First, thanks for the help on IP sorting. I added it to the program and it 
runs great.

If it gets to the point I like it, I may post it here as an example of how 
-NOT- to do data reduction and generate statistical data on a million+ line 
file :)

Anyway...

I am still tinkering with other stuff too...

As a background, I have -0- programming experience and am learning both 
Python and programming from scratch. So far so good, however I am having 
problems understanding two things I need for something I am writing.

The first is getopt(). I just don't get it. Can someone give a better 
description of it, other than is presented in the module, (with examples 
too! :) )? I have tried that one, the O'Reily book and searching 
online..and I am still kinda lost...although I do know 
getopt(arg,option(,long options)) :)


The second, is I would like to add a config file to  program..something 
along the lines of an apache httpd.conf file, to specify directories and 
the like. I checked out ConfigParser...and I just dont get it..

Ok..so I am feeling moronic today :)

Any kind soul wanna hand hold a true newbie?


Thanks in advance..

Chris



From arcege@speakeasy.net  Thu Dec 27 23:40:17 2001
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Thu, 27 Dec 2001 18:40:17 -0500
Subject: [Tutor] WHY IT DI DIS?
In-Reply-To: <3C2B9855.651AEF8D@my995internet.com>; from deliberatus@my995internet.com on Thu, Dec 27, 2001 at 04:53:25PM -0500
References: <3C2B9855.651AEF8D@my995internet.com>
Message-ID: <20011227184017.A911@speakeasy.net>

On Thu, Dec 27, 2001 at 04:53:25PM -0500, Kirk Bailey wrote:
> OK, WHY DOES IT DO THIS?
> 
> 
> ns# ./TLwebmgr.py
>   File "./TLwebmgr.py", line 35
>     print "<a href=" + \" + webpath + "cgi-bin/commander.py?list=" + x +
> \" + '>' + x + "</a> ", descriptor(x) + '<P>'
>                                                                                                                     
> ^
> SyntaxError: invalid token
> 

The   + \" +   expression is incorrect.  Quoting a double quote
only works withing a string.  In a more simple form you can have:
  print "<a href=\"" + webpath + "cgi-bin/commander.py?list=" + x + \
    "\">" + x + "</a> ", descriptor(x) + "<P>"

Or with string formats and single quotes,
  print '<a href="%scgi-bin/commander.py?list=%s">%s</a> %s<P>' % \
    ( webpath, x, x, descriptor(x) )

The only place where you may want to be more distinguishing is at the
'%scgi' part.  But then for that one URL concatenation, I'd be using
urlparse.urljoin myself. :)

  -Arcege



From deliberatus@my995internet.com  Fri Dec 28 00:50:01 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Thu, 27 Dec 2001 19:50:01 -0500
Subject: [Tutor] ok, I want to read a dir.
References: <Pine.LNX.4.21.0112261723150.32593-100000@hkn.eecs.berkeley.edu> <3C2A83E4.2C5F1D4E@my995internet.com> <20011226213715.F2524@speakeasy.net> <3C2A9C69.3D974E25@my995internet.com> <20011227093833.G2524@speakeasy.net> <3C2BBCF3.226C09D6@my995internet.com> <20011227194107.B911@speakeasy.net>
Message-ID: <3C2BC1B9.A5A5F69F@my995internet.com>

HAH! Our messages crossed! I just noticed this reading the reference,
and wrote to you. So how do we do this and not invoke functions not in
1.5.2?


"Michael P. Reilly" wrote:
> 
> On Thu, Dec 27, 2001 at 07:29:39PM -0500, Kirk Bailey wrote:
> > it got me this:
> >
> > Traceback (innermost last):
> >   File "./TLwebmgr.py", line 31, in ?
> >     filelist = fnmatch.filter(os.listdir('./lists'), "*.info")
> > AttributeError: filter
> > ns#
> >
> > AttributeError:  filter??? Hmmm?
> 
> The fnmatch.filter funciton was added only in Python 2.2.  The glob.glob1
> function I mentioned has been in Python since before 1.5.2.
> 
>   -Arcege
> 
> --
> +----------------------------------+-----------------------------------+
> | Michael P. Reilly                | arcege@speakeasy.net              |
> | Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html     |

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From dyoo@hkn.eecs.berkeley.edu  Fri Dec 28 01:34:06 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 27 Dec 2001 17:34:06 -0800 (PST)
Subject: [Tutor] pyhton (fwd)
Message-ID: <Pine.LNX.4.21.0112271731070.18301-100000@hkn.eecs.berkeley.edu>

Hi Ted,

It's usually a better idea to send your replies to 'tutor@python.org'
instead of me directly.  I don't want to be the weakest link here...
*grin*

Seriously though, it helps to send messages to the Tutor group because it
allows any one of the volunteers here to reply when others are busy.  
I'll forward your message to the others on Tutor.


----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: <tutor@python.org>
Cc: <civic525@hotmail.com>
Sent: Thursday, December 27, 2001 2:13 PM
Subject: Re: [Tutor] pyhton (fwd)


> On Wed, 26 Dec 2001, Danny Yoo wrote:
>
> > hello do ou know were i can find a chart or page telling what the
> > different commands on pyhton do?
>
> Hello!  There's a 'Library Reference' that gives a list of the commands
> you can use in Python:
>
>     http://www.python.org/doc/lib/
>
> However, it is very densely packed information, and if you're starting to
> learn Python, I'd recommend not going through it like Cliff Notes.
>
>
> You might find the tutorials at:
>
>     http://python.org/doc/Newbies.html
>
> more useful --- they may have the kind of summary that you're looking for.
>
>
>
> > or better yet do you know wich command "enters" or goes to the next
> > line on python?
>
> I'm not sure I understand what you mean.  When we run Python programs, we
> go from top-down, executing each statement in turn.  For example:
>
> ###
> print 1
> print 2
> print 3
> ###
>
> should print out:
>
> ###
> 1
> 2
> 3
> ###
>
> without having to tell it to run the next line.
>
> Please feel free to ask more questions on Tutor.  Good luck to you!
>

i tried that but i just sead
###
>>>1
>>>print 2
>>>2
>>>print 3
>>>3

          if you know whats wrong please help me



From dyoo@hkn.eecs.berkeley.edu  Fri Dec 28 01:37:10 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 27 Dec 2001 17:37:10 -0800 (PST)
Subject: [Tutor] [Q] Installing Python 2.2 on Redhat (fwd)
Message-ID: <Pine.LNX.4.21.0112271735220.18301-100000@hkn.eecs.berkeley.edu>

Hi Young-Jin,

Let me forward your question to the rest of the Tutor list; I'll take a
look after dinner.


---------- Forwarded message ----------
Date: Thu, 27 Dec 2001 15:44:56 -0600
From: Young-Jin Lee <ylee12@uiuc.edu>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] [Q] Installing Python 2.2 on Redhat

> What happens when you try to install both at the same time?  Try:
>
>     rph -Uvh python2-*.rpm

I tried to double-click them in the Konqueror one by one and I got the
errors.
(I'm new to Redhat.) The Redhat linux installed on my computer does not have
"rph".
How can I solve it in this situation?

TIA
----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "Young-Jin Lee" <ylee12@uiuc.edu>
Cc: <tutor@python.org>
Sent: Thursday, December 27, 2001 1:49 PM
Subject: Re: [Tutor] [Q] Installing Python 2.2 on Redhat


> On Thu, 27 Dec 2001, Young-Jin Lee wrote:
>
> > Hi, I have a problem installing Python 2.2 on Redhat.
> > I tried to install Python 2.2 using RPM in the python web site, but it
> > didn't work.
> > When I tried to install python2-2.2-2.i386.rpm, I got "python 2 =
2.1.1-2 is
> > needed by python-devel-2.1.1-2.
> > I also got "python 2 = 2.2 is needed by python2-devel-2.2-2" error
message
> > when I tried to install python2-devel-2.2-2.i386.rpm.
> > How can I solve this problem?
>
> What happens when you try to install both at the same time?  Try:
>
>     rph -Uvh python2-*.rpm
>
> so that the packaging system can see that both components are being
> upgraded.  Redhat's package mangager is trying to make sure that your
> system's not in an inconsistant state.
>
> Good luck to you!
>



From deliberatus@my995internet.com  Fri Dec 28 01:45:50 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Thu, 27 Dec 2001 20:45:50 -0500
Subject: [Tutor] ok, I want to read a dir.
References: <Pine.LNX.4.21.0112261723150.32593-100000@hkn.eecs.berkeley.edu> <3C2A83E4.2C5F1D4E@my995internet.com> <20011226213715.F2524@speakeasy.net> <3C2A9C69.3D974E25@my995internet.com> <20011227093833.G2524@speakeasy.net> <3C2BBCF3.226C09D6@my995internet.com> <20011227194107.B911@speakeasy.net>
Message-ID: <3C2BCECE.53A402A5@my995internet.com>

ok, this is improving, still WRONG, but much closer.

Here is the new version:

ns# list TLwebmgr.py
Listing of file TLwebmgr.py in
directory:/www/www.howlermonkey.net/cgi-bin

#!/usr/local/bin/python
#
# You must define the next lien for the WEB path to your server's web
directory!
# ALL web scripts must live in the cgi-bin UNDER this dir!
# THAT IS WHERE TL LIVES! /lists lives UNDER that dir in the tree!
#
webpath="http://www.howlermonkey.net/"
import string, sys, os, glob
#
CRLF="\r\n"
forminput=sys.stdin
filelist=[]
print "<html><head>Content-Type: text/html"             # HTML is
following
print "Content-Type: text/html"                         # HTML is
following
print                                                   # blank line,
end of headers
print " <TITLE>TinyList WebManager menu page</TITLE>"   # tells the
browser the title
print " <STYLE TYPE=\"text/css\">"
print " <!--  A { text-decoration: none; }  A:visited, A:hover,
A:active  text-decoration:none; } // -->"
print " </STYLE>" 
print " </head>"                                                # this
is the end of the head
print " <body bgcolor=\"#FFFFFF\" text=\"#000000\" links=\"0000FF\"
><blockquote><P>"
print " <center><h1>TinyList membership management
menu</h1></center><P><br>"
print "Here are all the lists we host here:<P>"
print "<hr width=60% align=\"center\"><P>"
#
def descriptor(filename):                       # Read 1st line in file
named.
        f1=open(filename,'r')                   #open the file named,
        info=string.strip(f1.readline())        # read the first line in
the file
        f1.close()                              # close the file
        return info                             # and exit returning the
1 line read
#

filelist = glob.glob('./lists/*.info')
#
for x in filelist:                              # filelist lists all the
available info files
        #
        print "<a href= \"" + webpath + "cgi-bin/commander.py?list=" + x
+  "\">" + x + "</a> ", descriptor(x) +'<P>'
#which means:
#      print 'a
href="http://www.howlermonkey.net/cgi-bin/commander.py?list=(listname)">
(description)<p>'
#
#
print "<hr width=60% align=\"center\"><P><br>"
print "Please click a name to read the entire description and to access
the form to subscribe or subscribe for that list.<P>
<br>"
print "<P><br><small><A href=\"http://www.tinylist.org/ \">Powered by
TinyList!</a></small><P><br></body></html>"

and it is in the server. Click this link to see it's output:
	http://www.howlermonkey.net/cgi-bin/TLwebmgr.py

and this one should let you view the current source code:
	http://www.howlermonkey.net/TLwebmgr.shtml

Now, the thing is working, but still supplies me with more than desired
in the text. I want to take this by the forlock and cut off the
extranious stuff, at least for display purposes.

I am taking the liberty of posting this also to tutor list.
 


"Michael P. Reilly" wrote:
> 
> On Thu, Dec 27, 2001 at 07:29:39PM -0500, Kirk Bailey wrote:
> > it got me this:
> >
> > Traceback (innermost last):
> >   File "./TLwebmgr.py", line 31, in ?
> >     filelist = fnmatch.filter(os.listdir('./lists'), "*.info")
> > AttributeError: filter
> > ns#
> >
> > AttributeError:  filter??? Hmmm?
> 
> The fnmatch.filter funciton was added only in Python 2.2.  The glob.glob1
> function I mentioned has been in Python since before 1.5.2.
> 
>   -Arcege
> 
> --
> +----------------------------------+-----------------------------------+
> | Michael P. Reilly                | arcege@speakeasy.net              |
> | Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html     |

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From i812@iname.com  Fri Dec 28 02:22:53 2001
From: i812@iname.com (Rob McGee)
Date: Thu, 27 Dec 2001 20:22:53 -0600
Subject: [Tutor] [Q] Installing Python 2.2 on Redhat (fwd)
In-Reply-To: <Pine.LNX.4.21.0112271735220.18301-100000@hkn.eecs.berkeley.edu>; from dyoo@hkn.eecs.berkeley.edu on Thu, Dec 27, 2001 at 05:37:10PM -0800
References: <Pine.LNX.4.21.0112271735220.18301-100000@hkn.eecs.berkeley.edu>
Message-ID: <20011227202253.B19199@zs>

> ---------- Forwarded message ----------
> Date: Thu, 27 Dec 2001 15:44:56 -0600
> From: Young-Jin Lee <ylee12@uiuc.edu>
> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] [Q] Installing Python 2.2 on Redhat
> 
> > What happens when you try to install both at the same time?  Try:
> >
> >     rph -Uvh python2-*.rpm
> 
> I tried to double-click them in the Konqueror one by one and I got the
> errors.
> (I'm new to Redhat.) The Redhat linux installed on my computer does not have
> "rph".
> How can I solve it in this situation?

"rph" is a typo. "rpm" is the correct program (Redhat Package Manager.)
Don't click anything -- log in at the console or open some kind of X
terminal ("Konsole" is a good choice.) Then type the command.

Note, I don't do RedHat so I can't help any more than this. I don't even
know if the "-Uvh" parameters are correct. But you could look it up on
your own by typing "man rpm" in the console (or Konsole.) Free software
is all about empowering users to solve their own problems. :)

HTH,
    Rob - /dev/rob0


From i812@iname.com  Fri Dec 28 02:28:52 2001
From: i812@iname.com (Rob McGee)
Date: Thu, 27 Dec 2001 20:28:52 -0600
Subject: [Tutor] [Q] Installing Python 2.2 on Redhat
In-Reply-To: <Pine.LNX.4.21.0112271145540.13759-100000@hkn.eecs.berkeley.edu>; from dyoo@hkn.eecs.berkeley.edu on Thu, Dec 27, 2001 at 11:49:15AM -0800
References: <00e901c18eeb$6b7baa90$95757e82@visit2> <Pine.LNX.4.21.0112271145540.13759-100000@hkn.eecs.berkeley.edu>
Message-ID: <20011227202852.C19199@zs>

One other thing I forgot to mention before: running rpm to install or
remove software requires root privileges. If you're using your user
account, as you should, you will need to become root to run rpm. "su"
can do this for you -- just type the root password when prompted. And
Konsole has its built-in "root console" feature; you can have a root
prompt in the same session.

    Rob - /dev/rob0


From grimmtoothtoo@yahoo.com  Fri Dec 28 03:46:11 2001
From: grimmtoothtoo@yahoo.com (Grimmtooth)
Date: Thu, 27 Dec 2001 22:46:11 -0500
Subject: [Tutor] WHY IT DI DIS?
In-Reply-To: <3C2B9855.651AEF8D@my995internet.com>
Message-ID: <NLEIJCOLEACIANLABPOEEEDGCDAA.grimmtoothtoo@yahoo.com>

> OK, WHY DOES IT DO THIS?
>
> ns# ./TLwebmgr.py
>   File "./TLwebmgr.py", line 35
>     print "<a href=" + \" + webpath + "cgi-bin/commander.py?list=" + x +
> \" + '>' + x + "</a> ", descriptor(x) + '<P>'
>
> ^
> SyntaxError: invalid token

Looks like a mismatched quote, MAYBE, hard to tell for sure.

It MIGHT help to use substitution rather than concatenating all that stuff
together. It has bitten me in the backside more times than I care to tell
:-) If you're familiar with 'c' formatting codes, it follows pretty much the
same pattern except in how the arguments are indicated. Example (and not
necessarilly what you intended):

print "<a href=\"%scgi-bin/commander.py?list=%s\">%s</a>%s<P>" % (webpath,
x, x, descriptor(x))

Each of the items in the parenthesis goes into the 'bucket' designated by a
%s in the string itself, respectively in order of appearance, so to speak.



_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com



From dyoo@hkn.eecs.berkeley.edu  Fri Dec 28 04:22:33 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 27 Dec 2001 20:22:33 -0800 (PST)
Subject: [Tutor] [Q] Installing Python 2.2 on Redhat (fwd)
In-Reply-To: <20011227202253.B19199@zs>
Message-ID: <Pine.LNX.4.21.0112272017020.19888-100000@hkn.eecs.berkeley.edu>

On Thu, 27 Dec 2001, Rob McGee wrote:

> > > What happens when you try to install both at the same time?  Try:
> > >
> > >     rph -Uvh python2-*.rpm
> > 
> > I tried to double-click them in the Konqueror one by one and I got the
> > errors.
> > (I'm new to Redhat.) The Redhat linux installed on my computer does not have
> > "rph".
> > How can I solve it in this situation?
> 
> "rph" is a typo. "rpm" is the correct program (Redhat Package
> Manager.) Don't click anything -- log in at the console or open some
> kind of X terminal ("Konsole" is a good choice.) Then type the
> command.

Thanks for the correction, and apologies for my mistake!  The keyboard
that I'm using at the moment is much stickier than the one back home.

'rpm' is the "Redhat Package Manager' --- it's what the Redhat Linux
distribution uses to manage all the software in its distribution.


> Note, I don't do RedHat so I can't help any more than this. I don't
> even know if the "-Uvh" parameters are correct. But you could look it
> up on your own by typing "man rpm" in the console (or Konsole.) Free
> software is all about empowering users to solve their own problems. :)

I picked up those set of parameters as a habit, but I think they stand
for:

    -U: Upgrade
    -v: be Verbose about it
    -h: show Hash marks to indicate how much has been done.  This is
        like a progress bar.

Good luck to you!



From karthikg@aztec.soft.net  Fri Dec 28 04:42:35 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Fri, 28 Dec 2001 10:12:35 +0530
Subject: [Tutor] Config files & getopt()
In-Reply-To: <5.1.0.14.0.20011227182747.00a71a80@pop3.norton.antivirus>
Message-ID: <NEBBJNMDEKBIBCMCNMBDMEFMCMAA.karthikg@aztec.soft.net>

see of this is useful...
it creates a config file and then reads from it.

>>> from ConfigParser import *
>>> fp = open("test.conf","w+")
>>> c = ConfigParser()
>>> c.add_section("server")
>>> c.set("server","dsn","octago")
>>> c.set("server","password","octago")
>>> c.set("server","userid","octago")
>>> c.add_section("properties")
>>> c.set("properties","log","d:\\temp\\logs")
>>> c.set("properties","templates","d:\\temp\\templates")
>>> c.write(fp)
>>> fp.close()
........Now read from the same.....

>>> f = open("test.conf","r")
>>> c.readfp(f)
>>> c.sections()
['server', 'properties']
>>> c.get('server','dsn')
'octago'
>>> c.get('server','password')
'octago'
>>> c.get('server','userid')
'octago'
>>> c.get('properties','log')
'd:\\temp\\logs'
>>> c.get('properties','templates')
'd:\\temp\\templates'
>>>

[server]
userid = octago
password = octago
dsn = octago

[properties]
log = d:\temp\logs
templates = d:\temp\templates


never used getopt though

karthik.
-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
ccl
Sent: Friday, December 28, 2001 5:05 AM
To: tutor@python.org
Subject: [Tutor] Config files & getopt()


First, thanks for the help on IP sorting. I added it to the program and it
runs great.

If it gets to the point I like it, I may post it here as an example of how
-NOT- to do data reduction and generate statistical data on a million+ line
file :)

Anyway...

I am still tinkering with other stuff too...

As a background, I have -0- programming experience and am learning both
Python and programming from scratch. So far so good, however I am having
problems understanding two things I need for something I am writing.

The first is getopt(). I just don't get it. Can someone give a better
description of it, other than is presented in the module, (with examples
too! :) )? I have tried that one, the O'Reily book and searching
online..and I am still kinda lost...although I do know
getopt(arg,option(,long options)) :)


The second, is I would like to add a config file to  program..something
along the lines of an apache httpd.conf file, to specify directories and
the like. I checked out ConfigParser...and I just dont get it..

Ok..so I am feeling moronic today :)

Any kind soul wanna hand hold a true newbie?


Thanks in advance..

Chris


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


From dyoo@hkn.eecs.berkeley.edu  Fri Dec 28 04:29:23 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 27 Dec 2001 20:29:23 -0800 (PST)
Subject: [Tutor] pyhton (fwd)
In-Reply-To: <Pine.LNX.4.21.0112271731070.18301-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.21.0112272023510.19888-100000@hkn.eecs.berkeley.edu>

On Thu, 27 Dec 2001, Danny Yoo wrote:

> i tried that but i just sead
> ###
> >>>1
> >>>print 2
> >>>2
> >>>print 3
> >>>3
>           if you know whats wrong please help me

Ok, I think I understand a little better.  Yes, what you're running is
Python's "interpreter" --- it will run commands the moment you type them
in.  It's analogous to an interactive calculator, just much more powerful.

The interpreter is good for experimentation, but it's not meant for
writing whole programs.  What's happening is that, as soon as you enter in
a command, Python executes it --- that's why it appears that the
interpreter is interrupting you.


Instead, you'll probably want to write your program in a text file, and
then run Python over that text file.  You can write text files using
Notepad, but there's a much nicer text editor called IDLE that should be
installed on your computer.

Here's a small introduction that may help you:

    http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro

I hope it clears things up!  If you have more questions, please email
tutor@python.org.



From alan.gauld@bt.com  Fri Dec 28 11:48:02 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 28 Dec 2001 11:48:02 -0000
Subject: [Tutor] pyhton (fwd)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C20E@mbtlipnt02.btlabs.bt.co.uk>

>> Python programs, we go from top-down, executing each statement 
>> in turn.  For example:
>> ###
>> print 1
>> print 2
>> print 3
>> ###
>> 
>> should print out:
>> 
>> ###
>>  1
>>  2
>>  3
>> ###

> i tried that but i just sead
> ###
> >>>1
> >>>print 2
> >>>2
> >>>print 3
> >>>3

Thats coz you are using pythons interactive mode.

If you type your program into a file using notepad say, 
or better still in IDLE use File|New menu item.

Then run that file using python from the DOS command line
(or using Ctrl-F5 in IDLE) it will act as Danny suggested.

To reiterate:

use notepad to create a file called prints.py containing:

print 1
print 2
print 3

Now start an MS DOS window and at the C:\> prompt type:

C:\> python prints.py

You should then see 

1
2
3

displayed as output.

OR in IDLE use File|Open to open a new window and 
type in the same 3 lines. Use File|SaveAs... to save 
the file as prints.py Now hit Ctrl-F5 and in the 
original IDLE window you will see the output:
1
2
3

As before.

HTH,

Alan G.


From karthikg@aztec.soft.net  Fri Dec 28 12:13:17 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Fri, 28 Dec 2001 17:43:17 +0530
Subject: [Tutor] module objects
In-Reply-To: <Pine.LNX.4.21.0112272017020.19888-100000@hkn.eecs.berkeley.edu>
Message-ID: <NEBBJNMDEKBIBCMCNMBDOEGACMAA.karthikg@aztec.soft.net>

hi!,

i remember reading that a module in python is also an object.
so if i define a file test.py , i have a test module object.
i observed that sys.modules is a dict containing many modules.
if i add my module also to this dictionary what can i achieve?
i guess am not able to put it properly but my question is
that what can i do with it? some examples w'd help.

import test
import sys
sys.modules['test'] = test

TIA,
karthik.






From alan.gauld@bt.com  Fri Dec 28 11:54:22 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 28 Dec 2001 11:54:22 -0000
Subject: [Tutor] RE...Two Questions.........from PRJoshi
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C20F@mbtlipnt02.btlabs.bt.co.uk>

> not support the import command for my script i.e. when I 
> divide my program into a series of classes and keep each 
> class in a new page, I cannot import

You need to save them into a folder on your PYTHONPATH
PYTHONPATH is an environment variable that you need to 
set up - via AUTOEXEC.BAT if Win9x or via a 
ControlPanel|System|???? dialog box on NT/2000/XP

> 2. I want to change the icon of my Tkinter program window. I 
> read somewhere that the icon in a root window cannot be 
> changed. 

So far as I know you can't change that icon on any 
window under Windows - its a Tk bug not Tkinter. If 
anyone does know how I'd love to know...

> the code that is available for tkSimpleDialog 

I think that is used on Unix systems but has no 
effect on Windows because...

> tried and still it does not work. But the code works in the
> SimpleDialog(changes icon to whatever is written in the title).

SimpleDialog on windows actually calls the standard Windows 
message boxes rather than building them from scratch in Tk. 
Thus Windows correctly applies the required icon. Thus Tk 
apps on Windows not only have the wrong icon, they aren't 
even consistently wrong!

At least thats what I think is going on...

Alan g.


From scarblac@pino.selwerd.nl  Fri Dec 28 12:43:08 2001
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Fri, 28 Dec 2001 13:43:08 +0100
Subject: [Tutor] module objects
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDOEGACMAA.karthikg@aztec.soft.net>; from karthikg@aztec.soft.net on Fri, Dec 28, 2001 at 05:43:17PM +0530
References: <Pine.LNX.4.21.0112272017020.19888-100000@hkn.eecs.berkeley.edu> <NEBBJNMDEKBIBCMCNMBDOEGACMAA.karthikg@aztec.soft.net>
Message-ID: <20011228134308.A5415@pino.selwerd.nl>

On  0, Karthik Gurumurthy <karthikg@aztec.soft.net> wrote:
> i remember reading that a module in python is also an object.
> so if i define a file test.py , i have a test module object.
> i observed that sys.modules is a dict containing many modules.
> if i add my module also to this dictionary what can i achieve?
> i guess am not able to put it properly but my question is
> that what can i do with it? some examples w'd help.
> 
> import test
> import sys
> sys.modules['test'] = test

The first time you do 'import test', the module is loaded and automatically
put into sys.modules (so it's of no use to do it by hand).

If you later import test again (say, in another module), it's simply
retrieved from sys.modules and doesn't have to be loaded from the file all
over again.

This means that if you had put it into sys.modules as some other name, you
could have imported that name as well:

import test
import sys
sys.modules['test2'] = test
import test2
print test is test2 # prints 1

-- 
Remco Gerlich


From arcege@speakeasy.net  Fri Dec 28 15:22:42 2001
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Fri, 28 Dec 2001 10:22:42 -0500
Subject: [Tutor] ok, I want to read a dir.
In-Reply-To: <3C2BCECE.53A402A5@my995internet.com>; from deliberatus@my995internet.com on Thu, Dec 27, 2001 at 08:45:50PM -0500
References: <Pine.LNX.4.21.0112261723150.32593-100000@hkn.eecs.berkeley.edu> <3C2A83E4.2C5F1D4E@my995internet.com> <20011226213715.F2524@speakeasy.net> <3C2A9C69.3D974E25@my995internet.com> <20011227093833.G2524@speakeasy.net> <3C2BBCF3.226C09D6@my995internet.com> <20011227194107.B911@speakeasy.net> <3C2BCECE.53A402A5@my995internet.com>
Message-ID: <20011228102242.A919@speakeasy.net>

On Thu, Dec 27, 2001 at 08:45:50PM -0500, Kirk Bailey wrote:
> 
> ok, this is improving, still WRONG, but much closer.
> 
[beginning code snipped]
> def descriptor(filename):                       # Read 1st line in file
> named.
>         f1=open(filename,'r')                   #open the file named,
>         info=string.strip(f1.readline())        # read the first line in
> the file
>         f1.close()                              # close the file
>         return info                             # and exit returning the
> 1 line read
> #
> 
> filelist = glob.glob('./lists/*.info')
> #
> for x in filelist:                              # filelist lists all the
> available info files
>         #
>         print "<a href= \"" + webpath + "cgi-bin/commander.py?list=" + x
> +  "\">" + x + "</a> ", descriptor(x) +'<P>'
> #which means:
> #      print 'a
> href="http://www.howlermonkey.net/cgi-bin/commander.py?list=(listname)">
> (description)<p>'
> #
[rest snipped]

Okay, you need the pathname to get the descriptor, but you do not want
the path in the HTML.  Got it finally. :)

  filelist = glob.glob('./lists/*.info')
  for path in filelist:
    fname = os.path.basename(path)  # get just '*.info'
    url = webpath + 'cgi-bin/commander.py?list=' + fname  # I would
                      # put this on a separate line for clarity
    print '<a href="%s">%s</a>' % (url, fname), descriptor(path) + "<P>"

It might also be that you want to get rid of the '.info' portion in the
anchor tag itself.

  filelist = glob.glob('./lists/*.info')
  for path in filelist:
    fname = os.path.basename(path)  # get just '*.info'
    basename = os.path.splitext(fname)[0]   # take off '.info'
    # I would put this on a separate variable for clarity
    url = webpath + 'cgi-bin/commander.py?list=' + fname
    print '<a href="%s">%s</a>' % (url, basename), descriptor(path) + '<P>'

You might also want to put some code in if there are no files in the
filelist list.

  -Arcege



From prjoshi@ntc.net.np  Fri Dec 28 11:02:48 2001
From: prjoshi@ntc.net.np (Pravin Raj Joshi)
Date: Fri, 28 Dec 2001 16:32:48 +0530
Subject: [Tutor] Re...From PRJoshi
Message-ID: <MABBICBJKOGBBPCNIOOBIEKJCCAA.prjoshi@ntc.net.np>

This is a multi-part message in MIME format.

------=_NextPart_000_0000_01C18FBD.49EC5320
Content-Type: multipart/alternative;
	boundary="----=_NextPart_001_0001_01C18FBD.49EC5320"


------=_NextPart_001_0001_01C18FBD.49EC5320
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hi,

Sorry for not being very clear with my last questions.
I seem to have solved the problem for the pages and files.
But I would like to clearify my second question.
What I want to do is change the icon of my windows. (I have inserted a photo
of what I want to do!)



Basically I want to change the TK icon with something else. I read somewhere
it was not possible to change that for the root, but it was possible for the
toplevel.

How to change that?

Thanks

PRJoshi


------=_NextPart_001_0001_01C18FBD.49EC5320
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><TITLE></TITLE>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 5.50.4134.600" name=3DGENERATOR></HEAD>
<BODY>
<P><FONT size=3D2>Hi,</FONT></P>
<P><FONT size=3D2>Sorry for not being very clear with my last =
questions.<BR>I seem=20
to have solved the problem for the pages and files.<BR>But I would like =
to=20
clearify my second question.<BR>What I want to do is change the icon of =
my=20
windows. (I have inserted a photo of what I want to do!)</FONT> </P>
<P><IMG alt=3D"" hspace=3D0 src=3D"cid:860480111@28122001-241b" =
align=3Dbaseline=20
border=3D0></P>
<P><FONT face=3DArial size=3D2>Basically I want to change the TK icon =
with something=20
else. I read somewhere it was not possible to change that for the root, =
but it=20
was possible for the toplevel.</FONT></P>
<P><FONT face=3DArial size=3D2>How to change that?</FONT></P>
<P><FONT face=3DArial size=3D2>Thanks</FONT></P>
<P><FONT face=3DArial size=3D2>PRJoshi</FONT></P></BODY></HTML>

------=_NextPart_001_0001_01C18FBD.49EC5320--

------=_NextPart_000_0000_01C18FBD.49EC5320
Content-Type: image/gif;
	name="icon_photo.gif"
Content-Transfer-Encoding: base64
Content-ID: <860480111@28122001-241b>

R0lGODlhDQF+ALMAAH9/fwAAf7+/v+kAAP///wEBAd7e3icnJ0lJSY6Ojht/f1oAf+/v75EAAGBv
b7eioiH5BAAAAAAALAAAAAANAX4AAAT/kMhJq7046827/2AojmRpnmiXCJMBMNP6wRXduYjDEkKS
qomgUND7GY/IZCmBmDgKj8kh2nk0KYaCR1BAMAsspvICQCAKB3PwOm6736mHVpJ2SLIGj5jC7TAK
PhIIBwR7cBNeMWyHjI2OWAV5fwKEBA+VD0F5PAyaBAwOBzsSCWAwnQCbFJeQBkyugXdBOwYGPaOw
DLhBNhWJpAiwWLwTmQk2uY/KyxuiPISRhU1Pg9FdBweRXAVzEtym2NmxEg52FgnYZwCkaNlRZthQ
BFnhc6XhvYix6GkF64XtDsAA0AUNO3zMEiokkCjBugM+vGTZAZFAl08VDUnoQyAUjFKq/xiOiwEG
IJ1ADpoMgmGm45Vs8wAJMudrX8lSMQPlsBjFwIFaMhnSXEiUkRgEUQDYKbmJkg95DNdp5DGn4kkK
CP5VQLdxjgEYBlrulEbAqpxClSylxbqvUh+uElgV0BEjLauieOFQsgjj0h9S2bg93dFwEVVvo34J
0kphD0ef31QGElPycKlv3C4odqzlMmZL3DJizpy39Jg/d7Ow4iIjUeXCFThWFtl4bdlMV/r8QSCg
k2RgFne8FUWEiOZ9uTsTLy6BgRVA6IobN00dSR0pOw1VfO2jTOyqsaDeidbVVfLD5H6TPfCPIGga
D4bqU9T1fVwHYWlAlANffvX/JYQSi/+AAH31xGCC+ADXBFx8ZMoTFgzCAiVNcBZTFKWo9I8YpWSS
2R8OMOCTf7QBdxiIIh6w1DqqoTgigDCaABJJkgSm1FKE+bCNKn/I9AQ3ISES2UDndcSNF4T8sgdB
EHn1jUDH0YdeFqH19Y05VKKRT4xcpiBAkBfY0osum4iZgS1gWvDlBqqcxWCaIaw5AZmxwdnlnSUw
QNBoL5xwmW0ntMSQYXgWWqgBPz45UgmBLWoCF+HYaeik1CE62hRGbFPAlifAIimloBIlwBmYIYUE
qYyFquqqG4w6Gm9JZPkpq7Sa1hsHl7w6ChI/Elrrr9RRQhcG6Lw6a57f7ArssnlRwg3/icViht8b
fzJrbbOBOTPnnpj1CUdgVFwrLjPOohGupZix14gcBo3r7iPl/nRHoqE56oaN7+Z7SLnRuJpuuI1s
I6++BCuhKQK6kPqkso38SGLB7tYi8cQUV2xxrmiE8uoDFnfs8ccga/olyCSXbPLJKKes8sTdmHYs
rqONNmxCe/oKcQruVZeHdDz37HMPgcWM1M9EF2200d8AcPTSTDft9NNQO51zpTxETQS3ulqtNdF7
Lrf112CHHfbULlcNwNlop6122vSmO4gZZpSz9tx012132oFldffefPft99+AB4721S2XtrMAggcd
8+LsCe442go/LvnklFe+NuH/HS64/8ZoLH6p5YBnCzroJBT+gT+pnn425jqb7bgDZZSREtxvpzN6
34nCfjvl86TsnsoEnd07ysErjbjpeGmOtgMKNO9887ovr8Duo4tO/eTzPP279qhnLzXqrFN99dkO
PDDA+eifP33a5l9v+ZXuS+5909t/L7wt9htPtuGuA5D+/+drANoacL74TY5UjTOg4ObHtPp5LlnF
KR4Dl1a88JVtfP5DH/PKoQAHNECAACBgA6JXOQxSLjIKdNwEj+bAB4Ihgt3DHxG4wTMawnB1x8tc
/wbQgOaprYcdJGB8bmdCyUUuhQuUYQO1gL8X+syJx7ufdCAoshvqD3lFUV4IR8g2Bf+MMAEKUJ8P
0yYdHEZwcGU0XhEdlzckJpF73oNiDcsYwxrSkIqEw+H+8qJFADwAhGcLo+7C6MUCknF8GEQk4vSo
P8rlzo2BW6HRHEg0KEpQiTPETM8qmMPWrRFtYRxAIEc4gOaJ8pBoTGUjG/nJwFkPkn+TZNEo+TNL
1rFneLSiBfnXSj+WMpA89GIP1ZbIRbLSmIrcHNvgB8tYYpKFTJxhJekoRTvmMopX1GErRXi2Dwbw
AX8kJjLHychjAm52CURgMwEnS65FkwvTtOIEk5VLTu4xef37IQ+7mT7mnVKVq0wmI3tJt0ShDYXr
9Fs7f0bLJ1KTRVO0YRXzmE1PGlP/bfvkJ/qaB8hyqtGEPEPl3+CnzoQqVIae2+Q75TjFhzJQopl8
6C75mE/yBXCAAnTATU1KvtCcDaE83dv8UhrSlbrQpc+cJPg6Kb6L2vQB67tRIDsYVKX49JFVvdtC
fVY/+t3Sq3rEIlH6iLYHZPVuP2JPG89qt62q1K1FrSZYK9pUtgIOgVidnV3TRgDBacGvwgMsXS/o
1L3ajVRm8KlSsqEiw2LNhZCNLJ8eK9mkDZaXhXXs3BBI0mzpTbOgndtM8UnQ0GbLp9VoBwlDy9rL
0lRssH2awo7EORXF9ra4zS1DxbqQw+n2t8WZbTuO9FHgGve4ULtnFquG3Nwq7klD/2uudKc7S94q
xLfUXRrJ+PUkpa3su+ANr3jHS97yUoyJzM3u0Wb1XKRw6mYF+1161Vs07PaMXZFZAX33y9/+0nEe
8/WvdOzLM/ymQcAITrB05atgnh0uABCOcIS/IeEKW/jCGM6whjfM4Q57+MMgDrGIR1xhzBE4wQ/G
cAFIzOIWu/jFMI6xjCNs4gCjuGozzrGOdwzi0pUOwj8OQI0bPGAc8/jISEby8E72O9+tOABLNhlB
IDxkIhMhxRBegJa3vOULLyDJYA5zheH636RWF8hmdieVc3hiBGM5AAsA4Pm+HGEtD0DMeAYzmWG4
Z8KhmXtrZrCV10SECMs5fQ2IMP8B7xxjCfDY0XnOcJ/ZnMkH0vHP3ws0egdNaAEYGn1ctnOiAyBC
C0NaxKfOcaojPeY07zaOR4UhpmMa0UsLmc02drORA8BDLVe4Ab4moK/HTAASr1rGx2b1rJcYx3j6
GcpKpCIep3xrQVsZyx+kc52BDec5DxvIEwB3uMU9bigX29QUALeEIV2BCCdb2ZNuKC5tPc87wvR4
mgYwp9+8gFFnmdHd7vf5iK3ugo+b3eded8IdnWqGL/zc72Z1vFfqbHxDG5eaLGq+2yzgN1c4zozu
N6/tTHBzuxviDy+4wk9ucJSz3OTKNrWruUrxWtI7qde0eJWvvWsLx5nOIO83t1f/DnOYnxrh6G63
0VGu9IhHeuLNtrmsL27Ne+sc1/vuuYRLTWr0AVvkRD+6y1uObgynW+VEj/m6Z/7WJlac2vUGQz2f
vHMie1zRPITwor0NcLK3fOzHFvvJBe93tbub7UWNukOn/lKJTpvuWB/03SGcd72nT8v+frnSzX12
zp9982j3fMoNf/jiELXM0pT6sxtvR1vXvcGTD6Chvx5AbX/Y6aTXM0oX1/ZKn97iE994rjuu9YB/
PMu273HCcy9xxKM+01T3qvCzXmifJx/GuGf+kaHufMZ3/9mvV/DktU/+Rvu1r4F7MvoBB/nfhXb8
5Y8/iytLf8lCuP6jyTf+98///9HAX/4AGIAyNlqEJYAGeIADyFQAwnGc1oAOuDXKhVkPOIEUaDUR
+FoVmIEaCE1cwoAb+IEUeIGkBYIk+IEiuFwlmIIZeIJjNXwq+IIJxoK95YIwWIP8JYPXRYM2uIPU
hYMJ4YE8GITI5YPMAIRCeIS6RYTLYIRI2ISwpYTKwIROOIUQaF0oSIVYmFtQ+AhSmIVeSEFW2IJf
OIZgs4WO0IVkmIb/FSNoqIZqaIaN0IZuSIZwyAhyOIdfWIeHcId4mIV6CAd82IdU+IdvEIiC6ISE
6AaGeIhImIhtsIiMKISOOAaQGIk8OIlKUImWaIOYGCs6uIle2IlIoImg+IKieGcEpFiKKXiKRpCK
qkiCrPgDrviKJhiGM0iLcxiLKTCLuLiCtpiDvfiGv/iDnxiMkjiMRViMxniJyLiEyriMnNiMUfiM
0AiDuogCLtBa2riNkyONj9B/4BiO4jiO5FiO5giO8JWOBBMBADs=

------=_NextPart_000_0000_01C18FBD.49EC5320--



From aleaxit@yahoo.com  Fri Dec 28 11:20:10 2001
From: aleaxit@yahoo.com (Alex Martelli)
Date: Fri, 28 Dec 2001 12:20:10 +0100
Subject: [Tutor] Re: [Python-Help] Re...From PRJoshi
References: <MABBICBJKOGBBPCNIOOBIEKJCCAA.prjoshi@ntc.net.np>
Message-ID: <00be01c18f91$9dae24b0$102b2bc1@cadlab.it>

"Pravin Raj Joshi" <prjoshi@ntc.net.np> writes:
    ...
> What I want to do is change the icon of my windows. (I have inserted a
photo
> of what I want to do!)
    ...
> Basically I want to change the TK icon with something else. I read
somewhere
> it was not possible to change that for the root, but it was possible for
the
> toplevel.
>
> How to change that?

I think that, like all toplevel window-decoration issues, this too depends
on "negotiating" with the specific window-manager in use.  And I don't know
how this can be done from within Tkinter for Microsoft Windows in
particular,
or even if there is ANY way (without resorting to very low level, Windows
specific programming).

Perhaps posting to the general Python list, by letting many more people
see your question, might help you get a response.  Attachments are not
allowed.  Be specific about what window managers and system configurations
you need to support -- it probably does make a difference.


Alex




From alan.gauld@bt.com  Fri Dec 28 15:50:05 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 28 Dec 2001 15:50:05 -0000
Subject: [Tutor] module objects
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C214@mbtlipnt02.btlabs.bt.co.uk>

> i remember reading that a module in python is also an object.

Almost everything in Python is an object - especially in V2.2!

[ But note that an object is not necessarily the same thing 
  as an instance of a class ]

> so if i define a file test.py , i have a test module object.

Correct.

> i observed that sys.modules is a dict containing many modules.

It contains the list of modules currently imported.

> if i add my module also to this dictionary what can i achieve?

Not a lot! Python uses that list, its not really for programmers 
to mess with unless you really know what you're doing - and even 
then you probably shouldn't!

You should only add to the list by importing your module as in:

import test

> that what can i do with it? some examples w'd help.

You can do spome freaky things to python's internal 
operations, but you probably shouldn't...

> import test
> import sys
> sys.modules['test'] = test

Is redundant since the import already did that for you.

Alan g.


From karshi.hasanov@utoronto.ca  Fri Dec 28 16:08:06 2001
From: karshi.hasanov@utoronto.ca (Karshi)
Date: Fri, 28 Dec 2001 11:08:06 -0500
Subject: [Tutor] Python_debug_lib?
Message-ID: <20011228160921Z238885-4365+3@bureau6.utcc.utoronto.ca>

Hi all,

 How do find out what's python's debug library( python22_d or 
python_22_d.lib?)
For example, if I have Python2.2 installed on Wondows2000 and the
programm I am using asks for the python debug library . Where do I get it?
Thanks


From jeff@ccvcorp.com  Fri Dec 28 17:57:23 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri, 28 Dec 2001 09:57:23 -0800
Subject: [Tutor] ok, I want to read a dir.
References: <E16Jyra-0004Mq-00@mail.python.org>
Message-ID: <3C2CB282.FD1F9490@ccvcorp.com>

> Kirk Bailey <deliberatus@my995internet.com> wrote:
>
>         print "<a href= \"" + webpath + "cgi-bin/commander.py?list=" + x
> +  "\">" + x + "</a> ", descriptor(x) +'<P>'
> #which means:
> #      print 'a
> href="http://www.howlermonkey.net/cgi-bin/commander.py?list=(listname)">
> (description)<p>'

Do yourself (and us! ;) ) a favor, and learn to use string formatting.  Adding strings
together like you do above, is both slow and error-prone.  It hurts my head just looking
at that line and trying to figure out which parts are string and which parts are
variable and which quotation marks go with which chunks and.....  :)

If you use string formatting instead, that line becomes:

print '<a href="%scgi=bin/commander.py?list=%s">%s</a>%s<p>' %
            (webpath, x, x, descriptor(x))

Every place in the main string that you see a %s, Python will replace that with the
string value of the corresponding variable from the final tuple.  This has several
advantages over the multiple-concatenation that you were doing.  For one, it's a *lot*
cleaner and easier to read.  And it's much faster and more efficient--it creates a
single new string object, and all the substitution is done in C code in the
interpreter.  Your example creates almost a dozen new string objects, only to throw them
away almost immediately, not to mention setup and type checks and such that have to be
done with each and every addition...

If you are doing *any* work with text or strings, then the string-formatting operator is
your friend.  Learn to know it well, and it will help you immensely.  :)

Jeff Shannon
Technician/Programmer
Credit International





From jimajima9@yahoo.com  Fri Dec 28 21:45:46 2001
From: jimajima9@yahoo.com (Jim Angstadt)
Date: Fri, 28 Dec 2001 13:45:46 -0800 (PST)
Subject: [Tutor] Multi-line statements with comments
Message-ID: <20011228214546.52772.qmail@web14008.mail.yahoo.com>

Hi all,

situation = [ 'win98se', 'python 2.1.1', 
'very newbie user' ]

An earlier thread pointed out to me the value of the
string formatting operator. That was very helpful.  It
used this statement:

   print '<a
href="%scgi=bin/commander.py?list=%s">%s</a>%s<p>' %
            (webpath, x, x, descriptor(x))

[Somehow the continuation character, '\', was dropped.

 Maybe by my mail program.]

However, the use of the continuation character does
not permit one to have comments within the string.  In
regular expressions, there is a way to disreguard
whitespace within the RE, and add comments, which
makes a lengthy expression more readable.  ( I'm
referring to VERBOSE in python or x in perl. )

What is a good technique for commenting multi-line
statements that are not REs?

---
Jim


__________________________________________________
Do You Yahoo!?
Send your FREE holiday greetings online!
http://greetings.yahoo.com


From deliberatus@my995internet.com  Fri Dec 28 22:16:14 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Fri, 28 Dec 2001 17:16:14 -0500
Subject: [Tutor] ok, got a primitive but workable solution
Message-ID: <3C2CEF2E.C9FF437F@my995internet.com>

I wanted to trim a statement down to give me ONLY the name of the list.
I got it.

Probably not the best solution, but it works, and works in python 1.5.2
which is what is in my server.

 'list' is a string, such as: './lists/testlist3.info'

I want to extract the pure list name so I can display ONLY that. This
works.

def getname(list):
	a=string.split(list,'/')
	b=a[2]
	c=string.split(b,'.')
	return c[0]

>>> a
['.', 'lists', 'mylist.info']
>>> list
'./lists/mylist.info'
>>> string.split(list)
['./lists/mylist.info']
>>> string.split(list,'/')
['.', 'lists', 'mylist.info']
>>> def getname:
	
SyntaxError: invalid syntax
>>> def getname(list):
	a=string.split(list,'/')
	b=a[2]
	c=string.split(b,'.')
	return c[0]

>>> list
'./lists/mylist.info'
>>> getname(list)
'mylist'
>>> 



-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From arcege@speakeasy.net  Fri Dec 28 22:51:44 2001
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Fri, 28 Dec 2001 17:51:44 -0500
Subject: [Tutor] Multi-line statements with comments
In-Reply-To: <20011228214546.52772.qmail@web14008.mail.yahoo.com>; from jimajima9@yahoo.com on Fri, Dec 28, 2001 at 01:45:46PM -0800
References: <20011228214546.52772.qmail@web14008.mail.yahoo.com>
Message-ID: <20011228175144.B919@speakeasy.net>

On Fri, Dec 28, 2001 at 01:45:46PM -0800, Jim Angstadt wrote:
> Hi all,
> 
> situation = [ 'win98se', 'python 2.1.1', 
> 'very newbie user' ]
> 
> An earlier thread pointed out to me the value of the
> string formatting operator. That was very helpful.  It
> used this statement:
> 
>    print '<a
> href="%scgi=bin/commander.py?list=%s">%s</a>%s<p>' %
>             (webpath, x, x, descriptor(x))
> 
> [Somehow the continuation character, '\', was dropped.
> 
>  Maybe by my mail program.]
> 
> However, the use of the continuation character does
> not permit one to have comments within the string.  In
> regular expressions, there is a way to disreguard
> whitespace within the RE, and add comments, which
> makes a lengthy expression more readable.  ( I'm
> referring to VERBOSE in python or x in perl. )
> 
> What is a good technique for commenting multi-line
> statements that are not REs?

Line continuation cannot be used because the newline after it is, in
essence, being quoted by the backslash ('\').

But parentheses can be used to do this too.  But do not compare what
new forms of regular expressions do with what a computer language does.
The RE takes a single string and parses it internally.  Python won't
let you do the same within a string.

print (   # let's get busy
  '<a href="%scgi-bin/commander.py?list=%s">%s</a>%s<p>' # base format
  % (webpath, x, x, descriptor(x))  # rest of expression
)

But there IS a neat thing you can do with strings:

message = ('hi there\n'     # notice no operator to join the strings
           'how are you?\n' # no comma, no plus
           'have a good day'# just the comment afterward
          )    # but we use the parentheses to get the multi-line
print message

This makes an expression with only one value, no operators.
Syntactically, this is equivalent to:

message = 'hi there\nhow are you\nhave a good day'
print message

Enjoy.

  -Arcege



From shalehperry@attbi.com  Fri Dec 28 22:58:26 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 28 Dec 2001 14:58:26 -0800 (PST)
Subject: [Tutor] ok, got a primitive but workable solution
In-Reply-To: <3C2CEF2E.C9FF437F@my995internet.com>
Message-ID: <XFMail.20011228145826.shalehperry@attbi.com>

On 28-Dec-2001 Kirk Bailey wrote:
> I wanted to trim a statement down to give me ONLY the name of the list.
> I got it.
> 
> Probably not the best solution, but it works, and works in python 1.5.2
> which is what is in my server.
> 
>  'list' is a string, such as: './lists/testlist3.info'
> 
> I want to extract the pure list name so I can display ONLY that. This
> works.
> 
> def getname(list):
>       a=string.split(list,'/')
>       b=a[2]
>       c=string.split(b,'.')
>       return c[0]
> 

apparently you missed my mail.

def getname(thing): # list is A BAD NAME TO USE
    import os.path
    name = os.path.basename(thing)
    name, ext = os.path.splitext(name)
    return name


From deliberatus@my995internet.com  Sat Dec 29 00:17:05 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Fri, 28 Dec 2001 19:17:05 -0500
Subject: [Tutor] ok, got a primitive but workable solution
References: <XFMail.20011228145826.shalehperry@attbi.com>
Message-ID: <3C2D0B81.975675B@my995internet.com>

ok, got it working right- assuming my primitive understanding of cgi is
'right'.

Take a look.

outputted page:
http://www.howlermonkey.net/cgi-bin/TLwebmgr.py

Sourcecode:
http://sss.howlermonkey.net/TLwebmgr.shtml


This is the master page, the one listing all lists ( which have a info
file, nudge nudge, wink wink)
hosted on the service. It reads the first line of the (listname).info
file, which is to be a 1 line
description of the list. To read the FULL description (and access the
form to subscribe or unsubscribe) they
are to click a list name, and this sends in a command request to
TLcommander.py which reads the information
from the request using GET. IT's not a lot of info, so get is sufficent
for this.

This works, and it works in 1.5.2 python, so is downward compatible from
the latest version, which is cool, as there many still using, even STUCK
using, 1.5.foo!


Sean 'Shaleh' Perry wrote:
> 
> On 28-Dec-2001 Kirk Bailey wrote:
> > I wanted to trim a statement down to give me ONLY the name of the list.
> > I got it.
> >
> > Probably not the best solution, but it works, and works in python 1.5.2
> > which is what is in my server.
> >
> >  'list' is a string, such as: './lists/testlist3.info'
> >
> > I want to extract the pure list name so I can display ONLY that. This
> > works.
> >
> > def getname(list):
> >       a=string.split(list,'/')
> >       b=a[2]
> >       c=string.split(b,'.')
> >       return c[0]
> >
> 
> apparently you missed my mail.
> 
> def getname(thing): # list is A BAD NAME TO USE
>     import os.path
>     name = os.path.basename(thing)
>     name, ext = os.path.splitext(name)
>     return name
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From eskimopauk@hotmail.com  Sat Dec 29 00:54:53 2001
From: eskimopauk@hotmail.com (jonathan charlie)
Date: Fri, 28 Dec 2001 15:54:53 -0900
Subject: [Tutor] remove me
Message-ID: <OE15ct2n7kt6lhmhfE70000a4cc@hotmail.com>

------=_NextPart_001_0001_01C18FB7.FD184D60
Content-Type: text/plain; charset="iso-8859-1"

Get more from the Web.  FREE MSN Explorer download : http://explorer.msn.com
------=_NextPart_001_0001_01C18FB7.FD184D60
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<HTML><BODY STYLE=3D"font:10pt verdana; border:none;"><DIV><BR><BR></DIV>=
</BODY></HTML><br clear=3Dall><hr>Get more from the Web.  FREE MSN Explor=
er download : <a href=3D'http://explorer.msn.com'>http://explorer.msn.com=
</a><br></p>

------=_NextPart_001_0001_01C18FB7.FD184D60--


From dyoo@hkn.eecs.berkeley.edu  Sat Dec 29 01:28:00 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 28 Dec 2001 17:28:00 -0800 (PST)
Subject: [Tutor] remove me
In-Reply-To: <OE15ct2n7kt6lhmhfE70000a4cc@hotmail.com>
Message-ID: <Pine.LNX.4.21.0112281726210.2216-100000@hkn.eecs.berkeley.edu>

Hi Jonathan,

It sounds like you're trying to unsubscribe from Tutor.  If so, you can
unsubscribe yourself by visiting the web page you used to subscribe to
Tutor:

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

If you do down to the bottom of the page, you'll see an "Edit Options"
form.  From there, you should be able to edit your own options, and
unsubscribe.

Best of wishes to you.



From shalehperry@attbi.com  Sat Dec 29 01:30:09 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 28 Dec 2001 17:30:09 -0800 (PST)
Subject: [Tutor] ok, got a primitive but workable solution
In-Reply-To: <3C2D0B81.975675B@my995internet.com>
Message-ID: <XFMail.20011228173009.shalehperry@attbi.com>

> 
> This works, and it works in 1.5.2 python, so is downward compatible from
> the latest version, which is cool, as there many still using, even STUCK
> using, 1.5.foo!
> 

unless i really need something spiffy, I write all of my code in 1.5 style.


From prjoshi@ntc.net.np  Sat Dec 29 01:35:35 2001
From: prjoshi@ntc.net.np (Pravin Raj Joshi)
Date: Sat, 29 Dec 2001 07:05:35 +0530
Subject: [Tutor] RE...Quest from PRJoshi
Message-ID: <MABBICBJKOGBBPCNIOOBMEKKCCAA.prjoshi@ntc.net.np>

Hi,
Here is a small problem again.
I have two classes. Below are the codes and the file names.

#---------------------------------------------------------
trailabout.py
#---------------------------------------------------------
from Tkinter import *

class abouttrail:
    def __init__(self,root=None):
        self.frame = frame = Frame(root)
        self.button = button = Button(frame,text="Press")
        frame.pack()
        button.pack()

def trail():
    root = Tk()
    mainwin = abouttrail(root=root)
    root.mainloop()

if __name__ == '__main__':
    trail()


#-------------------------------------------------------
test.py
#-------------------------------------------------------
from Tkinter import *
from trailabout import abouttrail

root = Tk()
mainwin = abouttrail(root=root)
root.mainloop()
-------------------------------------------------------

I have both the files in the following path: c:\python\nepali_converter\
When I compile them from outside Idle (using command-line interpreter) they
work perfect, but from inside Idle here is the message I get and the program
fails. I am using the one that comes with Python 2.2.

#------------------------------------------------------
>>>
Traceback (most recent call last):
  File "C:\Python\nepali_converter\test.py", line 2, in ?
    from trailabout import abouttrail
ImportError: No module named trailabout
#------------------------------------------------------

Could anyone let me know what is wrong.

Thanks.

PRJoshi



From dyoo@hkn.eecs.berkeley.edu  Sat Dec 29 01:41:44 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 28 Dec 2001 17:41:44 -0800 (PST)
Subject: [Tutor] Multi-line statements with comments
In-Reply-To: <20011228214546.52772.qmail@web14008.mail.yahoo.com>
Message-ID: <Pine.LNX.4.21.0112281731520.2216-100000@hkn.eecs.berkeley.edu>

On Fri, 28 Dec 2001, Jim Angstadt wrote:


> However, the use of the continuation character does not permit one to
> have comments within the string.  In regular expressions, there is a
> way to disreguard whitespace within the RE, and add comments, which
> makes a lengthy expression more readable.  ( I'm referring to VERBOSE
> in python or x in perl. )
> 
> What is a good technique for commenting multi-line statements that are
> not REs?


We can cook up a simple function that allows us to do something like this:

###
comment_re = re.compile(r'#[^\n]*?\n')

def removeComments(s):
    return comment_re.sub('\n', s)    
###


Here's an example of how to use this function:

###
>>> removeComments('''this is # a test
... hello world ## foo!
... ''')
'this is \012hello world \012'
###



However, there's one big deficiency in the regular expression as it
stands: what happens if we give it soething like this?

###
s = removeComments("hello # why doesn't this comment disappear?")
print s
###


So there's definitely room to improve this.


Hope this helps!



From deliberatus@my995internet.com  Sat Dec 29 02:40:14 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Fri, 28 Dec 2001 21:40:14 -0500
Subject: [Tutor] environment data
Message-ID: <3C2D2D0E.F83F894F@my995internet.com>

ok, I want to read a environment variable in a script. 
This contains 'everything after the first "?" in the url' according to
my reading.
My application will have 1 word there.
The url is
http://www.howlermonkey.net/cgi-bin/commander.py?(listname)
where (listname) is replaced by a 1 word string, the name of the list of
intrest.

cgi module leaves me baffled, but if I can just read the bloddy
environment variable I can run with it from there.

How I do that?

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From shalehperry@attbi.com  Sat Dec 29 02:50:35 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 28 Dec 2001 18:50:35 -0800 (PST)
Subject: [Tutor] environment data
In-Reply-To: <3C2D2D0E.F83F894F@my995internet.com>
Message-ID: <XFMail.20011228185035.shalehperry@attbi.com>

On 29-Dec-2001 Kirk Bailey wrote:
> ok, I want to read a environment variable in a script. 
> This contains 'everything after the first "?" in the url' according to
> my reading.
> My application will have 1 word there.
> The url is
> http://www.howlermonkey.net/cgi-bin/commander.py?(listname)
> where (listname) is replaced by a 1 word string, the name of the list of
> intrest.
> 
> cgi module leaves me baffled, but if I can just read the bloddy
> environment variable I can run with it from there.
> 

import os.environ

print os.environ['MY_DATA']

The cgi module for python passes os.environ as a parameter:

environ = os.environ

environ['REQUEST_METHOD']

cgi.py is a lot like rfc822, it parses headers and other data storing them in a
dictionary and giving you access to them as if the returned item was a
dictionary itself.


From kojo@hal-pc.org  Sat Dec 29 04:44:25 2001
From: kojo@hal-pc.org (Kojo Idrissa)
Date: Fri, 28 Dec 2001 22:44:25 -0600
Subject: [Tutor] Building Python Source with Cygwin?
Message-ID: <5.1.0.14.0.20011228224026.00afe508@Pop3.norton.antivirus>

I know this is sort of off-topic, but I figured someone here might know.

I recently installed a lot of the Cygwin stuff on my machine (GCC, etc...).

Can I take the Python source from any of my Linux CD's and build it for 
Win2K with Cygwin?  I'm pretty sure source is source, but I'm just 
wondering if I can now take any related source (SWIG, Jython, etc...) from 
anywhere and build it on my Win2K box or partition.  That would be 
helpful.  God knows I've got plenty of source CDs floating around...

Just wondering,

****************************
Kojo Idrissa

kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
****************************



From grimmtoothtoo@yahoo.com  Sat Dec 29 05:46:22 2001
From: grimmtoothtoo@yahoo.com (Grimmtooth)
Date: Sat, 29 Dec 2001 00:46:22 -0500
Subject: [Tutor] Building Python Source with Cygwin?
In-Reply-To: <5.1.0.14.0.20011228224026.00afe508@Pop3.norton.antivirus>
Message-ID: <NLEIJCOLEACIANLABPOECEDNCDAA.grimmtoothtoo@yahoo.com>


> I know this is sort of off-topic, but I figured someone here might know.
>
> I recently installed a lot of the Cygwin stuff on my machine
> (GCC, etc...).
>
> Can I take the Python source from any of my Linux CD's and build it for
> Win2K with Cygwin?  I'm pretty sure source is source, but I'm just

Unless you're doing it for jollies, there's already a Python.exe included
with CygWin. But as I understand it, you can compile the *nix source with
little or no modification.


_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com



From dyoo@hkn.eecs.berkeley.edu  Sat Dec 29 06:45:02 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 28 Dec 2001 22:45:02 -0800 (PST)
Subject: [Tutor] environment data   [CGI]
In-Reply-To: <XFMail.20011228185035.shalehperry@attbi.com>
Message-ID: <Pine.LNX.4.21.0112282227200.4617-100000@hkn.eecs.berkeley.edu>

On Fri, 28 Dec 2001, Sean 'Shaleh' Perry wrote:

> > cgi module leaves me baffled, but if I can just read the bloddy
> > environment variable I can run with it from there.
> > 
> 
> import os.environ
> 
> print os.environ['MY_DATA']
> 
> The cgi module for python passes os.environ as a parameter:
> 
> environ = os.environ
> 
> environ['REQUEST_METHOD']
> 
> cgi.py is a lot like rfc822, it parses headers and other data storing
> them in a dictionary and giving you access to them as if the returned
> item was a dictionary itself.


The documentation hides a nice example of the cgi module in action here:

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

###
form = cgi.FieldStorage()
if not (form.has_key("name") and form.has_key("addr")):
    print "<H1>Error</H1>"
    print "Please fill in the name and addr fields."
    return
print "<p>name:", form["name"].value
print "<p>addr:", form["addr"].value
###

So cgi.FieldStorage() almost behaves like a dictionary, with the exception
that to get at the actual value, we need to do something like
'form[key].value' instead of just 'form[key]'.  Why?

There are good reasons for this: forms can have more than strings!  Their
values can be uploaded files as well, and the bottom of the link:

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

talks about this in more detail.  That's one big reason why
cgi.FieldStorage() is a little more awkward to use than a dictionary.


Also, there's a lot of resources you can look at for more CGI examples.  
Here are two that may interest you:

    http://python.org/topics/web/basic-cgi.html
    http://www.devshed.com/Server_Side/Python/CGI/page1.html


The devshed.com article is especially good, as it has a lot of examples
with commentary.



From dyoo@hkn.eecs.berkeley.edu  Sat Dec 29 06:52:38 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 28 Dec 2001 22:52:38 -0800 (PST)
Subject: [Tutor] Building Python Source with Cygwin?
In-Reply-To: <5.1.0.14.0.20011228224026.00afe508@Pop3.norton.antivirus>
Message-ID: <Pine.LNX.4.21.0112282245400.4617-100000@hkn.eecs.berkeley.edu>

On Fri, 28 Dec 2001, Kojo Idrissa wrote:

> I know this is sort of off-topic, but I figured someone here might know.
> 
> I recently installed a lot of the Cygwin stuff on my machine (GCC, etc...).
> 
> Can I take the Python source from any of my Linux CD's and build it
> for Win2K with Cygwin?  I'm pretty sure source is source, but I'm just
> wondering if I can now take any related source (SWIG, Jython, etc...)
> from anywhere and build it on my Win2K box or partition.

Yes, this should work, as there is one unified source code distribution
(the .tgz file) available on Python.org for each version release.


However, before doing anything, you'll really want to look at the README
file that's in the root of the source code distribution --- it talks a lot
about compilation issues that you might want to look at before tearing
your hair out in frustration.  *grin*

I've heard that a lot of compilation issues have been resolved in the more
recent Python releases, so you might want to try Python 2.1 or 2.2 in
preference over older releases.  If you have compilation problems, you can
ask questions on comp.lang.python --- the Visual C++ wizards on the
newsgroup can help you.

Good luck to you!



From urnerk@qwest.net  Sat Dec 29 15:42:05 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 29 Dec 2001 07:42:05 -0800
Subject: [Tutor] Multi-line statements with comments
In-Reply-To: <Pine.LNX.4.21.0112281731520.2216-100000@hkn.eecs.berkeley.edu>
Message-ID: <000201c1907f$628193b0$c03b0404@JACK>


Kirby Urner, 4D Solutions
 

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org] On Behalf
Of Danny Yoo
Sent: Friday, December 28, 2001 5:42 PM
To: Jim Angstadt
Cc: tutor@python.org
Subject: Re: [Tutor] Multi-line statements with comments

On Fri, 28 Dec 2001, Jim Angstadt wrote:


> However, the use of the continuation character does not permit one to
> have comments within the string.  In regular expressions, there is a
> way to disreguard whitespace within the RE, and add comments, which
> makes a lengthy expression more readable.  ( I'm referring to VERBOSE
> in python or x in perl. )
> 
> What is a good technique for commenting multi-line statements that are
> not REs?

Note:  you can also have comments in multi-lines where the goal is to 
define a sequence or mapping.

 >>> j = [
	1,2, # this is a
	3,4  # list
	]
 >>> j
 [1, 2, 3, 4]

So if you have your heart set on commenting each line of a string, 
spread across multiple lines, you could do something like:

 >>> mylist = ["here we",            # beginning of string
               " are testing",       # middle of string
               " a way to comment",  # etc.
	         " string formations"  # finis
	        ]

then join it all together at the end (comments automagically gone):
 
>>> thestring = ''.join(mylist)
>>> thestring
'here we are testing a way to comment string formations'


Kirby





From urnerk@qwest.net  Sat Dec 29 15:51:50 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 29 Dec 2001 07:51:50 -0800
Subject: [Tutor] Multi-line statements with comments
In-Reply-To: <000201c1907f$628193b0$c03b0404@JACK>
Message-ID: <000301c19080$beb151b0$c03b0404@JACK>


I just realized that, even simpler than joining a string split 
into a list of substrings, in order to comment each part,
is to take advantage of the syntax which concatenates 
strings if they simply appear in sequence e.g. 
"hello " "world" becomes "hello world".  

Combine this feature with the grouping characters (  ), which 
give you multilines without use of \, and you've got a way to 
comment a multi-line string sans use of join():

 >>> mystr  =  ("the"      # another way to comment
                " "        # a multiline string
                "end")     # check it out!
 >>> mystr
 'the end'

Kirby





From urnerk@qwest.net  Sat Dec 29 16:26:09 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 29 Dec 2001 08:26:09 -0800
Subject: [Tutor] Multi-line statements with comments
In-Reply-To: <000301c19080$beb151b0$c03b0404@JACK>
Message-ID: <000101c19085$8a32a6f0$c03b0404@JACK>

 >>> mystr  =  ("the"      # another way to comment
                " "        # a multiline string
                "end")     # check it out!
 >>> mystr
 'the end'

However, the above "discovery" is exactly what the 
docs suggest for defining a regular expression across
multi-lines -- something I thought was acknowledged
at the top of this thread (not sure):

  re.compile("[A-Za-z_]"       # letter or underscore
             "[A-Za-z0-9_]*"   # letter, digit or underscore
             )

So I haven't added anything new here.  Oh well.

Kirby





From glingl@aon.at  Sat Dec 29 14:53:15 2001
From: glingl@aon.at (Gregor Lingl)
Date: Sat, 29 Dec 2001 15:53:15 +0100
Subject: [Tutor] Multi-line statements with comments
References: <Pine.LNX.4.21.0112281731520.2216-100000@hkn.eecs.berkeley.edu>
Message-ID: <003201c19078$8c1339b0$1664a8c0@mega>

...
> 
> def removeComments(s):
>     return comment_re.sub('\n', s)    
> ###
> 

...

> 
> However, there's one big deficiency in the regular expression as it
> stands: what happens if we give it soething like this?
> 
> ###
> s = removeComments("hello # why doesn't this comment disappear?")
> print s
> ###
> 
> 
> So there's definitely room to improve this.
> 

Would you consider this to be an appropriate
proposition:

def removeComments(s):
        return comment_re.sub('\n', s+'\n')[:-1]

?

Gregor 



From bwinton@tor.dhs.org  Sat Dec 29 15:05:10 2001
From: bwinton@tor.dhs.org (Blake Winton)
Date: Sat, 29 Dec 2001 10:05:10 -0500
Subject: [Tutor] environment data   [CGI]
In-Reply-To: <Pine.LNX.4.21.0112282227200.4617-100000@hkn.eecs.berkeley.edu>
References: <XFMail.20011228185035.shalehperry@attbi.com> <Pine.LNX.4.21.0112282227200.4617-100000@hkn.eecs.berkeley.edu>
Message-ID: <20011229100510.A16533@tor.dhs.org>

* Danny Yoo <dyoo@hkn.eecs.berkeley.edu> [011229 01:48]:
> On Fri, 28 Dec 2001, Sean 'Shaleh' Perry wrote:
> > > cgi module leaves me baffled, but if I can just read the bloddy
> > > environment variable I can run with it from there.
> So cgi.FieldStorage() almost behaves like a dictionary, with the exception
> that to get at the actual value, we need to do something like
> 'form[key].value' instead of just 'form[key]'.  Why?

My question is why I can't get the "aaa" from the url
http://tor.dhs.org/cgi-bin/daily.py?aaa&name=Source
the "name=Source" comes through fine, but the aaa is lost.

Later,
Blake.
-- 
9:40pm up 52 days, 21:07, 2 users, load average: 0.02, 0.09, 0.07


From kojo@hal-pc.org  Sat Dec 29 15:14:00 2001
From: kojo@hal-pc.org (Kojo Idrissa)
Date: Sat, 29 Dec 2001 09:14:00 -0600
Subject: [Tutor] Building Python Source with Cygwin?
In-Reply-To: <NLEIJCOLEACIANLABPOECEDNCDAA.grimmtoothtoo@yahoo.com>
References: <5.1.0.14.0.20011228224026.00afe508@Pop3.norton.antivirus>
Message-ID: <5.1.0.14.0.20011229090550.00afeae8@Pop3.norton.antivirus>

At 12:46 AM 12/29/2001 -0500, "Grimmtooth" wrote:

>Unless you're doing it for jollies, there's already a Python.exe included
>with CygWin. But as I understand it, you can compile the *nix source with
>little or no modification.

Yeah, pretty much for jollies.  I've recently been playing with the "build 
your own binary with different options turned on " features of software (ie 
build Python 1.5.2 with thread support under Linux).  Just wondering if I'd 
be able to do the same type of stuff on my Win2K box/partition now that 
I've got the GNU development tools installed there.

Actually, it seems like this could be another selling point for Python (and 
most Free/Open software) to be used on Win32 platforms...the ability to get 
customized versions at no cost (free/cheap source with free/cheap 
development tools to build the source).  Not a new idea of course, but it's 
my first time playing with this stuff on my Win partition.

Anyway, enough with the Free Software discussion.  Back to Python.  Thanks 
for the response.  You too Danny.

****************************
Kojo Idrissa

kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
****************************



From pythontutor@venix.com  Sat Dec 29 18:50:35 2001
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat, 29 Dec 2001 13:50:35 -0500
Subject: [Tutor] environment data   [CGI]
References: <XFMail.20011228185035.shalehperry@attbi.com> <Pine.LNX.4.21.0112282227200.4617-100000@hkn.eecs.berkeley.edu> <20011229100510.A16533@tor.dhs.org>
Message-ID: <3C2E107B.5040604@venix.com>

try saying ...?aaa=1&name=Source

So far as I know, unset variables don't make it through to cgi scripts
(at least under apache).  Obviously, a lot of settings could affect this.

Blake Winton wrote:

> * Danny Yoo <dyoo@hkn.eecs.berkeley.edu> [011229 01:48]:
> 
>>On Fri, 28 Dec 2001, Sean 'Shaleh' Perry wrote:
>>
>>>>cgi module leaves me baffled, but if I can just read the bloddy
>>>>environment variable I can run with it from there.
>>>>
>>So cgi.FieldStorage() almost behaves like a dictionary, with the exception
>>that to get at the actual value, we need to do something like
>>'form[key].value' instead of just 'form[key]'.  Why?
>>
> 
> My question is why I can't get the "aaa" from the url
> http://tor.dhs.org/cgi-bin/daily.py?aaa&name=Source
> the "name=Source" comes through fine, but the aaa is lost.
> 
> Later,
> Blake.
> 


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

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



From jimajima9@yahoo.com  Sat Dec 29 19:53:12 2001
From: jimajima9@yahoo.com (Jim Angstadt)
Date: Sat, 29 Dec 2001 11:53:12 -0800 (PST)
Subject: [Tutor] Multi-line statements with comments
In-Reply-To: <000101c19085$8a32a6f0$c03b0404@JACK>
Message-ID: <20011229195312.11165.qmail@web14007.mail.yahoo.com>

Many thanks for all who responded to my question on
multi-line statements with comments.

Here's a summary of what I learned:

* pure string literal => use triple quotes.

If there are no operators or variables, just pure
text, then I'll use triple quotes.  I have not found
the need to comment my own comments.

* embedded operators and variables => use something
like the following:

# -----
print (                  # let's get busy
  # comments
  'noise %s noise %s noise\n' # base format
  # comments
  'pure text' operators variables \
   more operators, vars, string, etc \
   and the end of statement.
  # comments
  % ( x, y )      # rest of expression
  # comments
)
# -----

In other words, I'll use continuation characters to
keep my lines short, for readability.  Then comment
before and or after.

* functions to remove comments => not yet.

I tend to want to write code that is well-commented
and easy to read, with a minimum of abstraction.  For
now, another function seems a little to much, an
unnecessary amount of logic that others may not pick
up on.

It also may make my code harder to share, without some
cut and paste for readability.

Once again, I appreciate all the responses, thanks
very much.

---
Jim



__________________________________________________
Do You Yahoo!?
Send your FREE holiday greetings online!
http://greetings.yahoo.com


From dyoo@hkn.eecs.berkeley.edu  Sat Dec 29 20:03:27 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 29 Dec 2001 12:03:27 -0800 (PST)
Subject: [Tutor] RE...Quest from PRJoshi  [fixing IDLE]
In-Reply-To: <MABBICBJKOGBBPCNIOOBMEKKCCAA.prjoshi@ntc.net.np>
Message-ID: <Pine.LNX.4.21.0112291131160.13114-200000@hkn.eecs.berkeley.edu>

  This message is in MIME format.  The first part should be readable text,
  while the remaining parts are likely unreadable without MIME-aware tools.
  Send mail to mime@docserver.cac.washington.edu for more info.

--545280650-578560010-1009656207=:13114
Content-Type: TEXT/PLAIN; charset=US-ASCII

On Sat, 29 Dec 2001, Pravin Raj Joshi wrote:

> I have both the files in the following path:
> c:\python\nepali_converter\ When I compile them from outside Idle
> (using command-line interpreter) they work perfect, but from inside
> Idle here is the message I get and the program fails. I am using the
> one that comes with Python 2.2.
> 
> #------------------------------------------------------
> >>>
> Traceback (most recent call last):
>   File "C:\Python\nepali_converter\test.py", line 2, in ?
>     from trailabout import abouttrail
> ImportError: No module named trailabout


Ok, I just checked this out.  Nothing's wrong with your program.  
Instead, this feels like an IDLE bug to me.  Try "Import Module" instead
--- it's right next to the Run Script command in the window.  It appears
to behave more nicely.  I wonder why?  Let me check on this...


Hmmm...*shuffle shuffle* .... Ah!  The problem is that "Run Script" uses
Python's 'execfile()' function to run a script.  The bug is that IDLE
doesn't add "C:\Python\nepali_converter" to the sys.path directory list.
What this means is that when your file tries to import 'abouttrail', IDLE
has no clue where to find it.


IDLE is itself written in Python, so if we feel brave, we can fix this
problem if we're willing to look at the source.  The file
'ScriptBinding.py' within the IDLE directory has a function called
"run_script_event()" which does the work when we "Run Script".  Take a
look:

###
    def run_script_event(self, event):
        filename = self.getfilename()
        if not filename:
            return

        flist = self.editwin.flist
        shell = flist.open_shell()
        interp = shell.interp
        if (not sys.argv or
            os.path.basename(sys.argv[0]) != os.path.basename(filename)):
            # XXX Too often this discards arguments the user just set...
            sys.argv = [filename]
        interp.execfile(filename)
###


The important part is right at the bottom: it just calls execfile(), but
doesn't fix sys.path before doing this.  A possible fix for this would be
to forcefully set up sys.path to do the right thing:

###
   def run_script_event(self, event):
        filename = self.getfilename()
        if not filename:
            return

        flist = self.editwin.flist
        shell = flist.open_shell()
        interp = shell.interp
        if (not sys.argv or
            os.path.basename(sys.argv[0]) != os.path.basename(filename)):
            # XXX Too often this discards arguments the user just set...
            sys.argv = [filename]
        old_syspath = sys.path[:]
        sys.path.append(os.path.dirname(os.path.abspath(filename)))
        interp.execfile(filename)
        sys.path = old_syspath
###


and this appears to fix the problem.

I've attached the fixed ScriptBinding.py file to this message.  You can
copy this to "C:\Python2.2\Tools\idle" directory (but make a backup copy
of ScriptBinding.py just in case I messed up).  Afterwards, if you restart
IDLE, things should work.  I'll send this message also to the IDLE folks
too and see if they like this approach.


Good luck to you.

--545280650-578560010-1009656207=:13114
Content-Type: TEXT/PLAIN; charset=US-ASCII; name="ScriptBinding.py"
Content-Transfer-Encoding: BASE64
Content-ID: <Pine.LNX.4.21.0112291203270.13114@hkn.eecs.berkeley.edu>
Content-Description: 
Content-Disposition: attachment; filename="ScriptBinding.py"

IiIiRXh0ZW5zaW9uIHRvIGV4ZWN1dGUgY29kZSBvdXRzaWRlIHRoZSBQeXRo
b24gc2hlbGwgd2luZG93Lg0KDQpUaGlzIGFkZHMgdGhlIGZvbGxvd2luZyBj
b21tYW5kcyAodG8gdGhlIEVkaXQgbWVudSwgdW50aWwgdGhlcmUncyBhDQpz
ZXBhcmF0ZSBQeXRob24gbWVudSk6DQoNCi0gQ2hlY2sgbW9kdWxlIChBbHQt
RjUpIGRvZXMgYSBmdWxsIHN5bnRheCBjaGVjayBvZiB0aGUgY3VycmVudCBt
b2R1bGUuDQpJdCBhbHNvIHJ1bnMgdGhlIHRhYm5hbm55IHRvIGNhdGNoIGFu
eSBpbmNvbnNpc3RlbnQgdGFicy4NCg0KLSBJbXBvcnQgbW9kdWxlIChGNSkg
aXMgZXF1aXZhbGVudCB0byBlaXRoZXIgaW1wb3J0IG9yIHJlbG9hZCBvZiB0
aGUNCmN1cnJlbnQgbW9kdWxlLiAgVGhlIHdpbmRvdyBtdXN0IGhhdmUgYmVl
biBzYXZlZCBwcmV2aW91c2x5LiBUaGUNCm1vZHVsZSBpcyBhZGRlZCB0byBz
eXMubW9kdWxlcywgYW5kIGlzIGFsc28gYWRkZWQgdG8gdGhlIF9fbWFpbl9f
DQpuYW1lc3BhY2UuICBPdXRwdXQgZ29lcyB0byB0aGUgc2hlbGwgd2luZG93
Lg0KDQotIFJ1biBtb2R1bGUgKENvbnRyb2wtRjUpIGRvZXMgdGhlIHNhbWUg
YnV0IGV4ZWN1dGVzIHRoZSBtb2R1bGUncw0KY29kZSBpbiB0aGUgX19tYWlu
X18gbmFtZXNwYWNlLg0KDQoiIiINCg0KaW1wb3J0IHN5cw0KaW1wb3J0IG9z
DQppbXBvcnQgaW1wDQppbXBvcnQgdGtNZXNzYWdlQm94DQoNCmluZGVudF9t
ZXNzYWdlID0gIiIiRXJyb3I6IEluY29uc2lzdGVudCBpbmRlbnRhdGlvbiBk
ZXRlY3RlZCENCg0KVGhpcyBtZWFucyB0aGF0IGVpdGhlcjoNCg0KKDEpIHlv
dXIgaW5kZW50YXRpb24gaXMgb3V0cmlnaHQgaW5jb3JyZWN0IChlYXN5IHRv
IGZpeCksIG9yDQoNCigyKSB5b3VyIGluZGVudGF0aW9uIG1peGVzIHRhYnMg
YW5kIHNwYWNlcyBpbiBhIHdheSB0aGF0IGRlcGVuZHMgb24gXA0KaG93IG1h
bnkgc3BhY2VzIGEgdGFiIGlzIHdvcnRoLg0KDQpUbyBmaXggY2FzZSAyLCBj
aGFuZ2UgYWxsIHRhYnMgdG8gc3BhY2VzIGJ5IHVzaW5nIFNlbGVjdCBBbGwg
Zm9sbG93ZWQgXA0KYnkgVW50YWJpZnkgUmVnaW9uIChib3RoIGluIHRoZSBF
ZGl0IG1lbnUpLiIiIg0KDQpjbGFzcyBTY3JpcHRCaW5kaW5nOg0KDQogICAg
a2V5ZGVmcyA9IHsNCiAgICAgICAgJzw8Y2hlY2stbW9kdWxlPj4nOiBbJzxB
bHQtRjU+JywgJzxNZXRhLUY1PiddLA0KICAgICAgICAnPDxpbXBvcnQtbW9k
dWxlPj4nOiBbJzxGNT4nXSwNCiAgICAgICAgJzw8cnVuLXNjcmlwdD4+Jzog
Wyc8Q29udHJvbC1GNT4nXSwNCiAgICB9DQoNCiAgICBtZW51ZGVmcyA9IFsN
CiAgICAgICAgKCdlZGl0JywgW05vbmUsDQogICAgICAgICAgICAgICAgICAo
J0NoZWNrIG1vZHVsZScsICc8PGNoZWNrLW1vZHVsZT4+JyksDQogICAgICAg
ICAgICAgICAgICAoJ0ltcG9ydCBtb2R1bGUnLCAnPDxpbXBvcnQtbW9kdWxl
Pj4nKSwNCiAgICAgICAgICAgICAgICAgICgnUnVuIHNjcmlwdCcsICc8PHJ1
bi1zY3JpcHQ+PicpLA0KICAgICAgICAgICAgICAgICBdDQogICAgICAgICks
DQogICAgXQ0KDQogICAgZGVmIF9faW5pdF9fKHNlbGYsIGVkaXR3aW4pOg0K
ICAgICAgICBzZWxmLmVkaXR3aW4gPSBlZGl0d2luDQogICAgICAgICMgUHJv
dmlkZSBpbnN0YW5jZSB2YXJpYWJsZXMgcmVmZXJlbmNlZCBieSBEZWJ1Z2dl
cg0KICAgICAgICAjIFhYWCBUaGlzIHNob3VsZCBiZSBkb25lIGRpZmZlcmVu
dGx5DQogICAgICAgIHNlbGYuZmxpc3QgPSBzZWxmLmVkaXR3aW4uZmxpc3QN
CiAgICAgICAgc2VsZi5yb290ID0gc2VsZi5mbGlzdC5yb290DQoNCiAgICBk
ZWYgY2hlY2tfbW9kdWxlX2V2ZW50KHNlbGYsIGV2ZW50KToNCiAgICAgICAg
ZmlsZW5hbWUgPSBzZWxmLmdldGZpbGVuYW1lKCkNCiAgICAgICAgaWYgbm90
IGZpbGVuYW1lOg0KICAgICAgICAgICAgcmV0dXJuDQogICAgICAgIGlmIG5v
dCBzZWxmLnRhYm5hbm55KGZpbGVuYW1lKToNCiAgICAgICAgICAgIHJldHVy
bg0KICAgICAgICBpZiBub3Qgc2VsZi5jaGVja3N5bnRheChmaWxlbmFtZSk6
DQogICAgICAgICAgICByZXR1cm4NCg0KICAgIGRlZiB0YWJuYW5ueShzZWxm
LCBmaWxlbmFtZSk6DQogICAgICAgIGltcG9ydCB0YWJuYW5ueQ0KICAgICAg
ICBpbXBvcnQgdG9rZW5pemUNCiAgICAgICAgZiA9IG9wZW4oZmlsZW5hbWUs
ICdyJykNCiAgICAgICAgdHJ5Og0KICAgICAgICAgICAgdGFibmFubnkucHJv
Y2Vzc190b2tlbnModG9rZW5pemUuZ2VuZXJhdGVfdG9rZW5zKGYucmVhZGxp
bmUpKQ0KICAgICAgICBleGNlcHQgdG9rZW5pemUuVG9rZW5FcnJvciwgbXNn
Og0KICAgICAgICAgICAgc2VsZi5lcnJvcmJveCgiVG9rZW4gZXJyb3IiLA0K
ICAgICAgICAgICAgICAgICAgICAgICAgICAiVG9rZW4gZXJyb3I6XG4lcyIg
JSBzdHIobXNnKSkNCiAgICAgICAgICAgIHJldHVybiAwDQogICAgICAgIGV4
Y2VwdCB0YWJuYW5ueS5OYW5ueU5hZywgbmFnOg0KICAgICAgICAgICAgIyBU
aGUgZXJyb3IgbWVzc2FnZXMgZnJvbSB0YWJuYW5ueSBhcmUgdG9vIGNvbmZ1
c2luZy4uLg0KICAgICAgICAgICAgc2VsZi5lZGl0d2luLmdvdG9saW5lKG5h
Zy5nZXRfbGluZW5vKCkpDQogICAgICAgICAgICBzZWxmLmVycm9yYm94KCJU
YWIvc3BhY2UgZXJyb3IiLCBpbmRlbnRfbWVzc2FnZSkNCiAgICAgICAgICAg
IHJldHVybiAwDQogICAgICAgIHJldHVybiAxDQoNCiAgICBkZWYgY2hlY2tz
eW50YXgoc2VsZiwgZmlsZW5hbWUpOg0KICAgICAgICBmID0gb3BlbihmaWxl
bmFtZSwgJ3InKQ0KICAgICAgICBzb3VyY2UgPSBmLnJlYWQoKQ0KICAgICAg
ICBmLmNsb3NlKCkNCiAgICAgICAgaWYgJ1xyJyBpbiBzb3VyY2U6DQogICAg
ICAgICAgICBpbXBvcnQgcmUNCiAgICAgICAgICAgIHNvdXJjZSA9IHJlLnN1
YihyIlxyXG4iLCAiXG4iLCBzb3VyY2UpDQogICAgICAgIGlmIHNvdXJjZSBh
bmQgc291cmNlWy0xXSAhPSAnXG4nOg0KICAgICAgICAgICAgc291cmNlID0g
c291cmNlICsgJ1xuJw0KICAgICAgICB0cnk6DQogICAgICAgICAgICBjb21w
aWxlKHNvdXJjZSwgZmlsZW5hbWUsICJleGVjIikNCiAgICAgICAgZXhjZXB0
IChTeW50YXhFcnJvciwgT3ZlcmZsb3dFcnJvciksIGVycjoNCiAgICAgICAg
ICAgIHRyeToNCiAgICAgICAgICAgICAgICBtc2csIChlcnJvcmZpbGVuYW1l
LCBsaW5lbm8sIG9mZnNldCwgbGluZSkgPSBlcnINCiAgICAgICAgICAgICAg
ICBpZiBub3QgZXJyb3JmaWxlbmFtZToNCiAgICAgICAgICAgICAgICAgICAg
ZXJyLmFyZ3MgPSBtc2csIChmaWxlbmFtZSwgbGluZW5vLCBvZmZzZXQsIGxp
bmUpDQogICAgICAgICAgICAgICAgICAgIGVyci5maWxlbmFtZSA9IGZpbGVu
YW1lDQogICAgICAgICAgICBleGNlcHQ6DQogICAgICAgICAgICAgICAgbGlu
ZW5vID0gTm9uZQ0KICAgICAgICAgICAgICAgIG1zZyA9ICIqKiogIiArIHN0
cihlcnIpDQogICAgICAgICAgICBpZiBsaW5lbm86DQogICAgICAgICAgICAg
ICAgc2VsZi5lZGl0d2luLmdvdG9saW5lKGxpbmVubykNCiAgICAgICAgICAg
IHNlbGYuZXJyb3Jib3goIlN5bnRheCBlcnJvciIsDQogICAgICAgICAgICAg
ICAgICAgICAgICAgICJUaGVyZSdzIGFuIGVycm9yIGluIHlvdXIgcHJvZ3Jh
bTpcbiIgKyBtc2cpDQogICAgICAgIHJldHVybiAxDQoNCiAgICBkZWYgaW1w
b3J0X21vZHVsZV9ldmVudChzZWxmLCBldmVudCk6DQogICAgICAgIGZpbGVu
YW1lID0gc2VsZi5nZXRmaWxlbmFtZSgpDQogICAgICAgIGlmIG5vdCBmaWxl
bmFtZToNCiAgICAgICAgICAgIHJldHVybg0KDQogICAgICAgIG1vZG5hbWUs
IGV4dCA9IG9zLnBhdGguc3BsaXRleHQob3MucGF0aC5iYXNlbmFtZShmaWxl
bmFtZSkpDQogICAgICAgIGlmIHN5cy5tb2R1bGVzLmhhc19rZXkobW9kbmFt
ZSk6DQogICAgICAgICAgICBtb2QgPSBzeXMubW9kdWxlc1ttb2RuYW1lXQ0K
ICAgICAgICBlbHNlOg0KICAgICAgICAgICAgbW9kID0gaW1wLm5ld19tb2R1
bGUobW9kbmFtZSkNCiAgICAgICAgICAgIHN5cy5tb2R1bGVzW21vZG5hbWVd
ID0gbW9kDQogICAgICAgIG1vZC5fX2ZpbGVfXyA9IGZpbGVuYW1lDQogICAg
ICAgIHNldGF0dHIoc3lzLm1vZHVsZXNbJ19fbWFpbl9fJ10sIG1vZG5hbWUs
IG1vZCkNCg0KICAgICAgICBkaXIgPSBvcy5wYXRoLmRpcm5hbWUoZmlsZW5h
bWUpDQogICAgICAgIGRpciA9IG9zLnBhdGgubm9ybXBhdGgob3MucGF0aC5h
YnNwYXRoKGRpcikpDQogICAgICAgIGlmIGRpciBub3QgaW4gc3lzLnBhdGg6
DQogICAgICAgICAgICBzeXMucGF0aC5pbnNlcnQoMCwgZGlyKQ0KDQogICAg
ICAgIGZsaXN0ID0gc2VsZi5lZGl0d2luLmZsaXN0DQogICAgICAgIHNoZWxs
ID0gZmxpc3Qub3Blbl9zaGVsbCgpDQogICAgICAgIGludGVycCA9IHNoZWxs
LmludGVycA0KICAgICAgICBpbnRlcnAucnVuY29kZSgicmVsb2FkKCVzKSIg
JSBtb2RuYW1lKQ0KDQogICAgZGVmIHJ1bl9zY3JpcHRfZXZlbnQoc2VsZiwg
ZXZlbnQpOg0KICAgICAgICBmaWxlbmFtZSA9IHNlbGYuZ2V0ZmlsZW5hbWUo
KQ0KICAgICAgICBpZiBub3QgZmlsZW5hbWU6DQogICAgICAgICAgICByZXR1
cm4NCg0KICAgICAgICBmbGlzdCA9IHNlbGYuZWRpdHdpbi5mbGlzdA0KICAg
ICAgICBzaGVsbCA9IGZsaXN0Lm9wZW5fc2hlbGwoKQ0KICAgICAgICBpbnRl
cnAgPSBzaGVsbC5pbnRlcnANCiAgICAgICAgaWYgKG5vdCBzeXMuYXJndiBv
cg0KICAgICAgICAgICAgb3MucGF0aC5iYXNlbmFtZShzeXMuYXJndlswXSkg
IT0gb3MucGF0aC5iYXNlbmFtZShmaWxlbmFtZSkpOg0KICAgICAgICAgICAg
IyBYWFggVG9vIG9mdGVuIHRoaXMgZGlzY2FyZHMgYXJndW1lbnRzIHRoZSB1
c2VyIGp1c3Qgc2V0Li4uDQogICAgICAgICAgICBzeXMuYXJndiA9IFtmaWxl
bmFtZV0NCiAgICAgICAgb2xkX3N5c3BhdGggPSBzeXMucGF0aFs6XQ0KICAg
ICAgICBzeXMucGF0aC5hcHBlbmQob3MucGF0aC5kaXJuYW1lKG9zLnBhdGgu
YWJzcGF0aChmaWxlbmFtZSkpKQ0KICAgICAgICBpbnRlcnAuZXhlY2ZpbGUo
ZmlsZW5hbWUpDQogICAgICAgIHN5cy5wYXRoID0gb2xkX3N5c3BhdGgNCg0K
ICAgIGRlZiBnZXRmaWxlbmFtZShzZWxmKToNCiAgICAgICAgIyBMb2dpYyB0
byBtYWtlIHN1cmUgd2UgaGF2ZSBhIHNhdmVkIGZpbGVuYW1lDQogICAgICAg
ICMgWFhYIEJldHRlciBsb2dpYyB3b3VsZCBvZmZlciB0byBzYXZlIQ0KICAg
ICAgICBpZiBub3Qgc2VsZi5lZGl0d2luLmdldF9zYXZlZCgpOg0KICAgICAg
ICAgICAgbmFtZSA9IChzZWxmLmVkaXR3aW4uc2hvcnRfdGl0bGUoKSBvcg0K
ICAgICAgICAgICAgICAgICAgICBzZWxmLmVkaXR3aW4ubG9uZ190aXRsZSgp
IG9yDQogICAgICAgICAgICAgICAgICAgICJVbnRpdGxlZCIpDQogICAgICAg
ICAgICBzZWxmLmVycm9yYm94KCJOb3Qgc2F2ZWQiLA0KICAgICAgICAgICAg
ICAgICAgICAgICAgICAiVGhlIGJ1ZmZlciBmb3IgJXMgaXMgbm90IHNhdmVk
LlxuIiAlIG5hbWUgKw0KICAgICAgICAgICAgICAgICAgICAgICAgICAiUGxl
YXNlIHNhdmUgaXQgZmlyc3QhIikNCiAgICAgICAgICAgIHNlbGYuZWRpdHdp
bi50ZXh0LmZvY3VzX3NldCgpDQogICAgICAgICAgICByZXR1cm4NCiAgICAg
ICAgZmlsZW5hbWUgPSBzZWxmLmVkaXR3aW4uaW8uZmlsZW5hbWUNCiAgICAg
ICAgaWYgbm90IGZpbGVuYW1lOg0KICAgICAgICAgICAgc2VsZi5lcnJvcmJv
eCgiTm8gZmlsZSBuYW1lIiwNCiAgICAgICAgICAgICAgICAgICAgICAgICAg
IlRoaXMgd2luZG93IGhhcyBubyBmaWxlIG5hbWUiKQ0KICAgICAgICAgICAg
cmV0dXJuDQogICAgICAgIHJldHVybiBmaWxlbmFtZQ0KDQogICAgZGVmIGVy
cm9yYm94KHNlbGYsIHRpdGxlLCBtZXNzYWdlKToNCiAgICAgICAgIyBYWFgg
VGhpcyBzaG91bGQgcmVhbGx5IGJlIGEgZnVuY3Rpb24gb2YgRWRpdG9yV2lu
ZG93Li4uDQogICAgICAgIHRrTWVzc2FnZUJveC5zaG93ZXJyb3IodGl0bGUs
IG1lc3NhZ2UsIG1hc3Rlcj1zZWxmLmVkaXR3aW4udGV4dCkNCiAgICAgICAg
c2VsZi5lZGl0d2luLnRleHQuZm9jdXNfc2V0KCkNCg==
--545280650-578560010-1009656207=:13114--


From deliberatus@my995internet.com  Sun Dec 30 00:53:35 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sat, 29 Dec 2001 19:53:35 -0500
Subject: [Tutor] sci heacaches
Message-ID: <3C2E658F.92F43726@my995internet.com>

ok, I want to pass A SINGLE WORD to a script.

EVERYTHING after the first '?' in a url is sent to the environment
variable QUERY_STRING.

ok, here's a sample link:
<a
href="http://www.howlermonkey.net/cgi-bin.TLwebform2.py?listname=foo">foo</a>

ok, 'listname=foo' should be deposited in QUERY_STRING, says so right
here.

Sure. Right. Check.


-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From deliberatus@my995internet.com  Sun Dec 30 03:22:25 2001
From: deliberatus@my995internet.com (Kirk Bailey)
Date: Sat, 29 Dec 2001 22:22:25 -0500
Subject: [Tutor] woopie!!!
References: <200112300315.fBU3FAM01048@ns.howlermonkey.net>
Message-ID: <3C2E8871.9C67917F@my995internet.com>

YAY!
ok, I bound a hysenbug and a typo.

It seems, SOME header sequences are more reliable than others.

MOST people send out the email in a certain sequence of headers, more or
less, and this seems to work better than the older flavor- but even
then, your milage may vary.

WORSE, I found a missing '+' so instead of msg=msg+ (foo), it was 
msg=msg(evaluating true, and tossed away), then
+ subject+CRLF
which, having HEADER definition field, was ignored. The field definition
literal ("Subject ") was BEFORE this part, and omitted by the missing
'+'.

Sigh.


ok, that solved some oddities, and got out names back into the FROM
field. YAY!

ON ANOTHER FRONT THE REPLY TO FEATURE IS NOW IN AND WORKING.

That means not only can you have reply-to set to the list, it can be set
to a THIRD PARTY, making a MODERATED list simple.

Set the reply to to the moderator. They forward to list if approved,
trash it if not.

Are we having fun yet?


Kirk Bailey wrote:
> 
> test. first line of body, there should be a single blank line above this one
> in the file, but not in your received copy.
> 
> That blank line serves to seperate headers from body in the message.
> 
> --
> 
> Respectfully,
>              -Kirk D Bailey (C)2001
>               Addme! icq #27840081
> end
> 
> Within the sweep of his sword, Each man is an Ubar.
> 
> http://www.howlermonkey.net/
> http://www.sacredelectron.org/
> 
> this is the very last line of the message, not even an extra CRLF
> follows this.
> 
> -testlist3.footer=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
> click [REPLY] to reply to sender
> Click [REPLYALL] to reply to the list and poster
> Click RESET for education on computers
> 
> lastline footer
> 
> List random #3
> 
> Hosted by http://www.howlermonkey.net/ ! Free Email and Lists!
> 
> 36<a target="_blank" href="http://www.netflip.com/DL?v=1&w=2335137&x=468&y=60&t=S&n=1">How would YOU spend $200? At NepFlip EVERYONE get's paid!</a><br>

-- 
Respectfully,
             -Kirk D Bailey (C)2001
              Addme! icq #27840081
end


Within the sweep of his sword, Each man is an Ubar.

http://www.howlermonkey.net/
http://www.sacredelectron.org/


From RWolfson@home.com  Sun Dec 30 03:55:55 2001
From: RWolfson@home.com (Ross Wolfson)
Date: Sat, 29 Dec 2001 22:55:55 -0500
Subject: [Tutor] BaseHTTPServer Tutorial
Message-ID: <DAEJIMBGGABPFALKBGFJIEJGCEAA.RWolfson@home.com>

Does anyone know of a good BaseHTTPServer tutorial? It seems like a great
library since Edna (http://edna.sourceforge.net) was written using it, but I
wonder how they learned how to use it. I've tried google and I can't get any
real tutorials on BaseHTTPServer. (One showing how to make a simple 'hello
world' webpage might be nice). Ednas source is also way too complex for a
simple hello world to come from it. (I also don't know anything about http
programming and headers etc)

-Ross W.








P.S. - Heres my nonworking source to a hello world attempt(don't try to
execute it, it doesn't work)(To be safe, I included every library edna did,
and I also copied a lot of source)


import SocketServer
import BaseHTTPServer
import ConfigParser
import sys
import string
import os
import cgi
import urllib
import socket
import re
import stat
import random
import time
import struct


# determine which mixin to use: prefer threading, fall back to forking.
try:
  import thread
  mixin = SocketServer.ThreadingMixIn
except ImportError:
  if not hasattr(os, 'fork'):
    print "ERROR: your platform does not support threading OR forking."
    sys.exit(1)
  mixin = SocketServer.ForkingMixIn



class myserver(mixin,BaseHTTPServer.HTTPServer):
    def __init__(self):
        self.port=80
        SocketServer.TCPServer.__init__(self,('',
self.port),myrequesthandler)
    def server_bind(self):
        # set SO_REUSEADDR (if available on this platform)
        if hasattr(socket, 'SOL_SOCKET') and hasattr(socket,
'SO_REUSEADDR'):
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
1)
            BaseHTTPServer.HTTPServer.server_bind(self)
    """
    def acl_ok(self, ipaddr):
        if not self.acls:
            return 1
        ipaddr = dot2int(ipaddr)
        for allowed, mask in self.acls:
            if (ipaddr & mask) == (allowed & mask):
                return 1
        return 0
    """

class myrequesthandler(BaseHTTPServer.BaseHTTPRequestHandler):

  def do_GET(self):
    self._perform_GET()

  def _perform_GET(self):
    if not self.server.acl_ok(self.client_address[0]):
      self.send_error(403, 'Forbidden')
      return
    path = self.translate_path()
    if path is None:
      self.send_error(400, 'Illegal URL construction')
      return
    self.send_response(200)
    self.send_header("Content-Type", 'text/html')
    self.end_headers()
    self.wfile.write('<html><head><title>Testing</title></head><body>Testing
1 2 3...')
    self.wfile.write('<br><br><br>')
    self.wfile.write(`self.client_address[0]`)

    print self.client_address[0]




if __name__ == '__main__':
  print 'working!'
  svr=myserver()
  svr.serve_forever()




From lha2@columbia.edu  Sun Dec 30 13:45:06 2001
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Sun, 30 Dec 2001 08:45:06 -0500
Subject: [Tutor] Re...From PRJoshi
References: <MABBICBJKOGBBPCNIOOBIEKJCCAA.prjoshi@ntc.net.np>
Message-ID: <3C2F1A62.46D9D205@mail.verizon.net>

If no one gets back to you on how to do this within Tkinter, check out
wxWindows, which does allow you to change that icon. It appears that an
MS Windows icon is standard, but the demo uses a custom icon.

Sorry if this is not responsive--I don't know wxWindows well enough to
know its ease of use compared to Tkinter, just ran the demo and saw that
the code for doing what you want is already written (for wxWindows).

> Pravin Raj Joshi wrote:
> 
> Hi,
> 
> Sorry for not being very clear with my last questions.
> I seem to have solved the problem for the pages and files.
> But I would like to clearify my second question.
> What I want to do is change the icon of my windows. (I have inserted a
> photo of what I want to do!)
> 
> (photo indicating that PRJoshi doesn't like the red cursive "Tk" in the 
> top left corner of each Tkinter window)
> 
> Basically I want to change the TK icon with something else. I read
> somewhere it was not possible to change that for the root, but it was
> possible for the toplevel.
> 
> How to change that?
> 
> Thanks
> 
> PRJoshi


From dyoo@hkn.eecs.berkeley.edu  Sun Dec 30 22:02:41 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 30 Dec 2001 14:02:41 -0800 (PST)
Subject: [Tutor] sci heacaches
In-Reply-To: <3C2E658F.92F43726@my995internet.com>
Message-ID: <Pine.LNX.4.21.0112300146090.21035-100000@hkn.eecs.berkeley.edu>

On Sat, 29 Dec 2001, Kirk Bailey wrote:

> ok, I want to pass A SINGLE WORD to a script.
> 
> EVERYTHING after the first '?' in a url is sent to the environment
> variable QUERY_STRING.

Yes, that what the CGI standard says is supposed to happen: the whole
query string be stored in the environmental variable QUERY_STRING.  It
becomes the programmer's job to either pick things out of QUERY_STRING
manually, or use something that other programmers have cooked up, like the
'cgi' module:

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

The 'cgi' module is a little complicated to use at first, but it's worth
using it.  The module does a lot of stuff like automatically escaping and
unescaping special characters in parameters.



From highprimate@howlermonkey.net  Sun Dec 30 23:02:27 2001
From: highprimate@howlermonkey.net (Kirk Bailey)
Date: Sun, 30 Dec 2001 18:2:27 -0500
Subject: [Tutor] ARG! @$^@$%@@$! isp email server...
Message-ID: <200112302302.fBUN2OM06513@ns.howlermonkey.net>

Oy Gevalt. MUTHA.

My isp's email server is down, AGAIN, since around 2:30 am. fortunately, here at HowlerMonkey we aspire 
to superior uptime ratios, and achive them by BoB by damn by yes.

oh say is the now. cgi-wiz around, for my brains are confuused, and my fingers now are brused.
webform2 is the task, and it sits on it's ass,
blowing errors for all, and my skills here are quite small.

Should I post the thing or point you at a web page that includes it?
	http://www.howlermonkey.net/TLwebform2.shtml

also have a web page with the web error log on display.
	http://www.howlermonkey.net/cgi-bin/current-error.cgi

As these are ssi, they are instant by instant updates and are CURRENT.
(ssi and html I got down fair to decent by now.)


end

In total confusion,
                   Kirk D Bailey

|----------------------------------------------------|
|           Consulting  Agent  Provecateur           |
|    Webmaster, Howlermonkey Email services Co.      |
|   Please visit us at http://www.howlermonkey.net/  |
|----------------------------------------------------|




From fallen@leveltwo.com  Sun Dec 30 23:31:52 2001
From: fallen@leveltwo.com (Fred Allen)
Date: Sun, 30 Dec 2001 15:31:52 -0800
Subject: [Tutor] PythonPath Stickiness
Message-ID: <4BB02C541824D311921600902765DB7B445B14@LTISERVER>

Dear Sirs and Mesdames:

I 've recently gotten a new system, which operates under MS Windows 2000
Pro and whereupon I've installed Python 2.2 and a coterie of adjuncts.
For reasons obscure to me, my PYTHONPATH environmental variable seems
ignored.  I believe when I enter the 'python' command, the command
processor should first search my current directory and, failing to find
the executable therein, proceed to search in sequence all directories
listed under the 'path' environmental variable and then, still failing
to find 'python.exe' proceed likewise, searching through those
directories associated with the environmental variable 'PYTHONPATH.'
Mine behaves otherwise, as the screen listing below attests.

Microsoft Windows 2000 [Version 5.00.2195]
(C) Copyright 1985-2000 Microsoft Corp.

C:\>set PYTHONPATH
PYTHONPATH=C:\Python22\;C:\Python22\Lib\site-packages\wxPython\demo\

C:\>python
'python' is not recognized as an internal or external command,
operable program or batch file.

C:\>cd Python22

C:\Python22>python
Python 2.2c1 (#27, Dec 14 2001, 13:15:16) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

I'll be grateful for any help.  With thanks in advance, I am,

Respectfully,

Fred Allen



From dyoo@hkn.eecs.berkeley.edu  Mon Dec 31 00:20:59 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 30 Dec 2001 16:20:59 -0800 (PST)
Subject: [Tutor] PythonPath Stickiness
In-Reply-To: <4BB02C541824D311921600902765DB7B445B14@LTISERVER>
Message-ID: <Pine.LNX.4.21.0112301617050.6268-100000@hkn.eecs.berkeley.edu>

On Sun, 30 Dec 2001, Fred Allen wrote:

> Dear Sirs and Mesdames:
> 
> I 've recently gotten a new system, which operates under MS Windows
> 2000 Pro and whereupon I've installed Python 2.2 and a coterie of
> adjuncts. For reasons obscure to me, my PYTHONPATH environmental
> variable seems ignored.

You're probably thinking of the PATH environmental variable, which Windows
uses to search for commands.

You can modify the PATH variable from the Control Panel applet; I don't
have Windows 2000 at the moment, but I did remember seeing something like
"Environmental Variables" somewhere in there.


PYTHONPATH is specific to Python's searching of library modules, not the
execution of console commands.  If you have more questions, please feel
free to ask.



From grimmtoothtoo@yahoo.com  Mon Dec 31 00:49:04 2001
From: grimmtoothtoo@yahoo.com (Grimmtooth)
Date: Sun, 30 Dec 2001 19:49:04 -0500
Subject: [Tutor] PythonPath Stickiness
In-Reply-To: <4BB02C541824D311921600902765DB7B445B14@LTISERVER>
Message-ID: <NLEIJCOLEACIANLABPOECEEECDAA.grimmtoothtoo@yahoo.com>

> For reasons obscure to me, my PYTHONPATH environmental variable seems
> ignored.  I believe when I enter the 'python' command, the command

PYTHONPATH is only used internally by Python itself.  The location of the
Python binary should be indicated in the primary PATH variable, just like
everything else.

PYTHONPATH tells Python where to find its goodies once it is started, so you
WILL need to have that set, too.



_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com



From wilson@visi.com  Mon Dec 31 02:30:43 2001
From: wilson@visi.com (Timothy Wilson)
Date: Sun, 30 Dec 2001 20:30:43 -0600 (CST)
Subject: [Tutor] Code critique please (OOP strategy)
Message-ID: <Pine.GSO.4.21.0112302022590.19805-100000@isis.visi.com>

Hi everyone,

I've done an object-oriented version of the stock portfolio tracking
program I assigned to my students
(http://www.isd197.org/sibley/cs/icp/assignments/portfolio_html). I plan
to use this for comparison when we introduce OOP after the Winter Break.

My version is available at http://www.qwerk.org/tim/

I'd like to get some feedback on the code. I've created two classes
here, Portfolio and Stock. I'm specifically interested in the way the
main() function interacts with the class methods. I've got a strange mix
of program logic stuck in a series of elif statements and in the class
methods themselves. Something doesn't seem right about it.

Is there a way to create a Menu class that would help?

-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 karthikg@aztec.soft.net  Mon Dec 31 04:40:43 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Mon, 31 Dec 2001 10:10:43 +0530
Subject: [Tutor] BaseHTTPServer Tutorial
In-Reply-To: <DAEJIMBGGABPFALKBGFJIEJGCEAA.RWolfson@home.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDMEGICMAA.karthikg@aztec.soft.net>

core python programming has this code..s'd be helpful.
in the beginning ,place a plain test.html file in the directory from where
you start the server and
try accesing it through

http://localhost/test.html

wffile in BaseHTTPRequestHandler points to the output stream where we can
write.
this code just reads the contents of the file u tried accessing
("test.html")
and writes it to that stream which can be seen on the browser.

...code...

from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        try:
            f = open(curdir + sep + self.path) #self.path has /test.html
            self.send_response(200)
            self.send_header('Content-type',	'text/html')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)

def main():
    try:
        server = HTTPServer(('', 80), MyHandler)
        print 'Welcome to the machine...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Ross Wolfson
Sent: Sunday, December 30, 2001 9:26 AM
To: tutor@python.org
Subject: [Tutor] BaseHTTPServer Tutorial


Does anyone know of a good BaseHTTPServer tutorial? It seems like a great
library since Edna (http://edna.sourceforge.net) was written using it, but I
wonder how they learned how to use it. I've tried google and I can't get any
real tutorials on BaseHTTPServer. (One showing how to make a simple 'hello
world' webpage might be nice). Ednas source is also way too complex for a
simple hello world to come from it. (I also don't know anything about http
programming and headers etc)

-Ross W.








P.S. - Heres my nonworking source to a hello world attempt(don't try to
execute it, it doesn't work)(To be safe, I included every library edna did,
and I also copied a lot of source)


import SocketServer
import BaseHTTPServer
import ConfigParser
import sys
import string
import os
import cgi
import urllib
import socket
import re
import stat
import random
import time
import struct


# determine which mixin to use: prefer threading, fall back to forking.
try:
  import thread
  mixin = SocketServer.ThreadingMixIn
except ImportError:
  if not hasattr(os, 'fork'):
    print "ERROR: your platform does not support threading OR forking."
    sys.exit(1)
  mixin = SocketServer.ForkingMixIn



class myserver(mixin,BaseHTTPServer.HTTPServer):
    def __init__(self):
        self.port=80
        SocketServer.TCPServer.__init__(self,('',
self.port),myrequesthandler)
    def server_bind(self):
        # set SO_REUSEADDR (if available on this platform)
        if hasattr(socket, 'SOL_SOCKET') and hasattr(socket,
'SO_REUSEADDR'):
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
1)
            BaseHTTPServer.HTTPServer.server_bind(self)
    """
    def acl_ok(self, ipaddr):
        if not self.acls:
            return 1
        ipaddr = dot2int(ipaddr)
        for allowed, mask in self.acls:
            if (ipaddr & mask) == (allowed & mask):
                return 1
        return 0
    """

class myrequesthandler(BaseHTTPServer.BaseHTTPRequestHandler):

  def do_GET(self):
    self._perform_GET()

  def _perform_GET(self):
    if not self.server.acl_ok(self.client_address[0]):
      self.send_error(403, 'Forbidden')
      return
    path = self.translate_path()
    if path is None:
      self.send_error(400, 'Illegal URL construction')
      return
    self.send_response(200)
    self.send_header("Content-Type", 'text/html')
    self.end_headers()
    self.wfile.write('<html><head><title>Testing</title></head><body>Testing
1 2 3...')
    self.wfile.write('<br><br><br>')
    self.wfile.write(`self.client_address[0]`)

    print self.client_address[0]




if __name__ == '__main__':
  print 'working!'
  svr=myserver()
  svr.serve_forever()



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


From shalehperry@attbi.com  Mon Dec 31 08:11:02 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 31 Dec 2001 00:11:02 -0800 (PST)
Subject: [Tutor] Code critique please (OOP strategy)
In-Reply-To: <Pine.GSO.4.21.0112302022590.19805-100000@isis.visi.com>
Message-ID: <XFMail.20011231001102.shalehperry@attbi.com>

On 31-Dec-2001 Timothy Wilson wrote:
> Hi everyone,
> 
> I've done an object-oriented version of the stock portfolio tracking
> program I assigned to my students
> (http://www.isd197.org/sibley/cs/icp/assignments/portfolio_html). I plan
> to use this for comparison when we introduce OOP after the Winter Break.
> 
> My version is available at http://www.qwerk.org/tim/
> 
> I'd like to get some feedback on the code. I've created two classes
> here, Portfolio and Stock. I'm specifically interested in the way the
> main() function interacts with the class methods. I've got a strange mix
> of program logic stuck in a series of elif statements and in the class
> methods themselves. Something doesn't seem right about it.
> 

In my opinion, constructing a class should never cause the program to stop at a
prompt.  This prevents later use.  If I wanted to make a list of portfolio's
and then give them files to open, I see no way to do this.  In C++ parlance you
have no default constructor.

I am also curious as to why the prices are * 100 every time.  There is no
comment in the code for this.

> Is there a way to create a Menu class that would help?
> 

you could make a menu class or function, but all that would do is move the
code out of main.

What you could do is have each menu choice be a function (or class method) and
have the code do a dictionary lookup -- think symbol table.

options['A'] = addNewStock
options['D'] = deleteStock
...

while not done:
    input = raw_input(prompt)
    try:
        options[input.upper()]()
    except KeyError:
        print "Invalid choice!"




From karthikg@aztec.soft.net  Mon Dec 31 13:50:50 2001
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Mon, 31 Dec 2001 19:20:50 +0530
Subject: [Tutor] overloaded methods
In-Reply-To: <XFMail.20011231001102.shalehperry@attbi.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDIEHBCMAA.karthikg@aztec.soft.net>

just to confirm. Overloading method names(with parameters belonging to
different types)
is not possible in python.

class Currency:
	pass
class Dollar(Currency):
	pass
class Euro(Currency):
	pass

class CalculateRupeeEquivalent:
	def calculate(currency):
		//type checking of curency here?
		//i don't like it with lots of ifs and else.

so alternative is...

class CalculateRupeeEquivalentForDollar(CalculateRupeeEquivalent):
	def calculate(currency):
		//return equivalent


class CalculateRupeeEquivalentForEuro(CalculateRupeeEquivalent):
	def calculate(currency):
		//return equivalent


if __name__ == '__main__':
	calc = a.GetCalculator()
	curr = a.GetCurrency()
	calc.calculate(curr)



karthik.



From alan.gauld@bt.com  Mon Dec 31 13:52:28 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 31 Dec 2001 13:52:28 -0000
Subject: [Tutor] ok, got a primitive but workable solution
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C219@mbtlipnt02.btlabs.bt.co.uk>

Kirk,

Just one wee suggestion:

> I want to extract the pure list name so I can display 
> ONLY that. This works.
> 
> def getname(list):
> 	a=string.split(list,'/')
> 	b=a[2]

instead of using 2 how about -1 to always get the 
last element.

If the configuration ever results in more than one level 
of depth your version will break. Always getting the 
last element shoud make it more resistant to change.

Just a thought...

> 	c=string.split(b,'.')
> 	return c[0]

Alan G.


From alan.gauld@bt.com  Mon Dec 31 14:10:59 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 31 Dec 2001 14:10:59 -0000
Subject: [Tutor] Building Python Source with Cygwin?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C21B@mbtlipnt02.btlabs.bt.co.uk>

> I recently installed a lot of the Cygwin stuff on my machine 
> (GCC, etc...).

Me too, it's pretty cool huh?

> Can I take the Python source from any of my Linux CD's and 
> build it for Win2K with Cygwin?  

Pretty much but there is an official Cygwin python that has 
already done that for you. Its currently at Python2.1 but 
2.2 should be along real soon. It includes the readline 
module which makes life in a DOS box/Bash shell much easier.

> wondering if I can now take any related source (SWIG, Jython, 
> etc...) from anywhere and build it on my Win2K box or partition.  

Thats the idea, once you get the LD-LIB paths and other config 
bits sorted out it should build fairly seamlessly, although 
I've not tried anything non-trivial yet myself.

Alan G.


From alan.gauld@bt.com  Mon Dec 31 14:20:57 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 31 Dec 2001 14:20:57 -0000
Subject: [Tutor] Multi-line statements with comments
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C21C@mbtlipnt02.btlabs.bt.co.uk>

> I tend to want to write code that is well-commented
> and easy to read, with a minimum of abstraction.  

Thats a good aim, just be sure not to over comment it!
It used to be said that 40% comment was good but more 
recent studies suggest that for higher level languages 
like Python 10-20% is better.

Also don't forget to use doc strings to comment your 
functions/classes rather than traditional comments.
With good doc strings in place you shouldn't need too many comments


For
> now, another function seems a little to much, an
> unnecessary amount of logic that others may not pick
> up on.
> 
> It also may make my code harder to share, without some
> cut and paste for readability.
> 
> Once again, I appreciate all the responses, thanks
> very much.
> 
> ---
> Jim
> 
> 
> 
> __________________________________________________
> Do You Yahoo!?
> Send your FREE holiday greetings online!
> http://greetings.yahoo.com
> 
> 


From alan.gauld@bt.com  Mon Dec 31 14:29:36 2001
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 31 Dec 2001 14:29:36 -0000
Subject: [Tutor] Re...From PRJoshi
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C21D@mbtlipnt02.btlabs.bt.co.uk>

> If no one gets back to you on how to do this within Tkinter, 
> check out wxWindows, which does allow you to change that icon. 

Yes, wxWindows will do this and a lot more.

> Sorry if this is not responsive--I don't know wxWindows well enough to
> know its ease of use compared to Tkinter, 

Personally I find wxWindows layout/constraints mechanism 
much more complicated to use than pack/grid. Otherwise its fine. 

But it really needs better tutorial documentation. Unless 
you are happy reading C++ the included docs are hard going 
and the tutors/examples could be better explained.

If I wasn't busy on another writing project at the moment I'd 
like to have a go myself! Not least as a way of educating 
myself on how wxWindows works :-)

Alan G.

PS Apologies to the group for an earlier missive about 
commenting being set prematurely...


From wilson@visi.com  Mon Dec 31 14:46:48 2001
From: wilson@visi.com (Timothy Wilson)
Date: Mon, 31 Dec 2001 08:46:48 -0600 (CST)
Subject: [Tutor] Code critique please (OOP strategy)
In-Reply-To: <XFMail.20011231001102.shalehperry@attbi.com>
Message-ID: <Pine.GSO.4.21.0112310838530.24548-100000@isis.visi.com>

On Mon, 31 Dec 2001, Sean 'Shaleh' Perry wrote:

> In my opinion, constructing a class should never cause the program to stop at a
> prompt.  This prevents later use.  If I wanted to make a list of portfolio's
> and then give them files to open, I see no way to do this.  In C++ parlance you
> have no default constructor.

You're talking about the Portfolio constructor, right? Should I create a
separate method to unpickle the data from disk?

> I am also curious as to why the prices are * 100 every time.  There is no
> comment in the code for this.

All the prices are stored in cents. My understanding is that a lot of
software that works with financial data keeps track of everything in
cents and converts to dollars when necessary. This should help eliminate
rounding errors.

> you could make a menu class or function, but all that would do is move the
> code out of main.

Here's an example:

The main() function contains the following code to delete a stock:

elif choice.upper() == 'D':
    ticker = raw_input("Delete which stock (type a ticker symbol): ")
    for stock in p.contents:
        if stock.ticker == ticker.upper():
            p.delStock(stock)
            print "Removed %s" % stock.ticker

The delStock method is:

def delStock(self, stock):
    self.contents.remove(stock)
    self.modified = 1

Is is correct to ask for the ticker symbol in the 'elif' or should I do
that in 'delStock'? My reason for doing it the way I did was to make the
code as reusable as possible. That may or may not be a valid reason in
this case. I'd appreciate feedback on this point.

-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 grimmtoothtoo@yahoo.com  Mon Dec 31 15:46:02 2001
From: grimmtoothtoo@yahoo.com (Grimmtooth)
Date: Mon, 31 Dec 2001 10:46:02 -0500
Subject: [Tutor] Code critique please (OOP strategy)
In-Reply-To: <Pine.GSO.4.21.0112310838530.24548-100000@isis.visi.com>
Message-ID: <NLEIJCOLEACIANLABPOEKEEGCDAA.grimmtoothtoo@yahoo.com>

> All the prices are stored in cents. My understanding is that a lot of
> software that works with financial data keeps track of everything in
> cents and converts to dollars when necessary.

That is, as far as I know, correct, or more correct to say that it leaves
out the decimal point. The main reason is that point of sale devices tend to
have limited memory, so the fewer places where floating point operations are
required, the better.

I don't know to what extent you plan to use it, though, so be aware that not
all nations use the same standard. In my company's Latin America
applications, we have to allow for wandering decimal places, including NO
decimal places. So if you intend to go multinational with the app, plan NOW
for a wandering decimal and you'll have few problems in the future. If you
have to bolt it on in the future, like we did, it's a real mess :-)



_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com



From shalehperry@attbi.com  Mon Dec 31 18:03:36 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 31 Dec 2001 10:03:36 -0800 (PST)
Subject: [Tutor] Code critique please (OOP strategy)
In-Reply-To: <Pine.GSO.4.21.0112310838530.24548-100000@isis.visi.com>
Message-ID: <XFMail.20011231100336.shalehperry@attbi.com>

On 31-Dec-2001 Timothy Wilson wrote:
> On Mon, 31 Dec 2001, Sean 'Shaleh' Perry wrote:
> 
>> In my opinion, constructing a class should never cause the program to stop
>> at a
>> prompt.  This prevents later use.  If I wanted to make a list of portfolio's
>> and then give them files to open, I see no way to do this.  In C++ parlance
>> you
>> have no default constructor.
> 
> You're talking about the Portfolio constructor, right? Should I create a
> separate method to unpickle the data from disk?
> 

yes, you should.  More choices that way.

>> I am also curious as to why the prices are * 100 every time.  There is no
>> comment in the code for this.
> 
> All the prices are stored in cents. My understanding is that a lot of
> software that works with financial data keeps track of everything in
> cents and converts to dollars when necessary. This should help eliminate
> rounding errors.
> 

you should document this fact.

>> you could make a menu class or function, but all that would do is move the
>> code out of main.
> 
> Here's an example:
> 
> The main() function contains the following code to delete a stock:
> 
> elif choice.upper() == 'D':
>     ticker = raw_input("Delete which stock (type a ticker symbol): ")
>     for stock in p.contents:
>         if stock.ticker == ticker.upper():
>             p.delStock(stock)
>             print "Removed %s" % stock.ticker
> 
> The delStock method is:
> 
> def delStock(self, stock):
>     self.contents.remove(stock)
>     self.modified = 1
> 
> Is is correct to ask for the ticker symbol in the 'elif' or should I do
> that in 'delStock'? My reason for doing it the way I did was to make the
> code as reusable as possible. That may or may not be a valid reason in
> this case. I'd appreciate feedback on this point.
> 

class methods should not prompt.  You have the right idea in the current code. 
If you follow the example with the dictionary in my code you can clean main up
quite a bit.


From arcege@speakeasy.net  Mon Dec 31 18:04:38 2001
From: arcege@speakeasy.net (Michael P. Reilly)
Date: Mon, 31 Dec 2001 13:04:38 -0500
Subject: [Tutor] Code critique please (OOP strategy)
In-Reply-To: <Pine.GSO.4.21.0112310838530.24548-100000@isis.visi.com>; from wilson@visi.com on Mon, Dec 31, 2001 at 08:46:48AM -0600
References: <XFMail.20011231001102.shalehperry@attbi.com> <Pine.GSO.4.21.0112310838530.24548-100000@isis.visi.com>
Message-ID: <20011231130438.B922@speakeasy.net>

On Mon, Dec 31, 2001 at 08:46:48AM -0600, Timothy Wilson wrote:
[rest snipped]
> > you could make a menu class or function, but all that would do is move the
> > code out of main.
> 
> Here's an example:
> 
> The main() function contains the following code to delete a stock:
> 
> elif choice.upper() == 'D':
>     ticker = raw_input("Delete which stock (type a ticker symbol): ")
>     for stock in p.contents:
>         if stock.ticker == ticker.upper():
>             p.delStock(stock)
>             print "Removed %s" % stock.ticker
> 
> The delStock method is:
> 
> def delStock(self, stock):
>     self.contents.remove(stock)
>     self.modified = 1
> 
> Is is correct to ask for the ticker symbol in the 'elif' or should I do
> that in 'delStock'? My reason for doing it the way I did was to make the
> code as reusable as possible. That may or may not be a valid reason in
> this case. I'd appreciate feedback on this point.

You might want to look at the cmd module; it's design is meant for
user keyboard input.

import cmd

class Portfolio(cmd.Cmd):
  prompt = '(O)pen existing portfolio or (M)ake a new one? '

  def __init__(self):
    cmd.Cmd.__init__(self)
    self.portfolio = None

  def do_M(self, args):
    self.portfolio = Portfolio()

  def do_O(self, args):
    file = raw_input("filename: ")
    self.portfolio = Portfolio(file)

class StockCmd(cmd.Cmd):
  prompt = '(A)dd/(D)elete stocks, (S)ave file, (U)pdate, ' \
           '(R)eport, or (Q)uit? '

  def __init__(self, portfolio):
    cmd.Cmd.__init__(self)
    self.portfolio = portfolio

  def do_A(self, args):
    ticker = raw_input("Ticket symbol: ")
    companyname = raw_input("Company name: ")
    ...
    p.addStock(s)

  def do_D(self, args):
  
  ...

then you create new instances of these classes:

cmd = PortfolioCmd()
cmd.onecmd()  # only one prompt and return
if cmd.portfolio is not None:
  StockCmd(cmd.portfolio).cmdloop()

This makes things a bit more extensible and teaches your students to
reuse library classes.

  -Arcege



From oliveriosierra@hotmail.com  Mon Dec 31 06:09:10 2001
From: oliveriosierra@hotmail.com (Oliverio Sierra)
Date: Mon, 31 Dec 2001 06:09:10 +0000
Subject: [Tutor] need a little help
Message-ID: <F1264upgNECPkGSXkIa0000e9a5@hotmail.com>

hi, i just downloaded and started studying python a few days ago. it's also 
the first language i have studied. i am currently writing my first 
semi-complicated(at least for me) program and i hit a dead end.  my program 
goes a little like this:

-there is a menu with 3 choices
-then a user = input() statement
-then an if, 2 elif, and an else statements

i can go into any of the 3 choices, but only once. i need to be able to go 
into them several times. i have read everything i could find on the net, but 
had no succes.  i know there is a way for the program to cycle back to where 
my user = input() statement is.  i apreshiate your help and time. thank you.

_________________________________________________________________
Hable con sus amigos en línea, pruebe MSN Messenger: http://messenger.msn.es



From jeff@ccvcorp.com  Mon Dec 31 18:20:43 2001
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 31 Dec 2001 10:20:43 -0800
Subject: [Tutor] Re: Tutor digest, Vol 1 #1302 - 15 msgs
References: <E16L4ac-0000sS-00@mail.python.org>
Message-ID: <3C30AC7A.BFA3F572@ccvcorp.com>

>
> Message: 9
> From: Karthik Gurumurthy <karthikg@aztec.soft.net>
> To: tutor@python.org
> Date: Mon, 31 Dec 2001 19:20:50 +0530
> Subject: [Tutor] overloaded methods
>
> just to confirm. Overloading method names(with parameters belonging to
> different types)
> is not possible in python.
>
> class Currency:
>         pass
> class Dollar(Currency):
>         pass
> class Euro(Currency):
>         pass
>
> class CalculateRupeeEquivalent:
>         def calculate(currency):
>                 //type checking of curency here?
>                 //i don't like it with lots of ifs and else.

Well, it *is* possible to get the name of an object's class...

>>> class A:
...  pass
...
>>> class B(A):
...  pass
...
>>> a = A()
>>> b = B()
>>> str(a.__class__)
'__main__.A'
>>> str(b.__class__)
'__main__.B'
>>>

__main__ would of course be replaced by whatever your module name is, but in any case the final component
should be the classname.  So you set up a dictionary that contains your conversion rates, and then do
something like:

def ConvertToRupees(currencyobject):
    # Get the part of the __class__ after the last period--
    currencytype = str(currencyobject.__class__).split('.')[-1]
    conversionrate = ConversionDict[currencytype]
    return (currencyobject.amount * conversionrate)


Actually, I think that a better approach would be to build conversions into each currency class, and then
simply query the currency object.

class Currency:
    def ConvertToRupees(self):
        return self.amount * self.rupeerate

class Dollar(Currency):
    rupeerate = 2.5

class Euro(Currency):
    rupeerate = 3.0

(Obviously I'm just randomly guessing at conversion rates, as I have honestly no idea what the relative
value of the Rupee is ;) )  Depending on your application, you may want to import the actual values for the
conversion rates from somewhere else (so that they can be, for example, automatically updated from a
database)...

Jeff Shannon
Technician/Programmer
Credit International




From dyoo@hkn.eecs.berkeley.edu  Mon Dec 31 18:16:18 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 31 Dec 2001 10:16:18 -0800 (PST)
Subject: [Tutor] wxPython? (fwd)
Message-ID: <Pine.LNX.4.21.0112311010200.22581-100000@hkn.eecs.berkeley.edu>

Hi Karshi,

Let me forward this to the rest of Tutor.  I hate saying this, but I
can't reproduce the wackiness.

The only thing I can think that of that can trigger this behavior is if
divide() itself was defined as:

###
def divide(x,y):
    return x
###

But then, I might not be considering some strange side effect.  Can you
check to see if this is what's happening?  Also, what version of Python
are you using?



---------- Forwarded message ----------
Date: Mon, 31 Dec 2001 09:13:45 -0500
From: Karshi <karshi.hasanov@utoronto.ca>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] wxPython?

Hi Danny,
Can you tell me why I am getting the strange results here:

from Numeric import *

def divide(x,y):
    return x/y

for y in range(-10,10,1):
    x=2
    try:
        print divide(x,y), y
        
    except ZeroDivisionError:
        print "You are trying to divide by zero"
    
----------------

-1 -10
-1 -9
-1 -8
-1 -7
-1 -6
-1 -5
-1 -4
-1 -3
-1 -2
-2 -1
You are trying to divide by zero
2 1
1 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9
------------------------------
Why x/y gives wrong results?


On Tuesday 25 December 2001 02:32 pm, you wrote:
> On Mon, 24 Dec 2001, Karshi Hasanov wrote:
> >  I wanna use python GUI's , like wxPython or Tkinter.
> > Which one would be easy to learn, or what 's advantage of using wxPython
> > than Tkinter?
>
> Both are pretty nice.  I think that Tkinter is easier to learn, but many
> people feel that Tkinter looks ugly.  *grin*
>
>
> Tkinter is also installed by default when we install Python, so it's used
> quite a lot.  Have you seen Fredrik Lungh's 'An Introduction to Tkinter'
> web site?
>
>     http://www.pythonware.com/library/tkinter/introduction/
>
> It's a great tutorial on Tkinter programming.  Take a look at it, and see
> if Tkinter is a good fit.
>
> Good luck!



From wheelege@hotmail.com  Mon Dec 31 18:15:46 2001
From: wheelege@hotmail.com (Glen Wheeler)
Date: Tue, 1 Jan 2002 05:15:46 +1100
Subject: [Tutor] need a little help
References: <F1264upgNECPkGSXkIa0000e9a5@hotmail.com>
Message-ID: <DAV72peVPOEcyhJzqNw000079f8@hotmail.com>

  Howdy,

  What your looking for is a loop - in this situation I think a while loop
would be best.  Is there a quit option in your menu?  Here is a little bit
of python...

print 'Hi, please enter 1 to print slime mould, 2 to quit'
while 1:
    choice = raw_input('> ')
    if choice == '1':
        print 'slime mould'
    elif choice == '2':
        print 'bye!'
        break
    else:
        print "That's not a 1 or 2 :)"

  HTH,
  Glen

----- Original Message -----
From: "Oliverio Sierra" <oliveriosierra@hotmail.com>
To: <tutor@python.org>
Sent: Monday, December 31, 2001 5:09 PM
Subject: [Tutor] need a little help


> hi, i just downloaded and started studying python a few days ago. it's
also
> the first language i have studied. i am currently writing my first
> semi-complicated(at least for me) program and i hit a dead end.  my
program
> goes a little like this:
>
> -there is a menu with 3 choices
> -then a user = input() statement
> -then an if, 2 elif, and an else statements
>
> i can go into any of the 3 choices, but only once. i need to be able to go
> into them several times. i have read everything i could find on the net,
but
> had no succes.  i know there is a way for the program to cycle back to
where
> my user = input() statement is.  i apreshiate your help and time. thank
you.
>
> _________________________________________________________________
> Hable con sus amigos en línea, pruebe MSN Messenger:
http://messenger.msn.es
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From shalehperry@attbi.com  Mon Dec 31 18:29:45 2001
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 31 Dec 2001 10:29:45 -0800 (PST)
Subject: [Tutor] need a little help
In-Reply-To: <F1264upgNECPkGSXkIa0000e9a5@hotmail.com>
Message-ID: <XFMail.20011231102945.shalehperry@attbi.com>

On 31-Dec-2001 Oliverio Sierra wrote:
> hi, i just downloaded and started studying python a few days ago. it's also 
> the first language i have studied. i am currently writing my first 
> semi-complicated(at least for me) program and i hit a dead end.  my program 
> goes a little like this:
> 
> -there is a menu with 3 choices
> -then a user = input() statement
> -then an if, 2 elif, and an else statements
> 
> i can go into any of the 3 choices, but only once. i need to be able to go 
> into them several times. i have read everything i could find on the net, but 
> had no succes.  i know there is a way for the program to cycle back to where 
> my user = input() statement is.  i apreshiate your help and time. thank you.
> 

this is called a loop.  There are two different kinds of loops in python.

the 'for' loop loops over a sequence of values.

for line in readlines():
    process_input(line)

would call process_input() once for each item in readlines().  The item from
readlines() is stored in the temporary variable 'line'.

the other loop structure is the 'while' loop.  This is just like an if, except
it loops.

end_point = 30

while 1: # loop forever
   val = do_something()
   if val == end_point: break # until we reach an end

this style is common in input situations.

Another is 'while not done:' where done is set to zero initially and then to 1
at some condition in the loop.


From dsh8290@rit.edu  Mon Dec 31 18:41:57 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 31 Dec 2001 13:41:57 -0500
Subject: [Tutor] Building Python Source with Cygwin?
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C21B@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C21B@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20011231184157.GA5155@localhost>

On Mon, Dec 31, 2001 at 02:10:59PM +0000, alan.gauld@bt.com wrote:
 
| > wondering if I can now take any related source (SWIG, Jython, 
| > etc...) from anywhere and build it on my Win2K box or partition.  
| 
| Thats the idea, once you get the LD-LIB paths and other config 
| bits sorted out it should build fairly seamlessly, although 
| I've not tried anything non-trivial yet myself.

I haven't built any python stuff with cygwin (too bad there isn't a
python-dev package, that would certainly make it easier), but I have
built glib, gtk+, and gvim (with GTK+) on cygwin (with XFree86)
without difficulty.

-D

-- 

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.

    Proverbs 6:16-19



From jimajima9@yahoo.com  Mon Dec 31 18:50:42 2001
From: jimajima9@yahoo.com (Jim Angstadt)
Date: Mon, 31 Dec 2001 10:50:42 -0800 (PST)
Subject: Divide function (was: Re: [Tutor] wxPython? (fwd))
In-Reply-To: <Pine.LNX.4.21.0112311010200.22581-100000@hkn.eecs.berkeley.edu>
Message-ID: <20011231185042.85993.qmail@web14003.mail.yahoo.com>

Just a newbie thought:

The results below seem consistent with 
integer division using a 'floor' approach.

--- Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:

<snip>

> from Numeric import *
> 
> def divide(x,y):
>     return x/y
> 
> for y in range(-10,10,1):
>     x=2
>     try:
>         print divide(x,y), y
>         
>     except ZeroDivisionError:
>         print "You are trying to divide by zero"
>     
> ----------------
> 
> -1 -10
> -1 -9
> -1 -8
> -1 -7
> -1 -6
> -1 -5
> -1 -4
> -1 -3
> -1 -2
> -2 -1
> You are trying to divide by zero
> 2 1
> 1 2
> 0 3
> 0 4
> 0 5
> 0 6
> 0 7
> 0 8
> 0 9
> ------------------------------
> Why x/y gives wrong results?

<snip> 


=====
Regards,
Jim

__________________________________________________
Do You Yahoo!?
Send your FREE holiday greetings online!
http://greetings.yahoo.com


From tjenkins@devis.com  Mon Dec 31 19:00:40 2001
From: tjenkins@devis.com (Tom Jenkins)
Date: 31 Dec 2001 14:00:40 -0500
Subject: [Tutor] Integer division (was wxPython? (fwd))
In-Reply-To: <Pine.LNX.4.21.0112311010200.22581-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.21.0112311010200.22581-100000@hkn.eecs.berkeley.edu>
Message-ID: <1009825241.4244.9.camel@asimov>

Hey Karshi,
These results are consistent with the notion of integer division.

int/int will return an int
int/float will return a float
float/int will return a float

so

2/8 = 0 with remainder of .25

2/-10 = 0 with remainder of -.2

now python will round down the remainders so

2/8 = 0
2/-10 = -1

Now this will change with python 2.2, I believe
int/int will return a float
float/float will return a float

if you want to your divide to return a float then you can change it to:
def divide(x,y):
  return float(x)/y

or alternatively:
def divide(x,y):
  return divmod(x,y)[0]


On Mon, 2001-12-31 at 13:16, Danny Yoo wrote:
> Hi Karshi,
> 
> Let me forward this to the rest of Tutor.  I hate saying this, but I
> can't reproduce the wackiness.
> 
> The only thing I can think that of that can trigger this behavior is if
> divide() itself was defined as:
> 
> ###
> def divide(x,y):
>     return x
> ###
> 
> But then, I might not be considering some strange side effect.  Can you
> check to see if this is what's happening?  Also, what version of Python
> are you using?
> 
> 
> 
> ---------- Forwarded message ----------
> Date: Mon, 31 Dec 2001 09:13:45 -0500
> From: Karshi <karshi.hasanov@utoronto.ca>
> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] wxPython?
> 
> Hi Danny,
> Can you tell me why I am getting the strange results here:
> 
> from Numeric import *
> 
> def divide(x,y):
>     return x/y
> 
> for y in range(-10,10,1):
>     x=2
>     try:
>         print divide(x,y), y
>         
>     except ZeroDivisionError:
>         print "You are trying to divide by zero"
>     
> ----------------
> 
> -1 -10
> -1 -9
> -1 -8
> -1 -7
> -1 -6
> -1 -5
> -1 -4
> -1 -3
> -1 -2
> -2 -1
> You are trying to divide by zero
> 2 1
> 1 2
> 0 3
> 0 4
> 0 5
> 0 6
> 0 7
> 0 8
> 0 9
> ------------------------------
> Why x/y gives wrong results?
> 
> 
> On Tuesday 25 December 2001 02:32 pm, you wrote:
> > On Mon, 24 Dec 2001, Karshi Hasanov wrote:
> > >  I wanna use python GUI's , like wxPython or Tkinter.
> > > Which one would be easy to learn, or what 's advantage of using wxPython
> > > than Tkinter?
> >
> > Both are pretty nice.  I think that Tkinter is easier to learn, but many
> > people feel that Tkinter looks ugly.  *grin*
> >
> >
> > Tkinter is also installed by default when we install Python, so it's used
> > quite a lot.  Have you seen Fredrik Lungh's 'An Introduction to Tkinter'
> > web site?
> >
> >     http://www.pythonware.com/library/tkinter/introduction/
> >
> > It's a great tutorial on Tkinter programming.  Take a look at it, and see
> > if Tkinter is a good fit.
> >
> > Good luck!
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 

Tom Jenkins
Development InfoStructure
http://www.devis.com




From kev@sat.net  Mon Dec 31 19:15:28 2001
From: kev@sat.net (Kevin McCormick)
Date: Mon, 31 Dec 2001 13:15:28 -0600
Subject: [Tutor] exception classes
Message-ID: <3C30B950.6040101@sat.net>

I am trying to figure out how to design an exception class so that my 
class / module can handle errors nicely.  What material I have found 
doesn't really explain it for me.  Can anyone give a brief explanation 
or directions to good explanations?
Thanks



From dyoo@hkn.eecs.berkeley.edu  Mon Dec 31 19:56:33 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 31 Dec 2001 11:56:33 -0800 (PST)
Subject: Divide function (was: Re: [Tutor] wxPython? (fwd))
In-Reply-To: <20011231185042.85993.qmail@web14003.mail.yahoo.com>
Message-ID: <Pine.LNX.4.21.0112311155040.24118-100000@hkn.eecs.berkeley.edu>

On Mon, 31 Dec 2001, Jim Angstadt wrote:

> Just a newbie thought:
> 
> The results below seem consistent with integer division using a
> 'floor' approach.

You're right!  What the heck was I thinking?  Thanks for catching me.



From moreno.rivilla@gmx.net  Mon Dec 31 20:14:23 2001
From: moreno.rivilla@gmx.net (Francisco Moreno Rivilla)
Date: Mon, 31 Dec 2001 21:14:23 +0100
Subject: [Tutor] ERROR using "BuildApplication"
Message-ID: <B8567101.26F2%moreno.rivilla@gmx.net>

hi all,
I=B4m a newbee, I=B4ve just writtem my first MAC-app. ("Hello World"), but I
cant compile it; using "BuildApplication" I always get the following
ERROR-message:

-----------------------------
Searching for modules...
Traceback (most recent call last):
  File "Online:Programme:Python 2.2:Mac:scripts:BuildApplication.py", line
141, in ?
    main()
  File "Online:Programme:Python 2.2:Mac:scripts:BuildApplication.py", line
46, in main
    buildapplication()
  File "Online:Programme:Python 2.2:Mac:scripts:BuildApplication.py", line
81, in buildapplication
    macgen_bin.generate(filename, dstfilename, None, architecture, 1)
  File "Online:Programme:Python 2.2:Mac:Tools:macfreeze:macgen_bin.py", lin=
e
26, in generate
    module_dict, missing =3D macmodulefinder.process(input, [], [], 1)
  File "Online:Programme:Python 2.2:Mac:Tools:macfreeze:macmodulefinder.py"=
,
line 85, in process
    modfinder.import_hook(m)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 134=
,
in import_hook
    q, tail =3D self.find_head_package(parent, name)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 175=
,
in find_head_package
    q =3D self.import_module(head, qname, parent)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 261=
,
in import_module
    m =3D self.load_module(fqname, fp, pathname, stuff)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 291=
,
in load_module
    self.scan_code(co, m)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 336=
,
in scan_code
    self.scan_code(c, m)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 336=
,
in scan_code
    self.scan_code(c, m)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 311=
,
in scan_code
    self.import_hook(name, m)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 134=
,
in import_hook
    q, tail =3D self.find_head_package(parent, name)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 175=
,
in find_head_package
    q =3D self.import_module(head, qname, parent)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 261=
,
in import_module
    m =3D self.load_module(fqname, fp, pathname, stuff)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 291=
,
in load_module
    self.scan_code(co, m)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 336=
,
in scan_code
    self.scan_code(c, m)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 311=
,
in scan_code
    self.import_hook(name, m)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 134=
,
in import_hook
    q, tail =3D self.find_head_package(parent, name)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 175=
,
in find_head_package
    q =3D self.import_module(head, qname, parent)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 261=
,
in import_module
    m =3D self.load_module(fqname, fp, pathname, stuff)
  File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 276=
,
in load_module
    co =3D compile(fp.read()+'\n', pathname, 'exec')
MemoryError
------------------------------------

Please help me! I=B4m working on an i-MAC G3/233 160MB RAM, OS 8.6 and PYTHON
2.2
I=B4ve read in the spanish MACWORLD that you cant build standalone-apps with
Python, you always need to compile with CODEWARRIER... true?
--
Francisco
Barcelona
Espa=F1a=20




From dsh8290@rit.edu  Mon Dec 31 22:25:11 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 31 Dec 2001 17:25:11 -0500
Subject: [Tutor] ERROR using "BuildApplication"
In-Reply-To: <B8567101.26F2%moreno.rivilla@gmx.net>
References: <B8567101.26F2%moreno.rivilla@gmx.net>
Message-ID: <20011231222511.GB6385@localhost>

On Mon, Dec 31, 2001 at 09:14:23PM +0100, Francisco Moreno Rivilla wrote:
| hi all,
| I´m a newbee, I´ve just writtem my first MAC-app. ("Hello World"), but I
| cant compile it; using "BuildApplication" I always get the following
| ERROR-message:

Python is interpreted.  You don't compile it.

| Please help me! I´m working on an i-MAC G3/233 160MB RAM, OS 8.6 and
| PYTHON 2.2

| I´ve read in the spanish MACWORLD that you cant build standalone-apps with
| Python, you always need to compile with CODEWARRIER... true?

You can build packages or installers to assist in shipping your app to
people who don't have python already installed.  There are a few
(immature) projects to try and convert python source to native machine
code, but I don't recommend attempting to use these until you are
familiar with both python and C and the intracicies of compiling
non-trivial applications.  I would also be surprised if CodeWarrior
could compile a python program.

Are you using MacOS X?  If so then that should be the easiest to work
with.  Just open a shell (eg tcsh or bash) and type "python".  If that
works you can follow unix instructions for running your programs (you
know that OSX is a unix system with a macintosh gui).  If you are
using any other MacOS (or don't want to get into shells on OSX) then
you need to check with some Mac people to learn how to run python
programs.  I haven't touched a Mac in ages and have never administered
one myself.

HTH,
-D

-- 

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.

    Proverbs 6:16-19



From dsh8290@rit.edu  Mon Dec 31 22:27:55 2001
From: dsh8290@rit.edu (dman)
Date: Mon, 31 Dec 2001 17:27:55 -0500
Subject: [Tutor] exception classes
In-Reply-To: <3C30B950.6040101@sat.net>
References: <3C30B950.6040101@sat.net>
Message-ID: <20011231222755.GC6385@localhost>

On Mon, Dec 31, 2001 at 01:15:28PM -0600, Kevin McCormick wrote:
| I am trying to figure out how to design an exception class so that my 
| class / module can handle errors nicely.  What material I have found 
| doesn't really explain it for me.  Can anyone give a brief explanation 
| or directions to good explanations?

What does your exception need to be able to do and what info does it
need to store?  The following is a minimal example :

# first define the class
class MyException( Exception ) :
    pass


# now somewhere else we can raise it if need be
def my_func() :
    # this should only be done in case of an error,
    # in this example an error always occurs
    raise MyException()


# now use the function that might raise an exception, _and_ handle
# that situaiton
try :
    my_func()
except MyException , err :
    print "Whoa, an exception was raised"
    print err



HTH,
-D

-- 

A)bort, R)etry, B)ang it with a large hammer



From dan@gui.com  Mon Dec 31 22:26:23 2001
From: dan@gui.com (Dan Shafer)
Date: Mon, 31 Dec 2001 14:26:23 -0800
Subject: [Tutor] ERROR using "BuildApplication"
In-Reply-To: <B8567101.26F2%moreno.rivilla@gmx.net>
References: <B8567101.26F2%moreno.rivilla@gmx.net>
Message-ID: <a0510031db85696560703@[63.205.23.218]>

At 9:14 PM +0100 12/31/01, Francisco Moreno Rivilla wrote:
>hi all,
>I=B4m a newbee, I=B4ve just writtem my first MAC-app. ("Hello World"), but =
I
>cant compile it; using "BuildApplication" I always get the following
>ERROR-message:

Since you're getting a memory error, my guess is you need to increase 
the amount of memory in Finder that you've allocated to 
BuildApplication. That's just a guess, though.

>-----------------------------
>Searching for modules...
>Traceback (most recent call last):
>   File "Online:Programme:Python 2.2:Mac:scripts:BuildApplication.py", line
>141, in ?
>     main()
>   File "Online:Programme:Python 2.2:Mac:scripts:BuildApplication.py", line
>46, in main
>     buildapplication()
>   File "Online:Programme:Python 2.2:Mac:scripts:BuildApplication.py", line
>81, in buildapplication
>     macgen_bin.generate(filename, dstfilename, None, architecture, 1)
>   File "Online:Programme:Python 2.2:Mac:Tools:macfreeze:macgen_bin.py", li=
ne
>26, in generate
>     module_dict, missing =3D macmodulefinder.process(input, [], [], 1)
>   File "Online:Programme:Python 2.2:Mac:Tools:macfreeze:macmodulefinder.py=
",
>line 85, in process
>     modfinder.import_hook(m)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 13=
4,
>in import_hook
>     q, tail =3D self.find_head_package(parent, name)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 17=
5,
>in find_head_package
>     q =3D self.import_module(head, qname, parent)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 26=
1,
>in import_module
>     m =3D self.load_module(fqname, fp, pathname, stuff)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 29=
1,
>in load_module
>     self.scan_code(co, m)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 33=
6,
>in scan_code
>     self.scan_code(c, m)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 33=
6,
>in scan_code
>     self.scan_code(c, m)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 31=
1,
>in scan_code
>     self.import_hook(name, m)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 13=
4,
>in import_hook
>     q, tail =3D self.find_head_package(parent, name)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 17=
5,
>in find_head_package
>     q =3D self.import_module(head, qname, parent)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 26=
1,
>in import_module
>     m =3D self.load_module(fqname, fp, pathname, stuff)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 29=
1,
>in load_module
>     self.scan_code(co, m)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 33=
6,
>in scan_code
>     self.scan_code(c, m)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 31=
1,
>in scan_code
>     self.import_hook(name, m)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 13=
4,
>in import_hook
>     q, tail =3D self.find_head_package(parent, name)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 17=
5,
>in find_head_package
>     q =3D self.import_module(head, qname, parent)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 26=
1,
>in import_module
>     m =3D self.load_module(fqname, fp, pathname, stuff)
>   File "Online:Programme:Python 2.2:Tools:freeze:modulefinder.py", line 27=
6,
>in load_module
>     co =3D compile(fp.read()+'\n', pathname, 'exec')
>MemoryError
>------------------------------------
>
>Please help me! I=B4m working on an i-MAC G3/233 160MB RAM, OS 8.6 and PYTH=
ON
>2.2
>I=B4ve read in the spanish MACWORLD that you cant build standalone-apps wit=
h
>Python, you always need to compile with CODEWARRIER... true?
>--
>Francisco
>Barcelona
>Espa=F1a


-- 
Dan Shafer, Author-Consultant
http://www.danshafer.com
http://www.shafermedia.com


From thomi@thomi.imail.net.nz  Mon Dec 31 11:35:55 2001
From: thomi@thomi.imail.net.nz (Thomi Richards)
Date: Tue, 1 Jan 2002 00:35:55 +1300
Subject: [Tutor] extramural papers in python??
Message-ID: <20020101003555.57c5e2f8.thomi@thomi.imail.net.nz>

can anyone recommend a university which runs a programming paper, using
python?? I'm looking to take one or more papers extramuraly, to complete
my degree.

thanks.

-- 
The software required Win95 or better, so I installed Linux.
Thomi Richards,
thomi@imail.net.nz