From cspears2002 at yahoo.com  Tue Aug  1 00:29:13 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Mon, 31 Jul 2006 15:29:13 -0700 (PDT)
Subject: [Tutor] syntax error
Message-ID: <20060731222913.40214.qmail@web51615.mail.yahoo.com>

My brain has gone squishy.  I am combining a linked
list with a priority queue.  This is the last exercise
out of How To Think Like A Computer Scientist (Chapter
19).


class Node:
	def __init__(self, cargo=None, next=None):
		self.cargo = cargo
		self.next = next
		
	def __str__(self):
		return str(self.cargo)

class ImprovedQueue:
	def __init__(self):
		self.length = 0
		self.head   = None
		self.last   = None

	def isEmpty(self):
		return (self.length == 0) 
    
	def insert(self, cargo):
		node = Node(cargo)
		node.next = None
		if self.length == 0:
			# if list is empty, the new node is head and last
			self.head = self.last = node
		elif node.cargo > self.head.cargo:
			node.next = self.head
			self.head = node
		else node.cargo <= self.head.cargo:
			self.last.next = node
			self.last = node
		self.length = self.length + 1
		
	
	def remove(self):
    		cargo = self.head.cargo
    		self.head = self.head.next
    		self.length = self.length - 1
    		if self.length == 0:
			self.last = None
		return cargo

Here is the error message:
>>> from linkedPriorityQueue import *
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "linkedPriorityQueue.py", line 27
    else node.cargo <= self.head.cargo:
            ^
SyntaxError: invalid syntax

I am not sure what this means.  Everything is spelled
correctly.

-Chris
 


From john at fouhy.net  Tue Aug  1 00:34:59 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 1 Aug 2006 10:34:59 +1200
Subject: [Tutor] syntax error
In-Reply-To: <20060731222913.40214.qmail@web51615.mail.yahoo.com>
References: <20060731222913.40214.qmail@web51615.mail.yahoo.com>
Message-ID: <5e58f2e40607311534q4a60581coe04469fede08f1fa@mail.gmail.com>

On 01/08/06, Christopher Spears <cspears2002 at yahoo.com> wrote:
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>  File "linkedPriorityQueue.py", line 27
>    else node.cargo <= self.head.cargo:
>            ^
> SyntaxError: invalid syntax
>
> I am not sure what this means.  Everything is spelled
> correctly.

An 'else' clause doesn't take a condition.  The general shape of an if
statement is:

if [condition]:
    do something
elif [another condition]:
    do something else
else:
    do other things

The 'else' clause is the catchall for anything that doesn't match one
of the preceding conditions, so it doesn't have its own condition.

What I often like to do is to use a comment to indicate what is true
in the 'else' branch.  eg:

               else:  # node.cargo <= self.head.cargo
                       self.last.next = node
                       self.last = node

HTH!

-- 
John.

From alan.gauld at freenet.co.uk  Tue Aug  1 00:43:11 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 31 Jul 2006 23:43:11 +0100
Subject: [Tutor] syntax error
References: <20060731222913.40214.qmail@web51615.mail.yahoo.com>
Message-ID: <000e01c6b4f2$b44a95b0$0201a8c0@XPpro>


> My brain has gone squishy.  

:-)  I know the feeling...

> Here is the error message:
>>>> from linkedPriorityQueue import *
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>  File "linkedPriorityQueue.py", line 27
>    else node.cargo <= self.head.cargo:
>            ^
> SyntaxError: invalid syntax

else:

or 

elif condition:

but not 

else condition:

HTH,

Alan G.


From Barry.Carroll at psc.com  Tue Aug  1 00:58:32 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Mon, 31 Jul 2006 15:58:32 -0700
Subject: [Tutor] syntax error
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36EF@eugsrv400.psc.pscnet.com>

Hello Chris,

> -----Original Message-----
> Date: Mon, 31 Jul 2006 15:29:13 -0700 (PDT)
> From: Christopher Spears <cspears2002 at yahoo.com>
> Subject: [Tutor] syntax error
> To: tutor at python.org
> Message-ID: <20060731222913.40214.qmail at web51615.mail.yahoo.com>
> Content-Type: text/plain; charset=iso-8859-1
> 
> My brain has gone squishy.  I am combining a linked
> list with a priority queue.  This is the last exercise
> out of How To Think Like A Computer Scientist (Chapter
> 19).
> 
<<snip>>
> 
> 	def insert(self, cargo):
> 		node = Node(cargo)
> 		node.next = None
> 		if self.length == 0:
> 			# if list is empty, the new node is head and
last
> 			self.head = self.last = node
> 		elif node.cargo > self.head.cargo:
> 			node.next = self.head
> 			self.head = node
> 		else node.cargo <= self.head.cargo:
> 			self.last.next = node
> 			self.last = node
> 		self.length = self.length + 1
> 
<<snip>>
> 
> Here is the error message:
> >>> from linkedPriorityQueue import *
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "linkedPriorityQueue.py", line 27
>     else node.cargo <= self.head.cargo:
>             ^
> SyntaxError: invalid syntax
> 
> I am not sure what this means.  Everything is spelled
> correctly.
> 
> -Chris
> 

The syntax error occurs just after the "else".  Unlike "if" and "elif",
"else" does not take an expression. It covers any cases left over after
the "if" clause and all of the "elif" clauses have been tried and
failed.  The expression "node.cargo <= self.head.cargo" is therefore
logically unnecessary. Python (and all other programming languages I
know of) enforces this by making it illegal to put an expression in an
"else" clause.   

I don't have access to "How To Think Like A Computer Scientist", so I
can't point you to the section that discusses this, but I'm sure it's in
there somewhere.  Look in the index for "else clause", "if-elif-else
statement" or some entry like that.  

HTH.

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

-Quarry worker's creed



From justin.mailinglists at gmail.com  Tue Aug  1 05:03:12 2006
From: justin.mailinglists at gmail.com (Justin Ezequiel)
Date: Tue, 1 Aug 2006 11:03:12 +0800
Subject: [Tutor] question about headers and smtplib
Message-ID: <3c6718980607312003w7ba84d31q74c5f4b51b7aaee8@mail.gmail.com>

When I first started with Python, I used MimeWriter to create E-mails.

Then some mail servers rejected my E-mails.

Some research (google) indicated (to me) that I needed a MIME-Version header.
(Can't recall now if I also needed a Content-Type header.)

Anyway, more research (Python docs) indicated that I should use the
email package instead.
I have been doing so since and have not had reports of anymore rejected E-mails.

Hope this helps.

>>> import email
>>> from email.MIMENonMultipart import MIMENonMultipart
>>> from email.Utils import formataddr
>>> format_addresses = lambda pairs: ', '.join([formataddr(pair) for
pair in pairs])
>>> msg = MIMENonMultipart('text', 'plain', charset='us-ascii')
>>> msg.set_payload('Foo Bar')
>>> msg.add_header('From', formataddr(('Justin', 'a at b.com')))
>>> msg.add_header('To', format_addresses([('Justin', 'a at b.com'),
('You', 'c at e.com')]))
>>> print msg.as_string()
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
From: Justin <a at b.com>
To: Justin <a at b.com>, You <c at e.com>

Foo Bar
>>>

From noufal at nibrahim.net.in  Tue Aug  1 07:52:35 2006
From: noufal at nibrahim.net.in (Noufal Ibrahim)
Date: Tue, 1 Aug 2006 11:22:35 +0530 (IST)
Subject: [Tutor] Debugging multithreaded programs in python
Message-ID: <26963.61.16.169.181.1154411555.squirrel@members.hcoop.net>

Greetings all,
    A friend here is trying to debug a rather badly written python program
which spawns off lots of threads here and there.  Are there any
frameworks that I can reccommend that would ease his pain?

    On a more general note, it seems rather strange that I can't quickly
google and find a debugger for multithreaded python programs. Python's
"batteries included" philosophy has always been very useful to me.
I've always managed to find what I need without any hassles. This is
the first exception. Any insights? Are there any decent ways to debug
a multi threaded program which make a debugger redundant?

Peace.
-- 
-NI


From kent37 at tds.net  Tue Aug  1 12:19:22 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 01 Aug 2006 06:19:22 -0400
Subject: [Tutor] Debugging multithreaded programs in python
In-Reply-To: <26963.61.16.169.181.1154411555.squirrel@members.hcoop.net>
References: <26963.61.16.169.181.1154411555.squirrel@members.hcoop.net>
Message-ID: <44CF2AAA.9010300@tds.net>

Noufal Ibrahim wrote:
> Greetings all,
>     A friend here is trying to debug a rather badly written python program
> which spawns off lots of threads here and there.  Are there any
> frameworks that I can reccommend that would ease his pain?
>   
winpdb claims to debug multi-threaded programs. I have found it useful 
for single-threaded programs, haven't tried it for m-t.
http://www.digitalpeers.com/pythondebugger/

Debugging m-t programs can be very hard. Placing a breakpoint can change 
the timing so a bug doesn't appear, or ruin a critical response time. 
Print statements can help.

You say the program is badly written, if it uses more threads than 
needed maybe the first step is to get rid of some of them. You could 
also look for subsystems that could be tested independently, perhaps 
using unittest.

Kent


From nephish at gmail.com  Tue Aug  1 21:29:13 2006
From: nephish at gmail.com (shawn bright)
Date: Tue, 1 Aug 2006 15:29:13 -0400
Subject: [Tutor] question about headers and smtplib
In-Reply-To: <3c6718980607312003w7ba84d31q74c5f4b51b7aaee8@mail.gmail.com>
References: <3c6718980607312003w7ba84d31q74c5f4b51b7aaee8@mail.gmail.com>
Message-ID: <384c93600608011229x4a8703efu89fc7311d1f2cb64@mail.gmail.com>

OK, this worked, please disregard my last. The online docs at
python.orgtold me the answer to that one. Between their example and
yours, i am able
to make it work.
thanks a whole bunch !

shawn

On 7/31/06, Justin Ezequiel <justin.mailinglists at gmail.com> wrote:
>
> When I first started with Python, I used MimeWriter to create E-mails.
>
> Then some mail servers rejected my E-mails.
>
> Some research (google) indicated (to me) that I needed a MIME-Version
> header.
> (Can't recall now if I also needed a Content-Type header.)
>
> Anyway, more research (Python docs) indicated that I should use the
> email package instead.
> I have been doing so since and have not had reports of anymore rejected
> E-mails.
>
> Hope this helps.
>
> >>> import email
> >>> from email.MIMENonMultipart import MIMENonMultipart
> >>> from email.Utils import formataddr
> >>> format_addresses = lambda pairs: ', '.join([formataddr(pair) for
> pair in pairs])
> >>> msg = MIMENonMultipart('text', 'plain', charset='us-ascii')
> >>> msg.set_payload('Foo Bar')
> >>> msg.add_header('From', formataddr(('Justin', 'a at b.com')))
> >>> msg.add_header('To', format_addresses([('Justin', 'a at b.com'),
> ('You', 'c at e.com')]))
> >>> print msg.as_string()
> Content-Type: text/plain; charset="us-ascii"
> MIME-Version: 1.0
> From: Justin <a at b.com>
> To: Justin <a at b.com>, You <c at e.com>
>
> Foo Bar
> >>>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060801/76e51ec3/attachment.html 

From cspears2002 at yahoo.com  Wed Aug  2 00:27:29 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Tue, 1 Aug 2006 15:27:29 -0700 (PDT)
Subject: [Tutor] When am I ever going to use this?
Message-ID: <20060801222729.62964.qmail@web51605.mail.yahoo.com>

I've been working through a tutorial:
http://www.ibiblio.org/obp/thinkCSpy/index.htm. 
Lately, I have been learning about abstract data types
(linked lists, stacks, queues, trees, etc.).  While I
do enjoy the challenge of creating these objects, I am
not sure what they are used for.


From jordangreenberg at gmail.com  Wed Aug  2 01:13:15 2006
From: jordangreenberg at gmail.com (Jordan Greenberg)
Date: Tue, 01 Aug 2006 19:13:15 -0400
Subject: [Tutor] When am I ever going to use this?
In-Reply-To: <20060801222729.62964.qmail@web51605.mail.yahoo.com>
References: <20060801222729.62964.qmail@web51605.mail.yahoo.com>
Message-ID: <44CFE00B.2050005@gmail.com>

Christopher Spears wrote:
> I've been working through a tutorial:
> http://www.ibiblio.org/obp/thinkCSpy/index.htm. 
> Lately, I have been learning about abstract data types
> (linked lists, stacks, queues, trees, etc.).  While I
> do enjoy the challenge of creating these objects, I am
> not sure what they are used for.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

They all have many uses. Priority Queues are used frequently in
operating systems for process scheduling, etc. Trees are fantastic for
most any searching application. Linked lists can be used for general
purpose storage (since unlike arrays, their size is not fixed.)

Learning data structures is really the one thing i wouldn't recommend
python for, just because the job is usually done for you. Why implement
a linked list, when we already have lists? Then Queues and Stacks are
trivial to implement once you've got lists.

If you're interested in learning more about data structures and their
uses, this looks like a good reference:
http://www.brpreiss.com/books/opus7/

-Jordan Greenberg


From dyoo at hkn.eecs.berkeley.edu  Wed Aug  2 05:19:37 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 1 Aug 2006 20:19:37 -0700 (PDT)
Subject: [Tutor] When am I ever going to use this?
In-Reply-To: <20060801222729.62964.qmail@web51605.mail.yahoo.com>
References: <20060801222729.62964.qmail@web51605.mail.yahoo.com>
Message-ID: <Pine.LNX.4.64.0608011604310.25719@hkn.eecs.berkeley.edu>



On Tue, 1 Aug 2006, Christopher Spears wrote:

> I've been working through a tutorial: 
> http://www.ibiblio.org/obp/thinkCSpy/index.htm. Lately, I have been 
> learning about abstract data types (linked lists, stacks, queues, trees, 
> etc.).  While I do enjoy the challenge of creating these objects, I am 
> not sure what they are used for.

Hi Chris,

Let say that we are trying to write a navigator program, one that helps 
plan road trips.  One portion of the input to this program would be a map 
of the roads.

For example:

     map = [('a', 'b'),
            ('a', 'c'),
            ('c', 'f'),
            ('b', 'd'),
            ('d', 'e'),
            ('d', 'f')]

might represent the following street map:

     a ------ b
     |        |
     |        |
     c        d ------ e
      \       |
       \      |
        ----- f

where 'a', 'b', 'c', 'd', 'e', and 'f' are points of interest.  (I'm 
oversimplifying, but I hope you don't mind!)


A simple question we might ask this system is: how far is it from point 
'a' to point 'f'?  We'd like to ask the system:

     distance('a', 'f', map)

and be able to get 2, since there's a hop from 'a' to 'c', and from 'c' to 
'f'.

This problem is ripe to be attacked with an algorithm called 
"breadth-first search", and breadth-first search typically is implemented 
by keeping a queue of places.  We can talk about this in more detail if 
you'd like.

     http://en.wikipedia.org/wiki/Breadth-first_search


This is a long hand-wavy example for a short explanation: queues and and 
other data structures are "background" support tools: they themselves 
aren't so interesting, but they're the tools that a programmer often will 
reach for when working on non-string related problems.



If you remember Starcraft: there was a four-level queue of movement 
commands that you could set up by holding "shift" while navigating your 
forces.  You could also "queue" up production orders in factories.

Same data structure.  *grin*


Best of wishes!

From marc_a_poulin at yahoo.com  Wed Aug  2 05:58:40 2006
From: marc_a_poulin at yahoo.com (Marc Poulin)
Date: Tue, 1 Aug 2006 20:58:40 -0700 (PDT)
Subject: [Tutor] When am I ever going to use this?
In-Reply-To: <20060801222729.62964.qmail@web51605.mail.yahoo.com>
Message-ID: <20060802035840.14836.qmail@web34114.mail.mud.yahoo.com>

--- Christopher Spears <cspears2002 at yahoo.com> wrote:

> I've been working through a tutorial:
> http://www.ibiblio.org/obp/thinkCSpy/index.htm. 
> Lately, I have been learning about abstract data
> types
> (linked lists, stacks, queues, trees, etc.).  While
> I
> do enjoy the challenge of creating these objects, I
> am
> not sure what they are used for.
> 

You probably use a linked list every day and don't
even know it.

Do you ever hit the "Back" button on your web browser
to return to previous pages? The browser keeps a list
of the pages you've visited, all linked together, so
you can move backwards and forwards through the list.

Here is a great resource for learning about different
kinds of data structures:

http://www.nist.gov/dads

Regards,
Marc

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

From arcege at gmail.com  Wed Aug  2 15:45:35 2006
From: arcege at gmail.com (Michael P. Reilly)
Date: Wed, 2 Aug 2006 09:45:35 -0400
Subject: [Tutor] When am I ever going to use this?
In-Reply-To: <20060801222729.62964.qmail@web51605.mail.yahoo.com>
References: <20060801222729.62964.qmail@web51605.mail.yahoo.com>
Message-ID: <7e5ba9220608020645t1d4d555ao9be367162d483ef6@mail.gmail.com>

On 8/1/06, Christopher Spears <cspears2002 at yahoo.com> wrote:
>
> I've been working through a tutorial:
> http://www.ibiblio.org/obp/thinkCSpy/index.htm.
> Lately, I have been learning about abstract data types
> (linked lists, stacks, queues, trees, etc.).  While I
> do enjoy the challenge of creating these objects, I am
> not sure what they are used for.
>

Queues and linked lists are also used extensively inside operating systems.
Process lists are a large collections of queues organized in multiple queues
implemented as linked lists and stored in one array.  File systems store
files by accessing data blocks through linked "blocks" (not quite the same
as your linked node structure) and access to the disks and the network are
through queues.  Trees are used less often, but still very useful.  The
directory structure (folders and files) on your disk are trees, the program
to search your email may use a tree.  Stacks are often used for network
protocols and program execution (every time you call a function, you are
pushing something onto a stack).

How about real life uses for these structures.  Queues are one of the most
natural structures from social life brought into computer science.  Insects,
banks, highways, birds, even the lunch line in grade school used queues.
Stacks are the next, with stacks of books, papers, etc.  Trees are used for
people's genealogies.  And you might used a linked list in a treasure hunt
or for footnotes and bibliographies.  Even post-it notes are a form of
mental linked list.

I hope this helps your understanding.
  -Arcege
-- 
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060802/b9d27cd0/attachment.html 

From RPhillips at engineer.co.summit.oh.us  Wed Aug  2 19:33:34 2006
From: RPhillips at engineer.co.summit.oh.us (Ron Phillips)
Date: Wed, 02 Aug 2006 13:33:34 -0400
Subject: [Tutor] Update BLOB with odbc
Message-ID: <44D0A9BD.0345.0006.0@engineer.co.summit.oh.us>

It must be easier than I am making it. 

--------------------
            sql = "UPDATE sa2.outfalls SET photo_content = %s WHERE
pppoint_id ='"+record[0].strip()+"';"
            newsql = sql%pstuff
            print newsql[:150]
            cursor.execute(newsql)
______________
the print newsql[:150] => "UPDATE sa2.outfalls SET photo_content =
????*EExif . . . "

and I get this error:

TypeError: argument 1 must be string without null bytes, not str

which sounds reasonable, but I don't know how to fix it. Is there some
escape thing that I'm missing?

Ron


 
 

From anilmrn at yahoo.com  Wed Aug  2 21:22:19 2006
From: anilmrn at yahoo.com (anil maran)
Date: Wed, 2 Aug 2006 12:22:19 -0700 (PDT)
Subject: [Tutor] latin-1 to unicode in python
Message-ID: <20060802192219.30038.qmail@web55901.mail.re3.yahoo.com>

Unicode?
im getting this error:
invalid byte sequence for encoding "UTF8": 0x92 

since the db is not handling latin-1 and is set to use UTF8 how do i handle this

thanks a lot

 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060802/fc538d18/attachment.htm 

From kent37 at tds.net  Wed Aug  2 21:30:26 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 02 Aug 2006 15:30:26 -0400
Subject: [Tutor] latin-1 to unicode in python
In-Reply-To: <20060802192219.30038.qmail@web55901.mail.re3.yahoo.com>
References: <20060802192219.30038.qmail@web55901.mail.re3.yahoo.com>
Message-ID: <44D0FD52.70305@tds.net>

anil maran wrote:
> Unicode?
> im getting this error:
> invalid byte sequence for encoding "UTF8": 0x92
>
> since the db is not handling latin-1 and is set to use UTF8 how do i 
> handle this

If you have a latin-1 string and you want utf-8, convert it to Unicode 
and then to utf-8 using decode() and encode():

In [1]: s='\x92'

In [3]: s.decode('latin-1').encode('utf-8')
Out[3]: '\xc2\x92'

Kent


From alan.gauld at freenet.co.uk  Wed Aug  2 22:01:46 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 2 Aug 2006 21:01:46 +0100
Subject: [Tutor] When am I ever going to use this?
References: <20060801222729.62964.qmail@web51605.mail.yahoo.com>
Message-ID: <002201c6b66e$7c5ac8a0$0201a8c0@XPpro>

> Lately, I have been learning about abstract data types
> (linked lists, stacks, queues, trees, etc.).  While I
> do enjoy the challenge of creating these objects, I am
> not sure what they are used for.

To be honest, with the possible exception of trees,  not very often!

Most of these data types are taught for historic reasons. Older 
programminng
languages like assembler, C, BASIC, Fortran, Pascal typically only had
arrays(and often only single dimensioned arrays)  for collecting data,
and arrays were either fixed size or had to be explicitly resized in 
blocks
of storage. Thus a whole science grew up in Computing about how to
represent data more abstractly using arrays as the underpinnings.
For example a linked list could be built using 2 identical arrays.
One held the data and the other held the index of the next item,
like this:

index    intList    next
0        42        1
1        27        2
2        66        -1    <-- where -1 indicates end of list...

which was equivalent to a list: 42,27,66

Now we can insert a member between 42 and 27 by adding an item at 
index 3
then modifying the next value for 42 to be 3 and setting the next 
value at 3 to
be 1 - like this:

index    intList    next
0        42        3
1        27        2
2        66        -1    <-- where -1 indicates end of list...
3        99        1

All very convoluted but produced the illusion of a python like list in 
a
language without lists.

But if the language has lists built in, which almost all modern 
languages do,
there is no real need for most of this. You can add features like 
priorities
and auto sorting etc etc, but this is almost trivial in modern 
languages
whereas in old languages it was a lot of work.

And if the language suuppors a dictionary type ijn addition to lists, 
and if
it can store data of moxed types, then you can implement almost any
abstract data collection easily. But the concepts of abstract data 
types
are still taught to an increasingly bewildered audience...

In practice, the average Python programmer can easily simulate or
replace all of the classic data structures with built in types (with 
the
possible exception of trees) or by using a relational database - the 
use
of which wasn't possible in the 60's, 70's and early 80's because
they hadn't been invented yet! Now implementing an RDBMS as part
of a solution is so trivial that there's rarely need to worry about 
bulding
trees etc for fast searches.

That may be a slightly controversial view but it reflects my personal
experience of programming with Python (and Ruby, Tcl, Smalltalk etc)!
Of course if you ever have to use one of the older languages then the
data structure stuff instantly applies again.

HTH,

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


From kent37 at tds.net  Wed Aug  2 22:30:31 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 02 Aug 2006 16:30:31 -0400
Subject: [Tutor] latin-1 to unicode in python
In-Reply-To: <20060802202149.93344.qmail@web55901.mail.re3.yahoo.com>
References: <20060802202149.93344.qmail@web55901.mail.re3.yahoo.com>
Message-ID: <44D10B67.3060401@tds.net>

anil maran wrote:
> In [1]: s='\x92'
>
> In [3]: s.decode('latin-1').encode('utf-8')
>
>
> Out[3]: '\xc2\x92'
>
> is this some kind of python shell, pls clarify
Yes, it's IPython.
http://ipython.scipy.org/

Kent
>
> */Kent Johnson <kent37 at tds.net>/* wrote:
>
>     anil maran wrote:
>     > Unicode?
>     > im getting this error:
>     > invalid byte sequence for encoding "UTF8": 0x92
>     >
>     > since the db is not handling latin-1 and is set to use UTF8 how
>     do i
>     > handle this
>
>     If you have a latin-1 string and you want utf-8, convert it to
>     Unicode
>     and then to utf-8 using decode() and encode():
>
>     In [1]: s='\x92'
>
>     In [3]: s.decode('latin-1').encode('utf-8')
>     Out[3]: '\xc2\x92'
>
>     Kent
>
>     _______________________________________________
>     Tutor maillist - Tutor at python.org
>     http://mail.python.org/mailman/listinfo/tutor
>
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam? Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
>



From kent37 at tds.net  Wed Aug  2 22:39:31 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 02 Aug 2006 16:39:31 -0400
Subject: [Tutor] latin-1 to unicode in python
In-Reply-To: <20060802202100.46710.qmail@web55905.mail.re3.yahoo.com>
References: <20060802202100.46710.qmail@web55905.mail.re3.yahoo.com>
Message-ID: <44D10D83.7050307@tds.net>

anil maran wrote:
> how to determine
> wat encoding it is in
> for eg i m might not know it is in latin-1
This is hard. It is better by far to know what encoding your data is in. 
There is no way to determine for sure what encoding it is by looking at 
the data. The best you can do is rule out some encodings, and make a 
best guess. Here is one way:
http://chardet.feedparser.org/

You can also try to decode the text using different encodings and use 
the first one that works. This is risky because latin-1 will always work.

Finally, a non-Python method - MS Word is pretty good about guessing the 
encodings of text files.

Kent

PS Please reply on list
>
> */Kent Johnson <kent37 at tds.net>/* wrote:
>
>     anil maran wrote:
>     > Unicode?
>     > im getting this error:
>     > invalid byte sequence for encoding "UTF8": 0x92
>     >
>     > since the db is not handling latin-1 and is set to use UTF8 how
>     do i
>     > handle this
>
>     If you have a latin-1 string and you want utf-8, convert it to
>     Unicode
>     and then to utf-8 using decode() and encode():
>
>     In [1]: s='\x92'
>
>     In [3]: s.decode('latin-1').encode('utf-8')
>     Out[3]: '\xc2\x92'
>
>     Kent
>
>     _______________________________________________
>     Tutor maillist - Tutor at python.org
>     http://mail.python.org/mailman/listinfo/tutor
>
>
> ------------------------------------------------------------------------
> How low will we go? Check out Yahoo! Messenger?s low PC-to-Phone call 
> rates. 
> <http://us.rd.yahoo.com/mail_us/taglines/postman8/*http://us.rd.yahoo.com/evt=39663/*http://voice.yahoo.com>



From kent37 at tds.net  Wed Aug  2 22:54:54 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 02 Aug 2006 16:54:54 -0400
Subject: [Tutor] latin-1 to unicode in python
In-Reply-To: <20060802204725.54244.qmail@web55907.mail.re3.yahoo.com>
References: <20060802204725.54244.qmail@web55907.mail.re3.yahoo.com>
Message-ID: <44D1111E.8000509@tds.net>

anil maran wrote:
> 'ascii' codec can't encode character u'\x96' in position 213: ordinal 
> not in range(128)
>
> now i m getting this error
Please show your code and the traceback and reply on list, not to me 
personally.

Kent

>
> */Kent Johnson <kent37 at tds.net>/* wrote:
>
>     anil maran wrote:
>     > Unicode?
>     > im getting this error:
>     > invalid byte sequence for encoding "UTF8": 0x92
>     >
>     > since the db is not handling latin-1 and is set to use UTF8 how
>     do i
>     > handle this
>
>     If you have a latin-1 string and you want utf-8, convert it to
>     Unicode
>     and then to utf-8 using decode() and encode():
>
>     In [1]: s='\x92'
>
>     In [3]: s.decode('latin-1').encode('utf-8')
>     Out[3]: '\xc2\x92'
>
>     Kent
>
>     _______________________________________________
>     Tutor maillist - Tutor at python.org
>     http://mail.python.org/mailman/listinfo/tutor
>
>
> ------------------------------------------------------------------------
> Do you Yahoo!?
> Get on board. You're invited 
> <http://us.rd.yahoo.com/evt=40791/*http://advision.webevents.yahoo.com/handraisers> 
> to try the new Yahoo! Mail Beta. 



From dkuhlman at rexx.com  Wed Aug  2 23:43:33 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Wed, 2 Aug 2006 14:43:33 -0700
Subject: [Tutor] Notes on namespaces, scopes, etc
In-Reply-To: <Pine.LNX.4.64.0607281425420.13099@hkn.eecs.berkeley.edu>
References: <20060727155200.GA94348@cutter.rexx.com> <44C8EDF4.5020809@tds.net>
	<20060728204526.GB11905@cutter.rexx.com>
	<Pine.LNX.4.64.0607281425420.13099@hkn.eecs.berkeley.edu>
Message-ID: <20060802214333.GA2067@cutter.rexx.com>

On Fri, Jul 28, 2006 at 02:36:08PM -0700, Danny Yoo wrote:
> > If there were really such a thing as nested scopes/namespaces, we would 
> > have a function that would give us access to them, similar to the way 
> > that locals() and globals() give us access to the local and global 
> > namespace.
> 
> It would be _convenient_ to have such a function for inspection, but it's 
> not a requirement.
> 
> Here's a function that shows lexical scope in action:
> 
> ##########################
> >>> def pair(x, y):
> ...     def f(b):
> ...         if b: return x
> ...         return y
> ...     return f
> ...
> >>> p = pair(3, 4)
> >>> p(True)
> 3
> >>> p(False)
> 4
> ##########################

I believe that I've incorporated most, if not all, of the
suggestions from those on the list, except for Danny's suggestion
(above) about closures.  To paraphrase "The Treasure of the Sierra
Madre":

    "Closures?  Closures?  We don't got to show you no stinking
    closures."

After all, these notes on notes and bindings were intended to
beginners, not computer science students.  But, I did add a link to
an explanation of closures.

I've also added a collection of links to related material at the
end of these notes.  Hopefully, if my explanation is confusing,
Alan's explanation or the standard docs will pull them through.

The document itself is still here:

    http://www.rexx.com/~dkuhlman/python_comments.html#namespaces

And, thanks again for all the help.

Off topic -- For those of you who need the quote:

    "Badges? We ain't got no badges. We don't need no badges.  I
    don't have to show you any stinking badges!"
      --Gold Hat, as played by Alfonso Bedoya
      "The Treasure of the Sierra Madre" (1948)

Dave

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

From cspears2002 at yahoo.com  Thu Aug  3 00:42:10 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Wed, 2 Aug 2006 15:42:10 -0700 (PDT)
Subject: [Tutor] os.walk()
Message-ID: <20060802224210.67474.qmail@web51606.mail.yahoo.com>

I'm creating a function that traverses a directory
tree and prints out paths to files:

#!/usr/bin/python

import os, os.path, glob

def traverse(base = '.'):
	for root,dirs,files in os.walk(base):
		for name in files:
			path = os.path.join(root, name)
			print path

Sample output:

./gui_screenshot.jpeg
./find_items.pyc
./find_items.py
./os
./LearningToProgram/loggablebankaccount.py
./LearningToProgram/BankAccounts.pyc
./LearningToProgram/KeysApp.py
./LearningToProgram/Message.py
./LearningToProgram/Message.pyc
./LearningToProgram/a.txt
./LearningToProgram/b.txt

I'm glad that the function works smoothly.  I'm just
wondering how os.walk works.  Shouldn't I have to
write a statement like this:

path = os.path.join(root, dirs, name)



From alan.gauld at freenet.co.uk  Thu Aug  3 01:58:46 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 3 Aug 2006 00:58:46 +0100
Subject: [Tutor] Notes on namespaces, scopes, etc
References: <20060727155200.GA94348@cutter.rexx.com>
	<44C8EDF4.5020809@tds.net><20060728204526.GB11905@cutter.rexx.com><Pine.LNX.4.64.0607281425420.13099@hkn.eecs.berkeley.edu>
	<20060802214333.GA2067@cutter.rexx.com>
Message-ID: <002b01c6b68f$982507a0$0201a8c0@XPpro>

Looks good Dave.

Alan G.

From kyrath at cox.net  Thu Aug  3 03:16:34 2006
From: kyrath at cox.net (Rob)
Date: Wed, 2 Aug 2006 21:16:34 -0400
Subject: [Tutor] smtp error from cgi script
Message-ID: <002201c6b69a$7622aa80$0701a8c0@kasil>

Hi, can someone help me interpret the error output below?

I can't tell whether this is a coding error, or a configuration error, in which case, it would be up to my host provider.

For privacy reasons, I have changed the actual email addresses to name at domain1.net and name at domain2.net.  The first was the recipient and the second was the sender.

Thanks in advance.
-- Rob

 
SMTPRecipientsRefused
Python 2.3.5: /usr/bin/python
Wed Aug 2 20:17:33 2006

A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.

 
   62 
   63     server = smtplib.SMTP(mailserver)
   64     failed = server.sendmail(From, To, text)
   65     server.quit() 
   66     if failed:
failed undefined, server = <smtplib.SMTP instance>, server.sendmail = <bound method SMTP.sendmail of <smtplib.SMTP instance>>, From = 'name at domain2.net',
To = 'name at domain1.net', text = 'From: name at domain2.net\nTo: name at domain1.net\nDa... 1 1 \n----------------------------------------\n'

 
/usr/lib/python2.3/smtplib.py
 in sendmail(self=<smtplib.SMTP instance>, from_addr='name at domain2.net', to_addrs=['name at domain1.net'], msg='From: name at domain2.net\nTo: name at domain1.net\nDa...
1 1 \n----------------------------------------\n', mail_options=[], rcpt_options=[])
  685             # the server refused all our recipients
  686             self.rset()
  687             raise SMTPRecipientsRefused(senderrs)
  688         (code,resp) = self.data(msg)
  689         if code != 250:
global SMTPRecipientsRefused = <class smtplib.SMTPRecipientsRefused>, senderrs = {'name at domain1.net': (550, 'authentication required')}

SMTPRecipientsRefused: {'name at domain1.net': (550, 'authentication required')} 
      args = ({'name at domain1.net': (550, 'authentication required')},) 
      recipients = {'name at domain1.net': (550, 'authentication required')} 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060802/667cfc18/attachment.htm 

From cspears2002 at yahoo.com  Thu Aug  3 06:14:23 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Wed, 2 Aug 2006 21:14:23 -0700 (PDT)
Subject: [Tutor] critique my script!
Message-ID: <20060803041423.84422.qmail@web51615.mail.yahoo.com>

I created a function that takes a pattern and a base
path and then uses os.walk and glob to traverse
directories starting from the base path and place
files that match the glob pattern in a dictionary.

#!/usr/bin/python

import os, os.path, glob

def glob_files(pattern, base = '.'):
	path_list = []
	abs_base = os.path.abspath(base)
	path_list.append(abs_base)
	for root,dirs,files in os.walk(abs_base):
		for name in dirs:
			path = os.path.join(root, name)
			#print path
			path_list.append(path)
	globbed = {}
	cwd = os.getcwd()
	for p in path_list:
		os.chdir(p)
		matched_files = glob.glob(pattern)
		if matched_files != []:
			globbed[p] = matched_files
		os.chdir(abs_base)
	os.chdir(cwd)
	return globbed
		
Tell me what you think.  This script would probably
have been easier to write with reqular expressions,
but I was determined to use glob.

From anilmrn at yahoo.com  Thu Aug  3 08:56:11 2006
From: anilmrn at yahoo.com (anil maran)
Date: Wed, 2 Aug 2006 23:56:11 -0700 (PDT)
Subject: [Tutor] how do i get datetime object or time object from updated in
	rss
Message-ID: <20060803065611.10588.qmail@web55913.mail.re3.yahoo.com>

How do i convert this string to
datetime object
Fri, 21 Apr 2006 03:02:17 +0000


Previously I'd been using mxDateTime (which does everything but requires a C extension) to parse e-mail style dates (i.e. the ones used in RSS and changes.xml) but it looks like they're handled by the standard library.
 
http://blogs.law.harvard.edu/tech/rss

mx.DateTime.DateTimeFrom(d['entries'][1].updated)
Traceback (most recent call last):
  File "<input>", line 1, in ?
  File "/usr/lib/python2.4/site-packages/mx/DateTime/DateTime.py", line 226, in DateTimeFrom
    value = float(arg)
ValueError: invalid literal for float(): Fri, 21 Apr 2006 03:02:17 +0000
 __________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060802/af77942a/attachment.htm 

From ewald.ertl at hartter.com  Thu Aug  3 09:14:18 2006
From: ewald.ertl at hartter.com (Ewald Ertl)
Date: Thu, 03 Aug 2006 09:14:18 +0200
Subject: [Tutor] smtp error from cgi script
In-Reply-To: <002201c6b69a$7622aa80$0701a8c0@kasil>
References: <002201c6b69a$7622aa80$0701a8c0@kasil>
Message-ID: <44D1A24A.2050504@hartter.com>

Hi Rob,

Rob wrote:
> Hi, can someone help me interpret the error output below?
>  
> I can't tell whether this is a coding error, or a configuration error,
> in which case, it would be up to my host provider.
>  
> For privacy reasons, I have changed the actual email addresses to
> name at domain1.net <mailto:name at domain1.net> and name at domain2.net
> <mailto:name at domain2.net>.  The first was the recipient and the second
> was the sender.
>  
> Thanks in advance.
> -- Rob
>  
>  
> SMTPRecipientsRefused
> Python 2.3.5: /usr/bin/python
> Wed Aug 2 20:17:33 2006
>  
> A problem occurred in a Python script. Here is the sequence of function
> calls leading up to the error, in the order they occurred.
>  
>  
>    62 
>    63     server = smtplib.SMTP(mailserver)
>    64     failed = server.sendmail(From, To, text)
>    65     server.quit() 
>    66     if failed:
> failed undefined, server = <smtplib.SMTP instance>, server.sendmail =
> <bound method SMTP.sendmail of <smtplib.SMTP instance>>, From =
> 'name at domain2.net' <mailto:'name at domain2.net'>,
> To = 'name at domain1.net' <mailto:'name at domain1.net'>, text = 'From:
> name at domain2.net\nTo <mailto:name at domain2.net\nTo>: name at domain1.net\nDa
> <mailto:name at domain1.net\nDa>... 1 1
> \n----------------------------------------\n'
>  
>  
> /usr/lib/python2.3/smtplib.py
>  in sendmail(self=<smtplib.SMTP instance>, from_addr='name at domain2.net'
> <mailto:from_addr='name at domain2.net'>, to_addrs=['name at domain1.net'],
> msg='From: name at domain2.net\nTo <mailto:name at domain2.net\nTo>:
> name at domain1.net\nDa <mailto:name at domain1.net\nDa>...
> 1 1 \n----------------------------------------\n', mail_options=[],
> rcpt_options=[])
>   685             # the server refused all our recipients
>   686             self.rset()
>   687             raise SMTPRecipientsRefused(senderrs)
>   688         (code,resp) = self.data(msg)
>   689         if code != 250:
> global SMTPRecipientsRefused = <class smtplib.SMTPRecipientsRefused>,
> senderrs = {'name at domain1.net' <mailto:{'name at domain1.net'>: (550,
> 'authentication required')}
>  
> SMTPRecipientsRefused: {'name at domain1.net' <mailto:{'name at domain1.net'>:
> (550, 'authentication required')}
>       args = ({'name at domain1.net' <mailto:{'name at domain1.net'>: (550,
> 'authentication required')},)
>       recipients = {'name at domain1.net' <mailto:{'name at domain1.net'>:
> (550, 'authentication required')}
> 

I've not worked with smtplib, but the error (550, 'authentication required'), suggests
to me, that you have to login into the mail-Server, otherwise the server would not
accept emails.
Looking into the doc for smtplib, the Class SMTP has method for that:

login(self, user, password)
    Log in on an SMTP server that requires authentication.

    The arguments are:
        - user:     The user name to authenticate with.
        - password: The password for the authentication.

    If there has been no previous EHLO or HELO command this session, this
    method tries ESMTP EHLO first.

    This method will return normally if the authentication was successful.

    This method may raise the following exceptions:

     SMTPHeloError            The server didn't reply properly to
                              the helo greeting.
     SMTPAuthenticationError  The server didn't accept the username/
                              password combination.
     SMTPException            No suitable authentication method was
                              found.


HTH Ewald


From alan.gauld at btinternet.com  Thu Aug  3 11:49:52 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Aug 2006 10:49:52 +0100
Subject: [Tutor] os.walk()
References: <20060802224210.67474.qmail@web51606.mail.yahoo.com>
Message-ID: <easgs2$qen$1@sea.gmane.org>


"Christopher Spears" <cspears2002 at yahoo.com> wrote> for 
root,dirs,files in os.walk(base):
> for name in files:
> path = os.path.join(root, name)
> print path
>
> Sample output:
>
> ./gui_screenshot.jpeg
> ./find_items.pyc
> ./find_items.py
> ./os
> ./LearningToProgram/loggablebankaccount.py

> I'm glad that the function works smoothly.  I'm just
> wondering how os.walk works.  Shouldn't I have to
> write a statement like this:
>
> path = os.path.join(root, dirs, name)
>

No, the dirs value holds a list of folders, the files
value holds a list of files. Thus if you wanted to print
out all the sub folders in the root you would
print root+dirs
But you want files not folders so you correctly use
print root+files

root holds the full path to the current point in the tree.
(And os.walk is a good example of a program using a
tree data structure! ;-)

Alan G. 




From alan.gauld at freenet.co.uk  Thu Aug  3 12:40:03 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 3 Aug 2006 11:40:03 +0100
Subject: [Tutor] critique my script!
References: <20060803041423.84422.qmail@web51615.mail.yahoo.com>
Message-ID: <000e01c6b6e9$2e5119e0$0201a8c0@XPpro>

>I created a function that takes a pattern and a base
> path and then uses os.walk and glob to traverse
> directories starting from the base path and place
> files that match the glob pattern in a dictionary.

I'm not sure why you are traversing the paths a second time.
Why not just apply glob within the os.walk traversal?
After all you are putting the path into the path list, then 
iterating over that list later, why not just apply glob the 
first time around?

> #!/usr/bin/python
> 
> import os, os.path, glob
> 
> def glob_files(pattern, base = '.'):
> path_list = []
> abs_base = os.path.abspath(base)
> path_list.append(abs_base)
> for root,dirs,files in os.walk(abs_base):
> for name in dirs:
> path = os.path.join(root, name)
> #print path
> path_list.append(path)
> globbed = {}
> cwd = os.getcwd()
> for p in path_list:
> os.chdir(p)
> matched_files = glob.glob(pattern)
> if matched_files != []:
> globbed[p] = matched_files
> os.chdir(abs_base)
> os.chdir(cwd)
> return globbed

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

From kent37 at tds.net  Thu Aug  3 13:09:25 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 03 Aug 2006 07:09:25 -0400
Subject: [Tutor] Notes on namespaces, scopes, etc
In-Reply-To: <20060802214333.GA2067@cutter.rexx.com>
References: <20060727155200.GA94348@cutter.rexx.com>
	<44C8EDF4.5020809@tds.net>	<20060728204526.GB11905@cutter.rexx.com>	<Pine.LNX.4.64.0607281425420.13099@hkn.eecs.berkeley.edu>
	<20060802214333.GA2067@cutter.rexx.com>
Message-ID: <44D1D965.60008@tds.net>

Dave Kuhlman wrote:
> I believe that I've incorporated most, if not all, of the
> suggestions from those on the list, except for Danny's suggestion
> (above) about closures.
>
> The document itself is still here:
>
>     http://www.rexx.com/~dkuhlman/python_comments.html#namespaces

Very nice. Just a few notes:

- When you talk about the hierarchy of namespace lookup, you might just 
mention nested scopes and refer to the PEP for more info, instead of 
omitting it completely.

- In the section "Accessing namespace dictionaries" you write, "Note 
that for lexically/statically nested scopes (for example, a function 
defined inside a function), it seems that globals() and locals() still 
give access to all items in the accessible namespaces, /but/ do not give 
dictionary style access to all visible scopes." globals() and locals() 
give access to items in the global and local namespaces, not all 
accessible namespaces. As was noted in the emails, variables in nested 
scopes are not included in locals() and globals(). I think that's what 
you're trying to say but it isn't clear.

- PEP 227 is definitely the present, not the future. Nested scopes have 
been available since Python 2.1.

Kent


From kent37 at tds.net  Thu Aug  3 13:20:20 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 03 Aug 2006 07:20:20 -0400
Subject: [Tutor] critique my script!
In-Reply-To: <000e01c6b6e9$2e5119e0$0201a8c0@XPpro>
References: <20060803041423.84422.qmail@web51615.mail.yahoo.com>
	<000e01c6b6e9$2e5119e0$0201a8c0@XPpro>
Message-ID: <44D1DBF4.3010805@tds.net>

Alan Gauld wrote:
>> I created a function that takes a pattern and a base
>> path and then uses os.walk and glob to traverse
>> directories starting from the base path and place
>> files that match the glob pattern in a dictionary.
>>     
>
> I'm not sure why you are traversing the paths a second time.
> Why not just apply glob within the os.walk traversal?
> After all you are putting the path into the path list, then 
> iterating over that list later, why not just apply glob the 
> first time around?

Alternately you could use fnmatch.fnmatch() to filter the list of files 
received from os.walk(). Then you wouldn't be using glob() but fnmatch() 
is the file-name-matching part of glob(). A list comprehension would be 
good for this:
matchedFiles = [ f for f in files if fnmatch(f, pattern) ]

I think your whole program can be written in about six lines, but I'll 
let you puzzle it a bit rather than showing you.

Kent


From ml.cyresse at gmail.com  Thu Aug  3 13:44:45 2006
From: ml.cyresse at gmail.com (Liam Clarke)
Date: Thu, 3 Aug 2006 23:44:45 +1200
Subject: [Tutor] Binary fractions, recommendations?
Message-ID: <b6f3249e0608030444l72823e44xf7e52ad009d6745e@mail.gmail.com>

Hi all,

I was recently playing with the problem of implementing the floor()
functionality, modulo being specifically mentioned in the briefing...

so, after grokking that x = a - (a % b) would do it (i.e. for a = 5.5
and b = 1, you'd get x =5) I felt very pleased...

...until I saw the definiton of modulo.

Which would be...

def my_mod(x, y):
	return x - (y*math.floor(x/y))

Ack. My floor() relies on modulo which relies on... floor.

So after some Googling, I find a page which indicates that the trick
seems to be bit operations  -
http://www.diycalculator.com/popup-m-round.shtml

Problem is; I can't bitshift on floats, so can't test. Can't bitshift
on floats in C either.  Does anyone know how I could work on a binary
representation of a float? Any language at all, I'm desperate...

Regards,

Liam Clarke

From rabidpoobear at gmail.com  Thu Aug  3 15:34:03 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 03 Aug 2006 08:34:03 -0500
Subject: [Tutor] Binary fractions, recommendations?
In-Reply-To: <b6f3249e0608030444l72823e44xf7e52ad009d6745e@mail.gmail.com>
References: <b6f3249e0608030444l72823e44xf7e52ad009d6745e@mail.gmail.com>
Message-ID: <44D1FB4B.4010309@gmail.com>

Liam Clarke wrote:
> Hi all,
>
> I was recently playing with the problem of implementing the floor()
> functionality, modulo being specifically mentioned in the briefing.
>
>   
you could convert the float to a string, split on the decimal point, and 
convert the left-hand side
back to an integer :)
or you could just convert the float to an integer.

From jgcox39 at highstream.net  Thu Aug  3 20:12:28 2006
From: jgcox39 at highstream.net (Joe Cox)
Date: Thu, 3 Aug 2006 11:12:28 -0700
Subject: [Tutor] Listbox selection
Message-ID: <LLEBIOJOJMEGEMFMBIOPOEBFCLAA.jgcox39@highstream.net>

I am still having a problem getting my listbox's binded to the radiobuttons.
I am getting closer.

###Assign each Radiobutton with its own listbox values, show one selected
button and one listbox###



from Tkinter import *

root = Tk()

var = StringVar()
var.set('a')

{ 'Aluminum' : ['Wrought', 'Die cast'],
       'Steel'   : ['Low Carbon', 'Medium-high carbon','Alloy'] }



def radio_command():
    if var.get() == 'a':
        # button with value 'a' selected
        listbox.insert('a') #here I am trying to put the string starting
with 'Steel' in the listbox
    elif var.get() == 'b':
        # button with value 'b' selected
        listbox.insert('b')   #here I am trying to put the string starting
with 'Aluminum' in the listbox



radio_a = Radiobutton(root,text="Steel", variable=var, value='a',
command=radio_command).pack()
radio_b = Radiobutton(root,text="Aluminum", variable=var, value='b',
command=radio_command).pack()
radio_c = Radiobutton(root,text="Cast Iron", variable=var, value='c',
command=radio_command).pack()
radio_d = Radiobutton(root,text="Nickel", variable=var, value='d',
command=radio_command).pack()
radio_e = Radiobutton(root,text="Titaniuim", variable=var, value='e',
command=radio_command).pack()


listbox = Listbox(root)
for item in ():
    listbox.insert(END, item)
listbox.pack(side=LEFT, fill=BOTH)

root.mainloop()

























Joe Cox
513-293-4830


From cspears2002 at yahoo.com  Thu Aug  3 17:33:46 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 3 Aug 2006 08:33:46 -0700 (PDT)
Subject: [Tutor] critique my script!
In-Reply-To: <000e01c6b6e9$2e5119e0$0201a8c0@XPpro>
Message-ID: <20060803153346.17327.qmail@web51614.mail.yahoo.com>

I didn't know I could place the glob in the os.walk
traversal.  Could you give me an example of how to do
this?

--- Alan Gauld <alan.gauld at freenet.co.uk> wrote:

> >I created a function that takes a pattern and a
> base
> > path and then uses os.walk and glob to traverse
> > directories starting from the base path and place
> > files that match the glob pattern in a dictionary.
> 
> I'm not sure why you are traversing the paths a
> second time.
> Why not just apply glob within the os.walk
> traversal?
> After all you are putting the path into the path
> list, then 
> iterating over that list later, why not just apply
> glob the 
> first time around?
> 
> > #!/usr/bin/python
> > 
> > import os, os.path, glob
> > 
> > def glob_files(pattern, base = '.'):
> > path_list = []
> > abs_base = os.path.abspath(base)
> > path_list.append(abs_base)
> > for root,dirs,files in os.walk(abs_base):
> > for name in dirs:
> > path = os.path.join(root, name)
> > #print path
> > path_list.append(path)
> > globbed = {}
> > cwd = os.getcwd()
> > for p in path_list:
> > os.chdir(p)
> > matched_files = glob.glob(pattern)
> > if matched_files != []:
> > globbed[p] = matched_files
> > os.chdir(abs_base)
> > os.chdir(cwd)
> > return globbed
> 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
> 


"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"I generally know what I'm doing."
-Buster Keaton

From kent37 at tds.net  Thu Aug  3 19:09:08 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 03 Aug 2006 13:09:08 -0400
Subject: [Tutor] Binary fractions, recommendations?
In-Reply-To: <b6f3249e0608030444l72823e44xf7e52ad009d6745e@mail.gmail.com>
References: <b6f3249e0608030444l72823e44xf7e52ad009d6745e@mail.gmail.com>
Message-ID: <44D22DB4.8060507@tds.net>

Liam Clarke wrote:
> Problem is; I can't bitshift on floats, so can't test. Can't bitshift
> on floats in C either.  Does anyone know how I could work on a binary
> representation of a float? Any language at all, I'm desperate...

In C you can certainly get access to the binary representation of a 
float as bytes. My C is really rusty but something like
float x = 1.3;
char* p = &x;

will give you a pointer to the binary representation of x. You can do 
something similar with the struct module in Python; struct.pack() will 
give you a byte string containing the representation of a float.

Kent


From arbaro at gmail.com  Thu Aug  3 19:28:42 2006
From: arbaro at gmail.com (arbaro arbaro)
Date: Thu, 3 Aug 2006 19:28:42 +0200
Subject: [Tutor] regular expression
Message-ID: <802dc1e0608031028h7cf4e84oe2454214c6399efa@mail.gmail.com>

Hello,

I'm trying to mount an usb device from python under linux.
To do so, I read the kernel log /proc/kmsg and watch for something like:
  "<6> /dev/scsi/host3/bus0/target0/lun0/:<7>usb-storage: device scan
complete"

When I compile a regular expression like:
  "r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')"
It is found. But I don't want the <\d+>\s or '<6> ' in front of the path, so
I tried:
   "r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')"
But this way the usb device path it is not found.

So what i'm trying to do is:
- find the usb device path from the kernel log with the regular expression.
- Determine the start and end positions of the match (and add /disc or
/part1 to the match).
- And use that to mount the usb stick on /mnt/usb -> mount -t auto match
/mnt/usb

If anyone can see what i'm doing wrong, please tell me, because I don't
understand it anymore.
Thanks.

Below is the code:

# \d+ = 1 or more digits
# \s  = an empty space

import re

def findusbdevice():
    ''' Returns path of usb device '''
    # I did a 'cat /proc/kmsg /log/kmsg' to be able to read the kernel
message.
    # Somehow I can't read /proc/kmsg directly.
    kmsg = open('/log/kmsg', 'r')
    r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')
    #r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')
    for line in kmsg:
        if 'usb-storage' in line and r.match(line):
            print 'Success', line
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060803/f505e592/attachment.html 

From jeffpeery at yahoo.com  Thu Aug  3 19:38:22 2006
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Thu, 3 Aug 2006 10:38:22 -0700 (PDT)
Subject: [Tutor] python processing of web html forms
Message-ID: <20060803173822.3453.qmail@web30508.mail.mud.yahoo.com>

Hello, I want to use python to process information input into a HTML form on my website. how is this typically performed? I saw cherrypy and also quixote for web python stuff... I have no experience with python on the web. Thanks.

jeff

 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060803/f8990b3e/attachment-0001.html 

From kent37 at tds.net  Thu Aug  3 19:46:55 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 03 Aug 2006 13:46:55 -0400
Subject: [Tutor] regular expression
In-Reply-To: <802dc1e0608031028h7cf4e84oe2454214c6399efa@mail.gmail.com>
References: <802dc1e0608031028h7cf4e84oe2454214c6399efa@mail.gmail.com>
Message-ID: <44D2368F.10706@tds.net>

arbaro arbaro wrote:
> Hello,
>
> I'm trying to mount an usb device from python under linux.
> To do so, I read the kernel log /proc/kmsg and watch for something like:
>   "<6> /dev/scsi/host3/bus0/target0/lun0/:<7>usb-storage: device scan 
> complete"
>
> When I compile a regular expression like:
>   "r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')"
You should use raw strings for regular expressions that contain \ 
characters.
> It is found. But I don't want the <\d+>\s or '<6> ' in front of the 
> path, so I tried:
>    "r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')"
> But this way the usb device path it is not found.
You are using re.match(), which just looks for a match at the start of 
the string. Try using re.search() instead.
http://docs.python.org/lib/matching-searching.html

Kent
>
> So what i'm trying to do is:
> - find the usb device path from the kernel log with the regular 
> expression.
> - Determine the start and end positions of the match (and add /disc or 
> /part1 to the match).
> - And use that to mount the usb stick on /mnt/usb -> mount -t auto 
> match /mnt/usb
>
> If anyone can see what i'm doing wrong, please tell me, because I 
> don't understand it anymore.
> Thanks.
>
> Below is the code:
>
> # \d+ = 1 or more digits
> # \s  = an empty space
>
> import re
>
> def findusbdevice():
>     ''' Returns path of usb device '''
>     # I did a 'cat /proc/kmsg /log/kmsg' to be able to read the kernel 
> message.
>     # Somehow I can't read /proc/kmsg directly.
>     kmsg = open('/log/kmsg', 'r')
>     r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')
>     #r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')
>     for line in kmsg:
>         if 'usb-storage' in line and r.match(line):
>             print 'Success', line
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



From alan.gauld at freenet.co.uk  Thu Aug  3 19:48:33 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 3 Aug 2006 18:48:33 +0100
Subject: [Tutor] critique my script!
References: <20060803153346.17327.qmail@web51614.mail.yahoo.com>
Message-ID: <000301c6b725$0a453ae0$0201a8c0@XPpro>


>I didn't know I could place the glob in the os.walk
> traversal.  Could you give me an example of how to do
> this?

I'm not sure why you see a problem. A simplified form of your
code is like this:

for root,dirs,files in os.walk(abs_base):
   for name in dirs:
       path = os.path.join(root, name)
       path_list.append(path)

So you create the path list here

for p in path_list:
   os.chdir(p)
   matched_files = glob.glob(pattern)

then you iterate over it applying glob. Why not combine the lops like:

for root,dirs,files in os.walk(abs_base):
   for name in dirs:
       path = os.path.join(root, name)
       os.chdir(path)
       matched_files = glob.glob(pattern)

Doesn't that do the same thing - or am I missing something?

Alan G.


> --- Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
>> >I created a function that takes a pattern and a
>> base
>> > path and then uses os.walk and glob to traverse
>> > directories starting from the base path and place
>> > files that match the glob pattern in a dictionary.
>>
>> I'm not sure why you are traversing the paths a
>> second time.
>> Why not just apply glob within the os.walk
>> traversal?
>> After all you are putting the path into the path
>> list, then
>> iterating over that list later, why not just apply
>> glob the
>> first time around?
>>
>> > #!/usr/bin/python
>> >
>> > import os, os.path, glob
>> >
>> > def glob_files(pattern, base = '.'):
>> > path_list = []
>> > abs_base = os.path.abspath(base)
>> > path_list.append(abs_base)
>> > for root,dirs,files in os.walk(abs_base):
>> > for name in dirs:
>> > path = os.path.join(root, name)
>> > #print path
>> > path_list.append(path)
>> > globbed = {}
>> > cwd = os.getcwd()
>> > for p in path_list:
>> > os.chdir(p)
>> > matched_files = glob.glob(pattern)
>> > if matched_files != []:
>> > globbed[p] = matched_files
>> > os.chdir(abs_base)
>> > os.chdir(cwd)
>> > return globbed
>>
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.freenetpages.co.uk/hp/alan.gauld
>>
>
>
> "I'm the last person to pretend that I'm a radio.  I'd rather go out 
> and be a color television set."
> -David Bowie
>
> "Who dares wins"
> -British military motto
>
> "I generally know what I'm doing."
> -Buster Keaton 


From Mike.Hansen at atmel.com  Thu Aug  3 20:07:40 2006
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 3 Aug 2006 12:07:40 -0600
Subject: [Tutor] python processing of web html forms
Message-ID: <57B026980605A64F9B23484C5659E32E254E64@poccso.US.ad.atmel.com>

 ______________________________

	From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]
On Behalf Of Jeff Peery
	Sent: Thursday, August 03, 2006 11:38 AM
	To: tutor at python.org
	Subject: [Tutor] python processing of web html forms
	
	
	Hello, I want to use python to process information input into a
HTML form on my website. how is this typically performed? I saw cherrypy
and also quixote for web python stuff... I have no experience with
python on the web. Thanks.
	
	jeff
	

	________________________________

You might want to take a look at the cgi module. 
Devshed has an article on getting started with it.
http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/

IMO, I think if you want to do web stuff, you should learn the basics
first(cgi), then move on to cherrypy, quixote, django, turbo gears...

Mike

From K.Weinert at gmx.net  Thu Aug  3 21:35:57 2006
From: K.Weinert at gmx.net (K.Weinert at gmx.net)
Date: Thu, 03 Aug 2006 21:35:57 +0200
Subject: [Tutor] File like object for Windows registry
Message-ID: <20060803193557.259320@gmx.net>

Hello!

My app should run on debian and windows platforms. For storing the configuration data, I use the ConfigParser module.

What I find difficult is to determine a place for my configuration file. On debian, it is simply

os.path.join(os.path.expanduser("~")),"myconfig")

but what am I supposed to do on Windows? I think a clean solution would be to create a file-like object that reads and writes to the registry, is it?

Kind regards,
Karsten.
-- 


"Feel free" ? 10 GB Mailbox, 100 FreeSMS/Monat ...
Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail

From lkvam at venix.com  Thu Aug  3 20:07:52 2006
From: lkvam at venix.com (Lloyd Kvam)
Date: Thu, 03 Aug 2006 14:07:52 -0400
Subject: [Tutor] python processing of web html forms
In-Reply-To: <20060803173822.3453.qmail@web30508.mail.mud.yahoo.com>
References: <20060803173822.3453.qmail@web30508.mail.mud.yahoo.com>
Message-ID: <1154628472.28304.569.camel@www.venix.com>

On Thu, 2006-08-03 at 10:38 -0700, Jeff Peery wrote:
> Hello, I want to use python to process information input into a HTML
> form on my website. how is this typically performed? I saw cherrypy
> and also quixote for web python stuff... I have no experience with
> python on the web. Thanks.

TurboGears provides a very nice tutorial.
http://www.turbogears.org/docs/wiki20/

That should help get you started.

> 
> jeff
> 
> 
> 
> ______________________________________________________________________
> Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great
> rates starting at 1?/min.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:  603-653-8139
fax:    320-210-3409


From arbaro at gmail.com  Thu Aug  3 22:16:38 2006
From: arbaro at gmail.com (arbaro arbaro)
Date: Thu, 3 Aug 2006 22:16:38 +0200
Subject: [Tutor] regular expression
In-Reply-To: <802dc1e0608031028h7cf4e84oe2454214c6399efa@mail.gmail.com>
References: <802dc1e0608031028h7cf4e84oe2454214c6399efa@mail.gmail.com>
Message-ID: <802dc1e0608031316n7c48f462n5f1bb847603b9f5f@mail.gmail.com>

Hello,

Im just answering my own email, since I just found out what my error was.

>From a regular expression howto: http://www.amk.ca/python/howto/regex/regex.html

The match() function only checks if the RE matches at the beginning of
the string while search() will scan forward through the string for a
match. It's important to keep this distinction in mind.  Remember,
match() will only report a successful match which will start at 0; if
the match wouldn't start at zero,  match() will not report it.

That was exactly my problem. Replacing r.match(line) for
r.search(line) solved it.

Sorry for having bothered you prematurely.




On 8/3/06, arbaro arbaro <arbaro at gmail.com> wrote:
>
> Hello,
>
> I'm trying to mount an usb device from python under linux.
> To do so, I read the kernel log /proc/kmsg and watch for something like:
>   "<6> /dev/scsi/host3/bus0/target0/lun0/:<7>usb-storage: device scan complete"
>
> When I compile a regular expression like:
>   "r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')"
> It is found. But I don't want the <\d+>\s or '<6> ' in front of the path, so I tried:
>    "r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')"
> But this way the usb device path it is not found.
>
> So what i'm trying to do is:
> - find the usb device path from the kernel log with the regular expression.
> - Determine the start and end positions of the match (and add /disc or /part1 to the match).
> - And use that to mount the usb stick on /mnt/usb -> mount -t auto match /mnt/usb
>
> If anyone can see what i'm doing wrong, please tell me, because I don't understand it anymore.
> Thanks.
>
> Below is the code:
>
> # \d+ = 1 or more digits
>  # \s  = an empty space
>
> import re
>
> def findusbdevice():
>     ''' Returns path of usb device '''
>     # I did a 'cat /proc/kmsg /log/kmsg' to be able to read the kernel message.
>     # Somehow I can't read /proc/kmsg directly.
>     kmsg = open('/log/kmsg', 'r')
>     r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')
>     #r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')
>     for line in kmsg:
>         if 'usb-storage' in line and  r.match(line):
>             print 'Success', line
>

From h.finucane at gmail.com  Thu Aug  3 22:37:13 2006
From: h.finucane at gmail.com (Henry Finucane)
Date: Thu, 3 Aug 2006 13:37:13 -0700
Subject: [Tutor] File like object for Windows registry
In-Reply-To: <20060803193557.259320@gmx.net>
References: <20060803193557.259320@gmx.net>
Message-ID: <f24e65d60608031337n875b157xb82402ea1e4034ef@mail.gmail.com>

On 8/3/06, K.Weinert at gmx.net <K.Weinert at gmx.net> wrote:
> Hello!
>
> My app should run on debian and windows platforms. For storing the configuration data, I use the ConfigParser module.
>
> What I find difficult is to determine a place for my configuration file. On debian, it is simply
>
> os.path.join(os.path.expanduser("~")),"myconfig")
>
> but what am I supposed to do on Windows? I think a clean solution would be to create a file-like object that reads and writes to the registry, is it?

You might be able to do that, I don't know much about win32
programming, but I believe a better solution is to use the built-in
windows variables. %APPDATA% is where you should store user-specific
application data (and even Microsoft is starting to store XML
configuration files there), and it's an easy variable to get.

>>> import os
>>> os.environ["APPDATA"]
'C:\\Documents and Settings\\UserName\\Application Data'

That should function just fine as a home directory replacement.

> Kind regards,
> Karsten.
> --
>
>
> "Feel free" ? 10 GB Mailbox, 100 FreeSMS/Monat ...
> Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
--H.F.
My penguin is bigger than yours, mister...

From andre.roberge at gmail.com  Thu Aug  3 22:42:41 2006
From: andre.roberge at gmail.com (Andre Roberge)
Date: Thu, 3 Aug 2006 17:42:41 -0300
Subject: [Tutor] File like object for Windows registry
In-Reply-To: <f24e65d60608031337n875b157xb82402ea1e4034ef@mail.gmail.com>
References: <20060803193557.259320@gmx.net>
	<f24e65d60608031337n875b157xb82402ea1e4034ef@mail.gmail.com>
Message-ID: <7528bcdd0608031342l9a38186je120f0a569f9eabe@mail.gmail.com>

On 8/3/06, Henry Finucane <h.finucane at gmail.com> wrote:
> On 8/3/06, K.Weinert at gmx.net <K.Weinert at gmx.net> wrote:
> > Hello!
> >
> > My app should run on debian and windows platforms. For storing the configuration data, I use the ConfigParser module.
> >
> > What I find difficult is to determine a place for my configuration file. On debian, it is simply
> >
> > os.path.join(os.path.expanduser("~")),"myconfig")

This works on Windows as well.  I just tried it :-)

> >
> > but what am I supposed to do on Windows? I think a clean solution would be to create a file-like object that reads and writes to the registry, is it?

Messing with the registry is (imo)  a bad idea.

>
> You might be able to do that, I don't know much about win32
> programming, but I believe a better solution is to use the built-in
> windows variables. %APPDATA% is where you should store user-specific
> application data (and even Microsoft is starting to store XML
> configuration files there), and it's an easy variable to get.
>
> >>> import os
> >>> os.environ["APPDATA"]
> 'C:\\Documents and Settings\\UserName\\Application Data'
>
> That should function just fine as a home directory replacement.
>
...

Andr?

From h.finucane at gmail.com  Thu Aug  3 22:54:40 2006
From: h.finucane at gmail.com (Henry Finucane)
Date: Thu, 3 Aug 2006 13:54:40 -0700
Subject: [Tutor] File like object for Windows registry
In-Reply-To: <7528bcdd0608031342l9a38186je120f0a569f9eabe@mail.gmail.com>
References: <20060803193557.259320@gmx.net>
	<f24e65d60608031337n875b157xb82402ea1e4034ef@mail.gmail.com>
	<7528bcdd0608031342l9a38186je120f0a569f9eabe@mail.gmail.com>
Message-ID: <f24e65d60608031354m3f6fbabbqedc950fbd357c753@mail.gmail.com>

On 8/3/06, Andre Roberge <andre.roberge at gmail.com> wrote:
> On 8/3/06, Henry Finucane <h.finucane at gmail.com> wrote:
> > On 8/3/06, K.Weinert at gmx.net <K.Weinert at gmx.net> wrote:
> > > Hello!
> > >
> > > My app should run on debian and windows platforms. For storing the configuration data, I use the ConfigParser module.
> > >
> > > What I find difficult is to determine a place for my configuration file. On debian, it is simply
> > >
> > > os.path.join(os.path.expanduser("~")),"myconfig")
>
> This works on Windows as well.  I just tried it :-)

Doh. Always try the simple stuff first :P.

> > >
> > > but what am I supposed to do on Windows? I think a clean solution would be to create a file-like object that reads and writes to the registry, is it?
>
> Messing with the registry is (imo)  a bad idea.
>
> >
> > You might be able to do that, I don't know much about win32
> > programming, but I believe a better solution is to use the built-in
> > windows variables. %APPDATA% is where you should store user-specific
> > application data (and even Microsoft is starting to store XML
> > configuration files there), and it's an easy variable to get.
> >
> > >>> import os
> > >>> os.environ["APPDATA"]
> > 'C:\\Documents and Settings\\UserName\\Application Data'
> >
> > That should function just fine as a home directory replacement.
> >
> ...
>
> Andr?
>


-- 
--H.F.
My penguin is bigger than yours, mister...

From alan.gauld at freenet.co.uk  Thu Aug  3 23:37:33 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 3 Aug 2006 22:37:33 +0100
Subject: [Tutor] File like object for Windows registry
References: <20060803193557.259320@gmx.net>
Message-ID: <002901c6b745$080d17a0$0201a8c0@XPpro>

> My app should run on debian and windows platforms.

Hard lines :-(

> For storing the configuration data, I use the ConfigParser module.
> What I find difficult is to determine a place for my configuration 
> file.

Config parser basically produces an .in file.
The rules that Windows uses to locate .ini files vary
according to Windows version. If you can assume you
only have to deal with Win2K and XP then things are
a bit easier since there is a recommended location
and indeed users have the concept of a home directory
- even the $HOME environment variable works.

However traditionally ini files were stored in one of
1) the Windows directory (%WINDIR%) or
2) the application home directory.
3) The C:\ root directory - but this is now strongly
    discouraged

If you want to have application level ini files as well as
per user configurations those are still the preferred
locations for the global files.

Between Windows 95 and Windows 2000 the Registry
was being pushed as the best place for config data
but as Registry performance and corruption problems
increase .ini files are coming back into favour.

To summarise. If you want to just have a per user
config file just store it in the users data folder. If you
also have a global ini file then I recommend putting
it in the app install folder. If the app is cross platform
I'd advise keeping well clear of the registry, but if
you must use it I'd favour using the WSH objects
rather than the Win32 API calls to access the
Registry - although it does add another dependency
to the app.

HTH,

Alan G. 


From cspears2002 at yahoo.com  Fri Aug  4 00:37:49 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 3 Aug 2006 15:37:49 -0700 (PDT)
Subject: [Tutor] critique my script!
In-Reply-To: <000301c6b725$0a453ae0$0201a8c0@XPpro>
Message-ID: <20060803223749.30495.qmail@web51602.mail.yahoo.com>

I rewrote my code with Alan's suggestions in mind.

#!/usr/bin/python

import os, os.path, glob

def glob_files(pattern, base_path = '.'):
	abs_base = os.path.abspath(base_path)
	#path_list = []
	#path_list.append(abs_base)
	globbed_dict = {}
	cwd = os.getcwd()
	for root,dirs,files in os.walk(abs_base):
		for name in dirs:
			path = os.path.join(root, name)
			print path
			os.chdir(path)
			matched_files = glob.glob(pattern)
			#print matched_files
			if matched_files != []:
				globbed_dict[path] = matched_files
			os.chdir(abs_base)
	os.chdir(cwd)
	return globbed_dict
	
if __name__ == "__main__":
	base_path = raw_input("Enter a base path: ")
	pattern = raw_input("Enter a glob pattern: ")
	
	str(base_path)
	str(pattern)
	
	globbed_dict = glob_files(pattern, base_path)
	
	print globbed_dict

However, the code still doesn't do exactly what I
want.

$ ./~/chris_python 126> ./find_items_01.py
Enter a base path: ./LearningToProgram
Enter a glob pattern: *.pyc
{}

Under the LearningToProgram directory is a test
directory that doesn't contain any .pyc files, so the
script's returned value is correct.  However, .pyc
files exist in the LearningToProgram directory, and I
would like to put those files in the dictionary too. 
Is there an elegant way to accomplish this?



From alan.gauld at freenet.co.uk  Fri Aug  4 01:26:41 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 4 Aug 2006 00:26:41 +0100
Subject: [Tutor] critique my script!
References: <20060803223749.30495.qmail@web51602.mail.yahoo.com>
Message-ID: <000301c6b754$46e386d0$0201a8c0@XPpro>

> Under the LearningToProgram directory is a test
> directory that doesn't contain any .pyc files, so the
> script's returned value is correct.  However, .pyc
> files exist in the LearningToProgram directory, and I
> would like to put those files in the dictionary too. 
> Is there an elegant way to accomplish this?

You just need to apply glob at the root level before starting
to walk the tree. Because your inner loop looks at the dirs
list you only glob the subdirectories, you need to glob the 
top level one too.

Alan G.

From python at venix.com  Fri Aug  4 01:49:42 2006
From: python at venix.com (Python)
Date: Thu, 03 Aug 2006 19:49:42 -0400
Subject: [Tutor] critique my script!
In-Reply-To: <20060803223749.30495.qmail@web51602.mail.yahoo.com>
References: <20060803223749.30495.qmail@web51602.mail.yahoo.com>
Message-ID: <1154648982.28304.622.camel@www.venix.com>

(Sorry about accidental posting before I had finished editing.)

On Thu, 2006-08-03 at 15:37 -0700, Christopher Spears wrote:
> I rewrote my code with Alan's suggestions in mind.
> 
> #!/usr/bin/python
> 
> import os, os.path, glob
> 
> def glob_files(pattern, base_path = '.'):
> 	abs_base = os.path.abspath(base_path)
> 	#path_list = []
> 	#path_list.append(abs_base)
> 	globbed_dict = {}
> 	cwd = os.getcwd()
> 	for root,dirs,files in os.walk(abs_base):
> 		for name in dirs:
> 			path = os.path.join(root, name)
> 			print path
> 			os.chdir(path)
> 			matched_files = glob.glob(pattern)
> 			#print matched_files
> 			if matched_files != []:
> 				globbed_dict[path] = matched_files
> 			os.chdir(abs_base)
> 	os.chdir(cwd)
> 	return globbed_dict
> 	
> if __name__ == "__main__":
> 	base_path = raw_input("Enter a base path: ")
> 	pattern = raw_input("Enter a glob pattern: ")
> 	
> 	str(base_path)
> 	str(pattern)
> 	
> 	globbed_dict = glob_files(pattern, base_path)
> 	
> 	print globbed_dict
> 
> However, the code still doesn't do exactly what I
> want.
> 
> $ ./~/chris_python 126> ./find_items_01.py
> Enter a base path: ./LearningToProgram
> Enter a glob pattern: *.pyc
> {}
> 
> Under the LearningToProgram directory is a test
> directory that doesn't contain any .pyc files, so the
> script's returned value is correct.  However, .pyc
> files exist in the LearningToProgram directory, and I
> would like to put those files in the dictionary too. 
> Is there an elegant way to accomplish this?

I won't answer for elegance, but you glob the dirs, but do not glob
root.  Now all of your code is knotted together pretty tightly, so it's
hard to make the change.  Suppose we have:

def dirs(abs_base):
	# (corrected from earlier accidental posting)
	yield abs_base
	for root,dirs,files in os.walk(abs_base):
		for name in dirs:
			yield os.path.join(root, name)

def globfiles(path,pattern):
	os.chdir(pattern)
	return glob.glob(pattern)

for path in dirs(abs_base):
	matched_files = globfiles(path, pattern)
	if matched_files:
		globbed_dict[path] = matched_files

Hopefully that's a step in the right direction.	
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp


From python at venix.com  Fri Aug  4 01:31:47 2006
From: python at venix.com (Python)
Date: Thu, 03 Aug 2006 19:31:47 -0400
Subject: [Tutor] critique my script!
In-Reply-To: <20060803223749.30495.qmail@web51602.mail.yahoo.com>
References: <20060803223749.30495.qmail@web51602.mail.yahoo.com>
Message-ID: <1154647907.28304.608.camel@www.venix.com>

On Thu, 2006-08-03 at 15:37 -0700, Christopher Spears wrote:
> I rewrote my code with Alan's suggestions in mind.
> 
> #!/usr/bin/python
> 
> import os, os.path, glob
> 
> def glob_files(pattern, base_path = '.'):
> 	abs_base = os.path.abspath(base_path)
> 	#path_list = []
> 	#path_list.append(abs_base)
> 	globbed_dict = {}
> 	cwd = os.getcwd()
> 	for root,dirs,files in os.walk(abs_base):
> 		for name in dirs:
> 			path = os.path.join(root, name)
> 			print path
> 			os.chdir(path)
> 			matched_files = glob.glob(pattern)
> 			#print matched_files
> 			if matched_files != []:
> 				globbed_dict[path] = matched_files
> 			os.chdir(abs_base)
> 	os.chdir(cwd)
> 	return globbed_dict
> 	
> if __name__ == "__main__":
> 	base_path = raw_input("Enter a base path: ")
> 	pattern = raw_input("Enter a glob pattern: ")
> 	
> 	str(base_path)
> 	str(pattern)
> 	
> 	globbed_dict = glob_files(pattern, base_path)
> 	
> 	print globbed_dict
> 
> However, the code still doesn't do exactly what I
> want.
> 
> $ ./~/chris_python 126> ./find_items_01.py
> Enter a base path: ./LearningToProgram
> Enter a glob pattern: *.pyc
> {}
> 
> Under the LearningToProgram directory is a test
> directory that doesn't contain any .pyc files, so the
> script's returned value is correct.  However, .pyc
> files exist in the LearningToProgram directory, and I
> would like to put those files in the dictionary too. 
> Is there an elegant way to accomplish this?

I won't answer for elegance, but you glob the dirs, but do not glob
root.  Now all of your code is knotted together pretty tightly, so it's
hard to make the change.  Suppose we have:

def dirs(abs_base):
	for root,dirs,files in os.walk(abs_base):
		yield root
		for name in dirs:
			yield os.path.join(root, name)

def globdir(path,pattern):
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp


From python at venix.com  Fri Aug  4 01:53:06 2006
From: python at venix.com (Python)
Date: Thu, 03 Aug 2006 19:53:06 -0400
Subject: [Tutor] critique my script!
In-Reply-To: <20060803223749.30495.qmail@web51602.mail.yahoo.com>
References: <20060803223749.30495.qmail@web51602.mail.yahoo.com>
Message-ID: <1154649186.28304.626.camel@www.venix.com>

On Thu, 2006-08-03 at 15:37 -0700, Christopher Spears wrote:
(in the os.walk processing)
>                         os.chdir(path)
>                         matched_files = glob.glob(pattern)
>From the os.walk documentation

Note: If you pass a relative pathname, don't change the current working
directory between resumptions of walk(). walk() never changes the
current directory, and assumes that its caller doesn't either.

Just making sure no one blindly copies this code without understanding
that an absolute path is essential.

-- 
Lloyd Kvam
Venix Corp


From python at venix.com  Fri Aug  4 01:56:48 2006
From: python at venix.com (Python)
Date: Thu, 03 Aug 2006 19:56:48 -0400
Subject: [Tutor] critique my script!
In-Reply-To: <000301c6b754$46e386d0$0201a8c0@XPpro>
References: <20060803223749.30495.qmail@web51602.mail.yahoo.com>
	<000301c6b754$46e386d0$0201a8c0@XPpro>
Message-ID: <1154649408.28304.629.camel@www.venix.com>

On Fri, 2006-08-04 at 00:26 +0100, Alan Gauld wrote:
> > Under the LearningToProgram directory is a test
> > directory that doesn't contain any .pyc files, so the
> > script's returned value is correct.  However, .pyc
> > files exist in the LearningToProgram directory, and I
> > would like to put those files in the dictionary too. 
> > Is there an elegant way to accomplish this?
> 
> You just need to apply glob at the root level before starting
> to walk the tree. Because your inner loop looks at the dirs
> list you only glob the subdirectories, you need to glob the 
> top level one too.

Which of course is all I suggested except with more shuffling than
necessary.

> 
> Alan G.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp


From ml.cyresse at gmail.com  Fri Aug  4 04:38:05 2006
From: ml.cyresse at gmail.com (Liam Clarke)
Date: Fri, 4 Aug 2006 14:38:05 +1200
Subject: [Tutor] Binary fractions, recommendations?
In-Reply-To: <44D22DB4.8060507@tds.net>
References: <b6f3249e0608030444l72823e44xf7e52ad009d6745e@mail.gmail.com>
	<44D22DB4.8060507@tds.net>
Message-ID: <b6f3249e0608031938v4b84acbclb6f5d706218ec009@mail.gmail.com>

Hmmm, and then I could use struct to swing it back... so, I'll be
using string slices to model bitshifting then.

Always found it quite strange that working mathematically with binary
is so hard in programming languages. Even in Scheme, which will
happily play with imaginary numbers.

Regards,

Liam

On 8/4/06, Kent Johnson <kent37 at tds.net> wrote:
> Liam Clarke wrote:
> > Problem is; I can't bitshift on floats, so can't test. Can't bitshift
> > on floats in C either.  Does anyone know how I could work on a binary
> > representation of a float? Any language at all, I'm desperate...
>
> In C you can certainly get access to the binary representation of a
> float as bytes. My C is really rusty but something like
> float x = 1.3;
> char* p = &x;
>
> will give you a pointer to the binary representation of x. You can do
> something similar with the struct module in Python; struct.pack() will
> give you a byte string containing the representation of a float.
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From kent37 at tds.net  Fri Aug  4 04:39:10 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 03 Aug 2006 22:39:10 -0400
Subject: [Tutor] critique my script!
In-Reply-To: <20060803223749.30495.qmail@web51602.mail.yahoo.com>
References: <20060803223749.30495.qmail@web51602.mail.yahoo.com>
Message-ID: <44D2B34E.2020808@tds.net>

Christopher Spears wrote:
> I rewrote my code with Alan's suggestions in mind.
>
> #!/usr/bin/python
>
> import os, os.path, glob
>
> def glob_files(pattern, base_path = '.'):
> 	abs_base = os.path.abspath(base_path)
> 	#path_list = []
> 	#path_list.append(abs_base)
> 	globbed_dict = {}
> 	cwd = os.getcwd()
> 	for root,dirs,files in os.walk(abs_base):
> 		for name in dirs:
> 			path = os.path.join(root, name)
> 			print path
> 			os.chdir(path)
> 			matched_files = glob.glob(pattern)
> 			#print matched_files
> 			if matched_files != []:
> 				globbed_dict[path] = matched_files
> 			os.chdir(abs_base)
> 	os.chdir(cwd)
> 	return globbed_dict
> 	
> if __name__ == "__main__":
> 	base_path = raw_input("Enter a base path: ")
> 	pattern = raw_input("Enter a glob pattern: ")
> 	
> 	str(base_path)
> 	str(pattern)
> 	
> 	globbed_dict = glob_files(pattern, base_path)
> 	
> 	print globbed_dict
>
> However, the code still doesn't do exactly what I
> want.
>
> $ ./~/chris_python 126> ./find_items_01.py
> Enter a base path: ./LearningToProgram
> Enter a glob pattern: *.pyc
> {}
>
> Under the LearningToProgram directory is a test
> directory that doesn't contain any .pyc files, so the
> script's returned value is correct.  However, .pyc
> files exist in the LearningToProgram directory, and I
> would like to put those files in the dictionary too. 
> Is there an elegant way to accomplish this?

The base_path directory will never appear in the dirs list from 
os.walk(). It will be returned as the root directory however. You could 
modify your program to glob the root directory instead of the list of 
dirs. Or use fnmatch.fnmatch() or fnmatch.filter(), which I still think 
is a better solution if you aren't married to glob():

import os, fnmatch

def glob_files(pattern, base_path = '.'):
	abs_base = os.path.abspath(base_path)
	globbed_dict = {}
	for root,dirs,files in os.walk(abs_base):
		matched_files = [ os.path.join(root, name) for name in fnmatch.filter(files, pattern) ]

		if matched_files: # Note: no need to compare to []
			globbed_dict[root] = matched_files
	return globbed_dict

Kent


From cspears2002 at yahoo.com  Fri Aug  4 06:03:25 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 3 Aug 2006 21:03:25 -0700 (PDT)
Subject: [Tutor] critique my script again!
Message-ID: <20060804040325.64157.qmail@web51604.mail.yahoo.com>

Here is the complete script with documentation:

#!/usr/bin/python

#This script prompts the user for a path and a glob
pattern.
#The script firsts looks in the directory denoted by
the path
#for a matching file.  If a match is found, the path
and file are added
#to a dictionary as a key and value.  This process is
repeated for all
#directories underneath the base directory.  Finally,
the directories and
#their corresponding files are formatted and printed
to the screen.
#Next step: rework script as GUI using PyGTK.
#Created by Chris Spears 7/3/06.
#Thanks to tutor at python.org.

import os, os.path, glob

def create_dict(path, globbed_dict):
	os.chdir(path)
	matched_files = glob.glob(pattern)
	if matched_files != []:
		globbed_dict[path] = matched_files
	return globbed_dict

def glob_files(pattern, base_path = '.'):
	abs_base = os.path.abspath(base_path)
	globbed_dict = {}
	cwd = os.getcwd()
	#Check the root directory first
	globbed_dict = create_dict(abs_base, globbed_dict)
	#Check other directories
	for root,dirs,files in os.walk(abs_base):
		for name in dirs:
			path = os.path.join(root, name)
			globbed_dict = create_dict(path, globbed_dict)
			os.chdir(abs_base)
	#Make sure the script returns to the user's original
directory.
	os.chdir(cwd)
	return globbed_dict
	
def print_dict(globbed_dict):
	paths = globbed_dict.keys()
	paths.sort()
	for p in paths:
		print p,": "
		file_list = globbed_dict[p]
		for f in file_list:
			print "\t",f
		
	
if __name__ == "__main__":
	base_path = raw_input("Enter a base path: ")
	pattern = raw_input("Enter a glob pattern: ")
	
	str(base_path)
	str(pattern)
	
	globbed_dict = glob_files(pattern, base_path)
	
	print_dict(globbed_dict)
		

	

	


From alan.gauld at freenet.co.uk  Fri Aug  4 09:30:59 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 4 Aug 2006 08:30:59 +0100
Subject: [Tutor] Binary fractions, recommendations?
References: <b6f3249e0608030444l72823e44xf7e52ad009d6745e@mail.gmail.com><44D22DB4.8060507@tds.net>
	<b6f3249e0608031938v4b84acbclb6f5d706218ec009@mail.gmail.com>
Message-ID: <002d01c6b797$ef21eb00$0201a8c0@XPpro>

> Always found it quite strange that working mathematically with 
> binary
> is so hard in programming languages. Even in Scheme, which will
> happily play with imaginary numbers.

I'm not clear on what you want to do.
You are working mathematically with binary all the time, in fact
that's the reason we get weird results sometimes because its
really binary and not decimal that we are manipulating.
Working in binary is the default behaviour.

>> > Problem is; I can't bitshift on floats, so can't test. Can't 
>> > bitshift
>> > on floats in C either.

Nor even in Assembler.
And that is because a float is really stored in IEEE representation
not in binary. You can bitshift the binary bits but it doesn't do
what you expect in that it doesn't multiply or divide the number
by powers of 2.

But the same is true of decimal numbers represented in
compacted reperesentations, you need to convert to a
normal number first.

> Does anyone know how I could work on a binary
> representation of a float? Any language at all,

Its the same in all languages; you need to convert
the IEE format to a binary format. The simplest way
will likely be a string but you can use two integers too.
Maybe writing a class? - In fact maybe a class exists
if you Google for it...

But why? What will be the advantage in having a
binary format float? And given the huge amount of memory
such a beast vwill consume (the reason we don't store
them like that in the first place) will the advantage
outweigh the cost?

>> In C you can certainly get access to the binary representation of a
>> float as bytes. My C is really rusty but something like
>> float x = 1.3;
>> char* p = &x;

That doesn't give you a binary representation of the
number just access to the bytes of the IEEE representation.
bit shifting that would be pretty pointless IMHO.

>> something similar with the struct module in Python;
> struct.pack() will give you a byte string containing the 
> representation of a float.

If its only the IEEE representation you want to bit shift then
this will be fine. But I'd be really interested in why anyone
would want to do that?

Alan G. 


From kent37 at tds.net  Fri Aug  4 12:43:22 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 04 Aug 2006 06:43:22 -0400
Subject: [Tutor] critique my script again!
In-Reply-To: <20060804040325.64157.qmail@web51604.mail.yahoo.com>
References: <20060804040325.64157.qmail@web51604.mail.yahoo.com>
Message-ID: <44D324CA.4070307@tds.net>

Christopher Spears wrote:
> import os, os.path, glob
>
> def create_dict(path, globbed_dict):
> 	os.chdir(path)
> 	matched_files = glob.glob(pattern)
> 	if matched_files != []:
> 		globbed_dict[path] = matched_files
> 	return globbed_dict
>   
As written create_dict() has the side-effect of changing the working 
dir, which you correct for in the caller. A better design would be to 
save and restore the correct dir in create_dict() so callers don't have 
to know that it has changed.
> def glob_files(pattern, base_path = '.'):
> 	abs_base = os.path.abspath(base_path)
> 	globbed_dict = {}
> 	cwd = os.getcwd()
> 	#Check the root directory first
> 	globbed_dict = create_dict(abs_base, globbed_dict)
> 	#Check other directories
> 	for root,dirs,files in os.walk(abs_base):
> 		for name in dirs:
> 			path = os.path.join(root, name)
> 			globbed_dict = create_dict(path, globbed_dict)
> 			os.chdir(abs_base)
> 	#Make sure the script returns to the user's original
> directory.
> 	os.chdir(cwd)
> 	return globbed_dict
>   
Rather than special-casing abs_base with its own call to create_dict, I 
would have the os.walk() loop act on root instead of dirs:

	for root,dirs,files in os.walk(abs_base):
		globbed_dict = create_dict(root, globbed_dict)


> 	
> def print_dict(globbed_dict):
> 	paths = globbed_dict.keys()
> 	paths.sort()
> 	for p in paths:
>   
Could be written more succinctly as
    for p in sorted(globbed_dict.keys()):

Kent

> 		print p,": "
> 		file_list = globbed_dict[p]
> 		for f in file_list:
> 			print "\t",f
> 		
> 	
> if __name__ == "__main__":
> 	base_path = raw_input("Enter a base path: ")
> 	pattern = raw_input("Enter a glob pattern: ")
> 	
> 	str(base_path)
> 	str(pattern)
> 	
> 	globbed_dict = glob_files(pattern, base_path)
> 	
> 	print_dict(globbed_dict)
> 		
>
> 	
>
> 	
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   



From kent37 at tds.net  Fri Aug  4 12:58:06 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 04 Aug 2006 06:58:06 -0400
Subject: [Tutor] Binary fractions, recommendations?
In-Reply-To: <002d01c6b797$ef21eb00$0201a8c0@XPpro>
References: <b6f3249e0608030444l72823e44xf7e52ad009d6745e@mail.gmail.com><44D22DB4.8060507@tds.net>
	<b6f3249e0608031938v4b84acbclb6f5d706218ec009@mail.gmail.com>
	<002d01c6b797$ef21eb00$0201a8c0@XPpro>
Message-ID: <44D3283E.6030003@tds.net>

Alan Gauld wrote:
> Does anyone know how I could work on a binary
>> representation of a float? Any language at all,
>>     
>>> In C you can certainly get access to the binary representation of a
>>> float as bytes. My C is really rusty but something like
>>> float x = 1.3;
>>> char* p = &x;
>>>       
>
> That doesn't give you a binary representation of the
> number just access to the bytes of the IEEE representation.
> bit shifting that would be pretty pointless IMHO.
>   
I guess it depends on what the OP means by "binary representation of a 
float". The request is ambiguous. I interpret it as, access to the 
actual bits of the representation, which the above code will give. 
Another interpretation is, an ASCII representation of the bits of the 
number, which seems to be what you mean.

Kent




From klappnase at freenet.de  Fri Aug  4 14:01:23 2006
From: klappnase at freenet.de (Michael Lange)
Date: Fri, 04 Aug 2006 12:01:23 -0000
Subject: [Tutor] Listbox selection
In-Reply-To: <LLEBIOJOJMEGEMFMBIOPOEBFCLAA.jgcox39@highstream.net>
References: <LLEBIOJOJMEGEMFMBIOPOEBFCLAA.jgcox39@highstream.net>
Message-ID: <20060210140136.46b7259c.klappnase@freenet.de>

Hi Joe,

On Thu, 3 Aug 2006 11:12:28 -0700
"Joe Cox" <jgcox39 at highstream.net> wrote:

> I am still having a problem getting my listbox's binded to the radiobuttons.
> I am getting closer.
> 
> ###Assign each Radiobutton with its own listbox values, show one selected
> button and one listbox###
> 
> 
> 
> from Tkinter import *
> 
> root = Tk()
> 
> var = StringVar()
> var.set('a')
> 
> { 'Aluminum' : ['Wrought', 'Die cast'],
>        'Steel'   : ['Low Carbon', 'Medium-high carbon','Alloy'] }
> 

Didn't you want to keep a reference to the dictionary?

> 
> def radio_command():
>     if var.get() == 'a':
>         # button with value 'a' selected
>         listbox.insert('a') #here I am trying to put the string starting
> with 'Steel' in the listbox
>     elif var.get() == 'b':
>         # button with value 'b' selected
>         listbox.insert('b')   #here I am trying to put the string starting
> with 'Aluminum' in the listbox
> 
> 
> 
> radio_a = Radiobutton(root,text="Steel", variable=var, value='a',
> command=radio_command).pack()

Are you aware that pack() returns None, so you actually assign None to all your
radio_* variables; if you want to keep access to the widgets you need to do:

    radio_a = Radiobutton()
    radio_a.pack()

> radio_b = Radiobutton(root,text="Aluminum", variable=var, value='b',
> command=radio_command).pack()
> radio_c = Radiobutton(root,text="Cast Iron", variable=var, value='c',
> command=radio_command).pack()
> radio_d = Radiobutton(root,text="Nickel", variable=var, value='d',
> command=radio_command).pack()
> radio_e = Radiobutton(root,text="Titaniuim", variable=var, value='e',
> command=radio_command).pack()
> 
> 
> listbox = Listbox(root)
> for item in ():
>     listbox.insert(END, item)

The last two lines don't really seem to have much sense, if you want an empty Listbox,
just don't insert anything.

> listbox.pack(side=LEFT, fill=BOTH)
> 
> root.mainloop()
> 


I am not sure what your question is here, maybe you want to try something like (untested):

    var = StringVar()
    var.set('Steel')
    listbox = Listbox(root)
    listbox.pack(side=LEFT, fill=BOTH)

    metals = {'Aluminum' : ['Wrought', 'Die cast'],
       'Steel'   : ['Low Carbon', 'Medium-high carbon','Alloy'] }

    def radio_command():
        listbox.delete(0, 'end')
        for m in metals[var.get()]:
            listbox.insert('end', m)

    for metal in metals.keys():
        # assuming that you don't need to keep references to all buttons
        Radiobutton(root, text=metal, variable=var, value=metal, command=radio_command).pack()

    # fill the listbox with initial values
    radio_command()

I hope this helps

Michael




From matthew.williams at cancer.org.uk  Fri Aug  4 14:58:23 2006
From: matthew.williams at cancer.org.uk (Matt Williams)
Date: Fri, 04 Aug 2006 13:58:23 +0100
Subject: [Tutor] (*args, **kwargs)
Message-ID: <44D3446F.5060902@cancer.org.uk>

Dear All,

I have learnt to do bits of python, but one of the things I cannot get 
my head around is the *args, **kwargs syntax.

I have tried reading stuff on the web, and I have a copy of the python 
cookbook (which uses it as a recipe early on) but I still don't 
understand it.

Please could someone explain _very_ slowly?

Apologies for the gross stupidity,

Matt


-- 
http://acl.icnet.uk/~mw
http://adhominem.blogsome.com/
+44 (0)7834 899570

From rabidpoobear at gmail.com  Fri Aug  4 15:23:38 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 04 Aug 2006 08:23:38 -0500
Subject: [Tutor] Listbox selection
In-Reply-To: <20060210140136.46b7259c.klappnase@freenet.de>
References: <LLEBIOJOJMEGEMFMBIOPOEBFCLAA.jgcox39@highstream.net>
	<20060210140136.46b7259c.klappnase@freenet.de>
Message-ID: <44D34A5A.2040706@gmail.com>

Michael Lange wrote:
> Hi Joe,
> [snip post]
Fix your date/time please Michael.
I don't think it's been February 10th for quite some time :)

From jordangreenberg at gmail.com  Fri Aug  4 18:38:54 2006
From: jordangreenberg at gmail.com (Jordan Greenberg)
Date: Fri, 04 Aug 2006 12:38:54 -0400
Subject: [Tutor] (*args, **kwargs)
In-Reply-To: <44D3446F.5060902@cancer.org.uk>
References: <44D3446F.5060902@cancer.org.uk>
Message-ID: <44D3781E.40204@gmail.com>

Matt Williams wrote:
> Dear All,
> 
> I have learnt to do bits of python, but one of the things I cannot get 
> my head around is the *args, **kwargs syntax.
> 
> I have tried reading stuff on the web, and I have a copy of the python 
> cookbook (which uses it as a recipe early on) but I still don't 
> understand it.
> 
> Please could someone explain _very_ slowly?
> 
> Apologies for the gross stupidity,
> 
> Matt

Basically, *args and **kwargs allows you to collect arguments.
Normally, you'd do something like:
*args collects any arguments (other then the positional ones) into a
list, and **kwargs collects arguments into a dictionary.
In [6]: def foo(a, b, c):
   ...:         print a, b, c
   ...:

In [7]: foo(1, 2, 3)
1 2 3

but, say you wanted to make it so it could accept any number of
arguments, you could use *args like so:
In [4]: def foo(*args):
   ...:         print args
   ...:         for each in args:
   ...:                 print each
   ...:

In [5]: foo(1, 2, 3, 4)
(1, 2, 3, 4)
1
2
3
4

Notice how all the parameters i passed to foo are collected in the list
args.

**kwargs collects arguments of the form key=value into a dictionary,
like so:

In [15]: def foo(**kwargs):
   ....:        print kwargs
   ....:

In [16]: foo(name="Jordan", email="jordangreenberg at gmail.com")
{'name': 'Jordan', 'email': 'jordangreenberg at gmail.com'}

Your functions can then use the list/dictionary as normal.
You can also use these in conjunction with normal positional parameters:

In [27]: def foo(a, b, c, *args, **kwargs):
   ....:        print "Positional arguments:"
   ....:        print a, b, c
   ....:        print "Non-positional argument list:"
   ....:        print args
   ....:        for each in args:
   ....:                print each
   ....:        print "Keyword argument list:"
   ....:        print kwargs
   ....:        for key in kwargs.keys():
   ....:                print "Key: ", key
   ....:                print "Data: ", kwargs[key]
   ....:

In [28]: foo(1, "monkey", 7.5, 10, 11, 12, name="jordan",
email="jordangreenberg at gmail.com")
Positional arguments:
1 monkey 7.5
Non-positional argument list:
(10, 11, 12)
10
11
12
Keyword argument list:
{'name': 'jordan', 'email': 'jordangreenberg at gmail.com'}
Key:  name
Data:  jordan
Key:  email
Data:  jordangreenberg at gmail.com

So, to summarize, *args and **kwargs are basically there so you can
build your functions so that they can accept a variable number of arguments.

We had a thread about this not terribly long ago too, and Kent Johnson
had a great explanation (as per usual) so I expect he'll be along
shortly with either a link to that thread or a better explanation then
mine!

Anyway, I hope this helps!
-Jordan Greenberg


From dyoo at hkn.eecs.berkeley.edu  Fri Aug  4 18:40:18 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 4 Aug 2006 09:40:18 -0700 (PDT)
Subject: [Tutor] Multiple buttons, One callback (fwd)
Message-ID: <Pine.LNX.4.64.0608040937540.32576@hkn.eecs.berkeley.edu>

Hi everyone,

Can someone help with Michael's question?  Unfortunately, I can't answer 
it at the moment.

Here it is below.  (I've stripped off the image attachment.)


---------- Forwarded message ----------
Date: Fri, 4 Aug 2006 09:32:48 -0700 (PDT)
From: Michael Cochez <michaelcochez at yahoo.com>
To: dyoo at hkn.eecs.berkeley.edu
Subject: Multiple buttons, One callback

Hi Danny,
I've just been reading your reply on this subject at
http://mail.python.org/pipermail/tutor/2005-September/041358.html
about a year ago.
I need something like this but also something more:
I'm making an app with an interface that is going to
look like in the added image. The "=" buttons are
there to copy the contents of the previous lines to
the current line.
To make the buttons tried a lot of things but the
problem is: the number of buttons is always different
(one less as the number of day) so it can be none or
20 or something else. So i putted the creation in a
for loop.
But now the real problem: every button must have its
own callback(because the linenumber is different) So
my question is: how can I give each button its 'own'
callback while only having one (the callbacks are all
the same but with another value of linenumber. I added
a piece of the code to show what i mean.

michaelcochez,

PS:excuse me if my English isn't comprehensive, I'm
not a native English speaker (I speak Dutch at home)

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Buttons.py
Type: text/x-python-script
Size: 803 bytes
Desc: 2612874683-Buttons.py
Url : http://mail.python.org/pipermail/tutor/attachments/20060804/916ceb88/attachment.bin 

From matthew.williams at cancer.org.uk  Fri Aug  4 18:49:12 2006
From: matthew.williams at cancer.org.uk (Matt Williams)
Date: Fri, 04 Aug 2006 17:49:12 +0100
Subject: [Tutor] (*args, **kwargs)
In-Reply-To: <20060804143807.96438.qmail@web55615.mail.re4.yahoo.com>
References: <20060804143807.96438.qmail@web55615.mail.re4.yahoo.com>
Message-ID: <44D37A88.1080109@cancer.org.uk>

Dear Etienne & Carlos,

Thanks so much for that - much clearer!

I guess the next question is _how_ do you use it intelligently? I'm 
interested because I'm trying to put stuff into a db using sqlobject.

Obviously one way would be:

class MyClass:

     def __init__(self,**kw)
         self.property1 = self.kw['property1']
	self.property2 = self.kw['property2']
	etc....

Does anyone know of an example of this ?

Thanks,

Matt

From anilmrn at yahoo.com  Fri Aug  4 19:19:43 2006
From: anilmrn at yahoo.com (anil maran)
Date: Fri, 4 Aug 2006 10:19:43 -0700 (PDT)
Subject: [Tutor] hi
Message-ID: <20060804171943.48837.qmail@web55913.mail.re3.yahoo.com>

i have a textbox in a webform
i save it in postgres
in postgres, it has several newlines and it is properly displayed
when i redisplay using cheetah
it just displays in a single line and looks ugly

is there a simple way to replace newlines with <br >

thanks

 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060804/256be4b5/attachment.html 

From anilmrn at yahoo.com  Fri Aug  4 20:46:36 2006
From: anilmrn at yahoo.com (anil maran)
Date: Fri, 4 Aug 2006 11:46:36 -0700 (PDT)
Subject: [Tutor] python unicode - help
Message-ID: <20060804184636.91744.qmail@web55904.mail.re3.yahoo.com>

postgres takes utf8
and ie has different encodings, sometimes western, sometimes utf8
when someone submits data to the form with different,  there is an error, how do we determine the encoding, automatically convert to utf8 and then feed to postgres

thanks a lot

 			
---------------------------------
See the all-new, redesigned Yahoo.com.  Check it out.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060804/27a04222/attachment.htm 

From K.Weinert at gmx.net  Fri Aug  4 21:05:19 2006
From: K.Weinert at gmx.net (K.Weinert at gmx.net)
Date: Fri, 04 Aug 2006 21:05:19 +0200
Subject: [Tutor] Config file directory (was: File like object for Windows
	registry)
Message-ID: <20060804190519.59480@gmx.net>

Hello again!

Thanks a lot for the helpful hints! I was not aware that expanduser does also work on windows since I am on WinMe... 

My current approach is this:

import platform, os.path

def _detect_filepath():
  op_sys= platform.system()
  op_rel= platform.release()
  if op_sys=="Windows":
    if op_rel in ["XP"]:
      return os.path.expanduser("~")
    else:
      return os.path.dirname(__file__) # store in package directory
  elif op_sys=="Linux":
    return os.path.expanduser("~")
  else:
    raise "Unsupported operating system."

What do you think? If someone with a win2000 system could tell me the return value of platform.release(), that would be nice.

Kind regards,
Karsten.

----- Original Message -----
Hello!

My app should run on debian and windows platforms. For storing the configuration data, I use the ConfigParser module.

What I find difficult is to determine a place for my configuration file. On debian, it is simply

os.path.join(os.path.expanduser("~")),"myconfig")

but what am I supposed to do on Windows? I think a clean solution would be to create a file-like object that reads and writes to the registry, is it?

Kind regards,
Karsten.

-- 


Echte DSL-Flatrate dauerhaft f?r 0,- Euro*. Nur noch kurze Zeit!
"Feel free" mit GMX DSL: http://www.gmx.net/de/go/dsl

From granted14 at yahoo.com  Fri Aug  4 16:38:07 2006
From: granted14 at yahoo.com (Etienne Robillard)
Date: Fri, 4 Aug 2006 10:38:07 -0400 (EDT)
Subject: [Tutor] (*args, **kwargs)
In-Reply-To: <44D3446F.5060902@cancer.org.uk>
Message-ID: <20060804143807.96438.qmail@web55615.mail.re4.yahoo.com>


--- Matt Williams <matthew.williams at cancer.org.uk>
wrote:

> Dear All,
> 
> I have learnt to do bits of python, but one of the
> things I cannot get 
> my head around is the *args, **kwargs syntax.
> I have tried reading stuff on the web, and I have a
> copy of the python 
> cookbook (which uses it as a recipe early on) but I
> still don't 
> understand it.
> 
> Please could someone explain _very_ slowly?

Here's how I've learned it so far:

First, there's a convention for 'passing lists as
arguments', which is simply to use 'kw' (I prefer that
one) or 'kwargs' with a '*' in front of them.

But first you need to initialize your data structure
properly, thus:

kw = {} # a empty dictionnary

Then you may want to add stuff inside that kw object:

kw['foo'] = "bar"

Now consider the following data structure:
class Foo:
      def __init__(self, **kw):
          # do something with kw objects here.
          pass

Then here's how to pass the whole kw object as a
argument list:
Foo(**kw) 

HTH,

Etienne

> Apologies for the gross stupidity,

P.S - There's no such thing here, sorry. :-)
 
> Matt
> 
> 
> -- 
> http://acl.icnet.uk/~mw
> http://adhominem.blogsome.com/
> +44 (0)7834 899570


--
Etienne Robillard <erob at cpan.org>
JID: incidah AT njs.netlab.cz
YMS/MSN: granted14 AT yahoo.com
TEL: +1  514.962.7703
URL: http://www.assembla.com/wiki/show/stn-portfolio/

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

From anilmrn at yahoo.com  Fri Aug  4 22:29:42 2006
From: anilmrn at yahoo.com (anil maran)
Date: Fri, 4 Aug 2006 13:29:42 -0700 (PDT)
Subject: [Tutor] how to use
Message-ID: <20060804202942.49301.qmail@web55909.mail.re3.yahoo.com>

list comprehensions to return a dictionary
thanks a lot

 			
---------------------------------
See the all-new, redesigned Yahoo.com.  Check it out.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060804/977ecbc0/attachment.html 

From anilmrn at yahoo.com  Fri Aug  4 22:32:50 2006
From: anilmrn at yahoo.com (anil maran)
Date: Fri, 4 Aug 2006 13:32:50 -0700 (PDT)
Subject: [Tutor] can some one explain
Message-ID: <20060804203250.49054.qmail@web55908.mail.re3.yahoo.com>

decorators and why uses them makes it faster than if then else blocks because of decorators using hash structures

i dont understand this
please help me


 		
---------------------------------
Do you Yahoo!?
 Next-gen email? Have it all with the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060804/70b87be0/attachment.htm 

From klappnase at freenet.de  Fri Aug  4 23:30:43 2006
From: klappnase at freenet.de (Michael Lange)
Date: Fri, 4 Aug 2006 23:30:43 +0200
Subject: [Tutor] Multiple buttons, One callback (fwd)
In-Reply-To: <Pine.LNX.4.64.0608040937540.32576@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0608040937540.32576@hkn.eecs.berkeley.edu>
Message-ID: <20060804233043.69d05361.klappnase@freenet.de>

> ---------- Forwarded message ----------
> Date: Fri, 4 Aug 2006 09:32:48 -0700 (PDT)
> From: Michael Cochez <michaelcochez at yahoo.com>
> To: dyoo at hkn.eecs.berkeley.edu
> Subject: Multiple buttons, One callback
> 
> Hi Danny,
> I've just been reading your reply on this subject at
> http://mail.python.org/pipermail/tutor/2005-September/041358.html
> about a year ago.
> I need something like this but also something more:
> I'm making an app with an interface that is going to
> look like in the added image. The "=" buttons are
> there to copy the contents of the previous lines to
> the current line.
> To make the buttons tried a lot of things but the
> problem is: the number of buttons is always different
> (one less as the number of day) so it can be none or
> 20 or something else. So i putted the creation in a
> for loop.
> But now the real problem: every button must have its
> own callback(because the linenumber is different) So
> my question is: how can I give each button its 'own'
> callback while only having one (the callbacks are all
> the same but with another value of linenumber. I added
> a piece of the code to show what i mean.

I would use a lambda for this, like:


def makeidentical(linenumber):

    print "the linenumber is: %d" % (linenumber)


for day in datelist:

    a=datelist.index(day)

    if a>0:#on every line exept the first

        identicalbutton=Button(frame2,text="=",command=lambda : makeidentical(a))

        identicalbutton.grid(row=a+2,column=3,sticky=W)

        frame2widgets.append(identicalbutton)


I hope this helps

Michael


From kent37 at tds.net  Sat Aug  5 00:53:11 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 04 Aug 2006 18:53:11 -0400
Subject: [Tutor] hi
In-Reply-To: <20060804171943.48837.qmail@web55913.mail.re3.yahoo.com>
References: <20060804171943.48837.qmail@web55913.mail.re3.yahoo.com>
Message-ID: <44D3CFD7.4080401@tds.net>

anil maran wrote:
> i have a textbox in a webform
> i save it in postgres
> in postgres, it has several newlines and it is properly displayed
> when i redisplay using cheetah
> it just displays in a single line and looks ugly
>
> is there a simple way to replace newlines with <br >

s.replace('\n', '<br>')

Kent


From kent37 at tds.net  Sat Aug  5 00:55:27 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 04 Aug 2006 18:55:27 -0400
Subject: [Tutor] python unicode - help
In-Reply-To: <20060804184636.91744.qmail@web55904.mail.re3.yahoo.com>
References: <20060804184636.91744.qmail@web55904.mail.re3.yahoo.com>
Message-ID: <44D3D05F.90604@tds.net>

anil maran wrote:
> postgres takes utf8
> and ie has different encodings, sometimes western, sometimes utf8
> when someone submits data to the form with different,  there is an 
> error, how do we determine the encoding, automatically convert to utf8 
> and then feed to postgres

Generally a browser will return form data in the same encoding as the 
form itself. Set the encoding of the form to utf8 using a meta tag and 
the browser will return utf8 to you. The meta tag looks like this and 
goes in the <head> section of your form:
<meta http-equiv="content-type" content="text/html; charset=utf-8" />

Kent


From kent37 at tds.net  Sat Aug  5 00:56:20 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 04 Aug 2006 18:56:20 -0400
Subject: [Tutor] how to use
In-Reply-To: <20060804202942.49301.qmail@web55909.mail.re3.yahoo.com>
References: <20060804202942.49301.qmail@web55909.mail.re3.yahoo.com>
Message-ID: <44D3D094.3000005@tds.net>

anil maran wrote:
> list comprehensions to return a dictionary

A list comprehension creates a list. Can you explain why you want this?

Kent


From kent37 at tds.net  Sat Aug  5 00:57:29 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 04 Aug 2006 18:57:29 -0400
Subject: [Tutor] can some one explain
In-Reply-To: <20060804203250.49054.qmail@web55908.mail.re3.yahoo.com>
References: <20060804203250.49054.qmail@web55908.mail.re3.yahoo.com>
Message-ID: <44D3D0D9.10507@tds.net>

anil maran wrote:
> decorators and why uses them makes it faster than if then else blocks 
> because of decorators using hash structures

Do you mean dictionaries rather than decorators? I'm not sure what you 
are talking about.

Kent


From kent37 at tds.net  Sat Aug  5 01:00:48 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 04 Aug 2006 19:00:48 -0400
Subject: [Tutor] Multiple buttons, One callback (fwd)
In-Reply-To: <20060804233043.69d05361.klappnase@freenet.de>
References: <Pine.LNX.4.64.0608040937540.32576@hkn.eecs.berkeley.edu>
	<20060804233043.69d05361.klappnase@freenet.de>
Message-ID: <44D3D1A0.7090304@tds.net>

Michael Lange wrote:
>> ---------- Forwarded message ----------
>> Date: Fri, 4 Aug 2006 09:32:48 -0700 (PDT)
>> From: Michael Cochez <michaelcochez at yahoo.com>
>> To: dyoo at hkn.eecs.berkeley.edu
>> Subject: Multiple buttons, One callback
>>
>> Hi Danny,
>> I've just been reading your reply on this subject at
>> http://mail.python.org/pipermail/tutor/2005-September/041358.html
>> about a year ago.
>> I need something like this but also something more:
>> I'm making an app with an interface that is going to
>> look like in the added image. The "=" buttons are
>> there to copy the contents of the previous lines to
>> the current line.
>> To make the buttons tried a lot of things but the
>> problem is: the number of buttons is always different
>> (one less as the number of day) so it can be none or
>> 20 or something else. So i putted the creation in a
>> for loop.
>> But now the real problem: every button must have its
>> own callback(because the linenumber is different) So
>> my question is: how can I give each button its 'own'
>> callback while only having one (the callbacks are all
>> the same but with another value of linenumber. I added
>> a piece of the code to show what i mean.
>>     
>
> I would use a lambda for this, like:
>
>
> def makeidentical(linenumber):
>
>     print "the linenumber is: %d" % (linenumber)
>
>
> for day in datelist:
>
>     a=datelist.index(day)
>
>     if a>0:#on every line exept the first
>
>         identicalbutton=Button(frame2,text="=",command=lambda : makeidentical(a))
>   
You have to bind the current value of a in the lambda, otherwise all the 
callbacks will use the final value of a. One way to do this is with a 
default argument to the lambda:

  identicalbutton=Button(frame2,text="=",command=lambda a=a : makeidentical(a))

Another way is with a separate function such as make_callback in the original post.

Kent

>
>   



From ag at adamgomaa.com  Fri Aug  4 19:05:46 2006
From: ag at adamgomaa.com (Adam Gomaa)
Date: Fri, 04 Aug 2006 13:05:46 -0400
Subject: [Tutor] IDLE Crashing
Message-ID: <44D37E6A.7030409@adamgomaa.com>

I'm having trouble with this script. When I run it, it crashes IDLE... 
which is no fun. :(

I'm running Ubuntu 6.06 w/ python 2.4

When I say crash, I mean really _crash_. IDLE stop responding, and I 
have to killall idle && killall python2.4 before I can restart it (cause 
python2.4 keeps the TCP port open, I'm assuming)

A few notes:
list.txt is a text file with 99 lines, each with three letters on it.
In ./retrieves, I have 99 files of style [xyz].1.txt. (in addition to 
list.txt) These are retrieved HTML pages that have the HTML stripped 
(the actual script is part of a series of scripts to download and format 
my school's course catalog)
It seems to crash on the final iteration of the second for loop, no 
matter what file it's on at that point (which I've changed by changing 
x&y in 'for each in filelist[x:y]:' to diffrent values), so I don't 
think it has anything to do with the actual files it's accessing.

-----
#2006 Adam Gomaa, Public Domain
listfiles=open('retrieves/list.txt','r')
fileread=listfiles.read() ##reads list.txt and assings to fileread
filelist=[]
filelist=fileread.splitlines() ##each filelist word is 3-letter combo
listfiles.close()
count,count2=0,0 ##for debugging
textstringlist=[]
goodlist1=[]
for each in filelist[:-50]: ##filelist[x:y] always crashes for any value 
of x,y
    print count ##for debugging
    count=count+1
    textfileread=open('retrieves/%s.1.txt' % each,'r')
    textstring=textfileread.read()
    textfileread.close()
    each=each.upper()
    textstringlist=textstring.split(each)##if I comment out from here...
    for each2 in textstringlist[:]: #changing to textstringlist[3:-3] 
still results in crash
        count2=count2+1
        print count2,'is count2' ##this gets quite high, into thousands, 
before stopping on the final iteration (and crashing)
        if 'Prerequisites' in each2:
            goodlist1.append(each2)##to here, it doesn't crash
print goodlist1
------

Anyone have an insight?
If someone would like me to I can tar the 99 files & list.txt and post a 
link.
Thanks,

From rabidpoobear at gmail.com  Sat Aug  5 08:52:51 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sat, 05 Aug 2006 01:52:51 -0500
Subject: [Tutor] IDLE Crashing
In-Reply-To: <44D37E6A.7030409@adamgomaa.com>
References: <44D37E6A.7030409@adamgomaa.com>
Message-ID: <44D44043.7070603@gmail.com>

Hi Adam.
Adam Gomaa wrote:
> I'm having trouble with this script. When I run it, it crashes IDLE... 
> which is no fun. :(
>
> I'm running Ubuntu 6.06 w/ python 2.4
>
> When I say crash, I mean really _crash_. IDLE stop responding, and I 
> have to killall idle && killall python2.4 before I can restart it (cause 
> python2.4 keeps the TCP port open, I'm assuming)
>
> A few notes:
> list.txt is a text file with 99 lines, each with three letters on it.
> In ./retrieves, I have 99 files of style [xyz].1.txt. (in addition to 
> list.txt) These are retrieved HTML pages that have the HTML stripped 
> (the actual script is part of a series of scripts to download and format 
> my school's course catalog)
> It seems to crash on the final iteration of the second for loop, no 
> matter what file it's on at that point (which I've changed by changing 
> x&y in 'for each in filelist[x:y]:' to diffrent values), so I don't 
> think it has anything to do with the actual files it's accessing.
>
> -----
> #2006 Adam Gomaa, Public Domain
> listfiles=open('retrieves/list.txt','r')
> fileread=listfiles.read() ##reads list.txt and assings to fileread
> filelist=[]
> filelist=fileread.splitlines() ##each filelist word is 3-letter combo
> listfiles.close()
> count,count2=0,0 ##for debugging
> textstringlist=[]
> goodlist1=[]
> for each in filelist[:-50]: ##filelist[x:y] always crashes for any value 
> of x,y
>     print count ##for debugging
>     count=count+1
>     textfileread=open('retrieves/%s.1.txt' % each,'r')
>     textstring=textfileread.read()
>     textfileread.close()
>     each=each.upper()
>     textstringlist=textstring.split(each)##if I comment out from here...
>   
Did you really mean to split the string on every occurrence of 'each' 
and not on each newline?
>     for each2 in textstringlist[:]: #changing to textstringlist[3:-3] 
> still results in crash
>         count2=count2+1
>         print count2,'is count2' ##this gets quite high, into thousands, 
> before stopping on the final iteration (and crashing)
>         if 'Prerequisites' in each2:
>             goodlist1.append(each2)##to here, it doesn't crash
> print goodlist1
> ------
>
> Anyone have an insight?
> If someone would like me to I can tar the 99 files & list.txt and post a 
> link.
>   
I can't tell what's wrong without looking at your input files and a more 
detailed explanation of what
you're trying to do.  If someone else comes along with help, that's 
great, but if not, I'll download the
tar and see what I can do.
> Thanks,
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From jon.papageorgiou at wachovia.com  Sat Aug  5 12:05:36 2006
From: jon.papageorgiou at wachovia.com (jon.papageorgiou at wachovia.com)
Date: Sat, 5 Aug 2006 06:05:36 -0400
Subject: [Tutor] Jon Papageorgiou is out of the office.
Message-ID: <OF27DFB311.893D6D6C-ON852571C1.003771FE-852571C1.003771FF@notes.wachovia.com>





I will be Out of the Office
Start Date: 8/4/2006.
End Date: 8/12/2006.


If you are in need of immediate support:

Don?t call the Help Desk
The Help Desk (590-9000) consultants are not trained to provide Command
Center support.
While they might attempt to assist you with your problem, the results could
compromise the
system and require extra repair work for the CC Support group.

So who do you call?  What do you do now?

PICCT vs. RAPS2
When deciding on which application to use, think of it this way.  PICCT is
your local mechanic shop and RAPS2 is the nearest car dealership.  If you
have a problem or break with current hardware/software that you use, please
open a PICCT ticket by following the steps below.  If you are looking for
something new, a new workstation or application, please use the RAPS2
request system.

Problem/Issue Support (PICCT)
A problem issue is an issue that deals with current software/hardware
already installed on your workstation.

For Normal Issues Please Follow this Procedure:
All issues must have a PICCT ticket created. All tickets must be
transferred to the "ts-prdsvs-ndso-cmd center support" group. You must
include an accurate description of the problem in the ticket. For example,
"The pc station is experiencing problems" is not an accurate description.
You must make sure your contact info is correct.
***If you are not the location specified in the PICCT ticket contact info,
please
     include where you are currently sitting in the "Brief Description"
field.  Any
     incorrect information will lead to a delay in service.  Also, please
include
       any pertinent information such as PC name. The more infomation we
have the
       sooner we can fix your problem.
 For Urgent Issues requiring an "Immediate Response", Please Follow this
Procedure:
 Page the On-Call Support Person via http://esm.wachovia.net/ListOncall.asp
 Include the Ticket Number
 Include ?Issue:?  - Brief description of the issue (first text line of
email)
 Include ?Contact:?  - Person to contact (second text line of email)
 Include ?Contact #:?- Phone # of person to contact, no 800 numbers (third
text line of email)

***Please don?t contact support individuals directly when reporting support
related issues.

***Please send all support related correspondence to the ?Command Center
Infrastructure Support? Notes ID

***Although we Support the Command Center 7/24/365 we are not staffed
     7/24/365, so please be patient for response.

New Request for Work (RAPS2)
This is a request for new software/hardware that you currently do not have
but need, such as workstation or software installs and any changes that are
not related to a problem issue. These types of requests would not be
problem related but new requests for work.  CCIS will provide you with
support on these issues.

Don?t use Remedy/Capture/PICCT/SM&A Work Request System for ?New Work
Requests?.

Instead please use the new corporate standard, RAPS2, located @
http://raps2.wachovia.net/raps2

Here are some steps that you might find to be helpful:
       1. Go to the website above, and click on "Submit a New Request"
       2. Select the plus sign (+) next to "Enterprise System Management
(ESM)".
       3. Select the green "Command Center Support Team Request".
       4. Enter your employee ID #
       5. Fill out all the fields with an aqua background.  Enter your
contact information.
           (For the Services Requested drop-down list, select "Command
Center Support")
       6. Click "next"
       7. You can add other information if you want, or just click on
"Finish!" If you have questions or concerns, please feel free to call us @
704-427-8179 or email us.
         ?Command Center Infrastructure Support? Notes ID

If your email is not concerning support, I will respond to your message
when I return.

From kent37 at tds.net  Sat Aug  5 13:56:04 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 05 Aug 2006 07:56:04 -0400
Subject: [Tutor] IDLE Crashing
In-Reply-To: <44D37E6A.7030409@adamgomaa.com>
References: <44D37E6A.7030409@adamgomaa.com>
Message-ID: <44D48754.5020804@tds.net>

Adam Gomaa wrote:
> I'm having trouble with this script. When I run it, it crashes IDLE... 
> which is no fun. :(
>
> I'm running Ubuntu 6.06 w/ python 2.4
>
> When I say crash, I mean really _crash_. IDLE stop responding, and I 
> have to killall idle && killall python2.4 before I can restart it (cause 
> python2.4 keeps the TCP port open, I'm assuming)
>
> A few notes:
> list.txt is a text file with 99 lines, each with three letters on it.
> In ./retrieves, I have 99 files of style [xyz].1.txt. (in addition to 
> list.txt) These are retrieved HTML pages that have the HTML stripped 
> (the actual script is part of a series of scripts to download and format 
> my school's course catalog)
> It seems to crash on the final iteration of the second for loop, no 
> matter what file it's on at that point (which I've changed by changing 
> x&y in 'for each in filelist[x:y]:' to diffrent values), so I don't 
> think it has anything to do with the actual files it's accessing.
>   
It looks like for some reason there is a problem with printing 
goodlist1. I can't think of why that would happen. (At first I thought, 
maybe there are special chars in the data, but printing a list prints 
the repr() of the list elements, so any special chars should be escaped. 
I also suspected the length of goodlist1 but it sounds like you have 
tried with a smaller subset of the data.)

A couple of things you could try. If you put these prints before "print 
goodlist1" it will confirm that you do exit the last loop.
# get some idea how much data is in goodlist
print len(goodlist1)
print len(repr(goodlist1))

Try running your program from the command line instead of inside IDLE.

Posting the tar file sounds like a good idea.
Kent
> -----
> #2006 Adam Gomaa, Public Domain
> listfiles=open('retrieves/list.txt','r')
> fileread=listfiles.read() ##reads list.txt and assings to fileread
> filelist=[]
> filelist=fileread.splitlines() ##each filelist word is 3-letter combo
> listfiles.close()
> count,count2=0,0 ##for debugging
> textstringlist=[]
> goodlist1=[]
> for each in filelist[:-50]: ##filelist[x:y] always crashes for any value 
> of x,y
>     print count ##for debugging
>     count=count+1
>     textfileread=open('retrieves/%s.1.txt' % each,'r')
>     textstring=textfileread.read()
>     textfileread.close()
>     each=each.upper()
>     textstringlist=textstring.split(each)##if I comment out from here...
>     for each2 in textstringlist[:]: #changing to textstringlist[3:-3] 
> still results in crash
>         count2=count2+1
>         print count2,'is count2' ##this gets quite high, into thousands, 
> before stopping on the final iteration (and crashing)
>         if 'Prerequisites' in each2:
>             goodlist1.append(each2)##to here, it doesn't crash
> print goodlist1
> ------
>
> Anyone have an insight?
> If someone would like me to I can tar the 99 files & list.txt and post a 
> link.
> Thanks,
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   



From meiermic at ee.ethz.ch  Sat Aug  5 14:08:04 2006
From: meiermic at ee.ethz.ch (Michael Meier)
Date: Sat, 05 Aug 2006 14:08:04 +0200
Subject: [Tutor] IDLE Crashing
Message-ID: <44D48A24.7040102@ee.ethz.ch>

I'm also having trouble when running IDLE under Debian 3.1 (Kernel
2.6.12). I often run into the same problem (IDLE not responding with the
only solution to killall idle) as Adam Gomaa just after starting up IDLE
and typing in some characters.

E.g. I'm starting up IDLE and typing in "import soc" when IDLE suddenly
stops responding. This happens while I'm typing and _not_ when executing
a line or a bunch of code.

This phenomenon is not reproducable, it just happens from time to time.
Unfortunately it happens rather often which does not amuse me ;)


Does anyone experience the same problem as I? Is there a common solution
to Adams and my problems?

Thanks,
Michael Meier

P.S. I'm new to this list... I think its a very interesting and friendly
place to be :)

From anilmrn at yahoo.com  Sat Aug  5 14:55:08 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sat, 5 Aug 2006 05:55:08 -0700 (PDT)
Subject: [Tutor] how to use
In-Reply-To: <44D48232.5000507@tds.net>
Message-ID: <20060805125508.96687.qmail@web55907.mail.re3.yahoo.com>

 the program has several groups
 i hav a table with titles
 and contents are in different table content_table

 each title -> is title_id in content_table

 so every time i display a group, i have to select title and then 
 select all messagesw with title_id

 now the problem is, I have to display more than one group in a single 
 page in cheetah,

 so after displaying the title, i have to now choose the message to display

 since i have a list of [] of messages

 i need to index into them
 so i thought i will make them return a dictionary indexed with URL 
 which is unique

 thanks
>     anil maran wrote:
>     > list comprehensions to return a dictionary
>
>     A list comprehension creates a list. Can you explain why you want
>     this?
>
>     Kent
>
>     _______________________________________________
>     Tutor maillist - Tutor at python.org
>     http://mail.python.org/mailman/listinfo/tutor

 		
---------------------------------
Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060805/08b435be/attachment.html 

From anilmrn at yahoo.com  Sat Aug  5 14:58:27 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sat, 5 Aug 2006 05:58:27 -0700 (PDT)
Subject: [Tutor] Generic functions
In-Reply-To: <20060804203250.49054.qmail@web55908.mail.re3.yahoo.com>
Message-ID: <20060805125827.55285.qmail@web55915.mail.re3.yahoo.com>


i have a hard time understanding, why these are a better idea than if then else structures . Here is the page, that is not clear

thanks a lot 

First Try at Generic FunctionsWiki:First Try at G??? Edit Goto Help. First Try at Generic Functions ... However,  I have long meant to use his generic functions, as I think they seem pretty ...
blog.ianbicking.org/first-try-at-generic-functions.html - 41k - Cached - Similar pages Python Buzz Forum - First Try at Generic FunctionsFirst Try at Generic Functions, Posted: Nov 1, 2005 2:42 AM ... Original Post:  First Try at Generic Functions Feed Title: Ian Bicking ...
www.artima.com/forums/flat.jsp?forum=122&thread=134755 - 17k -Cached - Similar pages

 """Why are generic functions better than this technique?"""
 
   Your technique will not affect any modules that used from jsonify import jsonify to obtain the function, because they won't see your replacement version.
   Your technique degrades performance linearly with the number of types added, while generic functions use a dispatch tree that uses hash tables, binary search, or other lookup techniques as appropriate. The dispatch tree is automatically balanced to test the most discriminating criteria first. So, adding a new type in the JSON example has virtually no effect on performance of the jsonify() function, versus one extra function-call of overhead added by your approach for each new type.
   Your technique can only add tests at the highest precedence level, which means that if there's any overlap in conditions between what you are adding, and what exists, you will need to code a more complex "if" rule, and you will need to know what other existing rules overlap. (Which means that only linear extension is possible, and that some tests will be repeated unnecessarily.)
   Your technique cannot take advantage of any overlap in the conditions being tested.  For example, the various isinstance() calls in your version repeatedly walk the object's class' __mro__ to see if it contains the target classes.  The generic function, however, will do this walk once, no matter how many types are registered, and then call the correct function.
   Your code is buggy; it should return jsonify_orig(obj).  :)
 In other words, generic functions are far superior to monkeypatching for creating an extensible operation, which is why the Python standard library uses a simple form of them for things like copying and pickling. However, the RuleDispatch generic function implementation supports automating the registration process and lookup tables for simple functions (using @dispatch.on) and allows for building dispatch trees on arbitrary computations with full generic functions (using @dispatch.generic).
 


 		
---------------------------------
Groups are talking. We&acute;re listening. Check out the handy changes to Yahoo! Groups. 
 		
---------------------------------
Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060805/0c9a26a3/attachment.htm 

From kent37 at tds.net  Sat Aug  5 15:04:05 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 05 Aug 2006 09:04:05 -0400
Subject: [Tutor] how to use
In-Reply-To: <20060805125508.96687.qmail@web55907.mail.re3.yahoo.com>
References: <20060805125508.96687.qmail@web55907.mail.re3.yahoo.com>
Message-ID: <44D49745.2030308@tds.net>

I still don't understand what you are trying to do. Can you post a short 
example of the data you have and the dictionary you would like to create 
from it?

Kent

anil maran wrote:
> the program has several groups
>  i hav a table with titles
>  and contents are in different table content_table
>
>  each title -> is title_id in content_table
>
>  so every time i display a group, i have to select title and then
>  select all messagesw with title_id
>
>  now the problem is, I have to display more than one group in a single
>  page in cheetah,
>
>  so after displaying the title, i have to now choose the message to 
> display
>
>  since i have a list of [] of messages
>
>  i need to index into them
>  so i thought i will make them return a dictionary indexed with URL
>  which is unique
>
>  thanks
>
>     > anil maran wrote:
>     > > list comprehensions to return a dictionary
>     >
>     > A list comprehension creates a list. Can you explain why you want
>     > this?
>     >
>     > Kent
>     >
>     > _______________________________________________
>     > Tutor maillist - Tutor at python.org
>     > http://mail.python.org/mailman/listinfo/tutor
>
> ------------------------------------------------------------------------
> Yahoo! Messenger with Voice. Make PC-to-Phone Calls 
> <http://us.rd.yahoo.com/mail_us/taglines/postman1/*http://us.rd.yahoo.com/evt=39663/*http://voice.yahoo.com> 
> to the US (and 30+ countries) for 2?/min or less.
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



From ismaelgf at adinet.com.uy  Sat Aug  5 19:25:18 2006
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Sat, 05 Aug 2006 14:25:18 -0300
Subject: [Tutor] IDLE Crashing
In-Reply-To: <44D48754.5020804@tds.net>
References: <44D37E6A.7030409@adamgomaa.com> <44D48754.5020804@tds.net>
Message-ID: <44D4D47E.20209@adinet.com.uy>

Kent Johnson escribi?:
> Adam Gomaa wrote:
>   
>> I'm having trouble with this script. When I run it, it crashes IDLE... 
>> which is no fun. :(
>>
>> I'm running Ubuntu 6.06 w/ python 2.4
>>
>> When I say crash, I mean really _crash_. IDLE stop responding, and I 
>> have to killall idle && killall python2.4 before I can restart it (cause 
>> python2.4 keeps the TCP port open, I'm assuming)
>>
>> A few notes:
>> list.txt is a text file with 99 lines, each with three letters on it.
>> In ./retrieves, I have 99 files of style [xyz].1.txt. (in addition to 
>> list.txt) These are retrieved HTML pages that have the HTML stripped 
>> (the actual script is part of a series of scripts to download and format 
>> my school's course catalog)
>> It seems to crash on the final iteration of the second for loop, no 
>> matter what file it's on at that point (which I've changed by changing 
>> x&y in 'for each in filelist[x:y]:' to diffrent values), so I don't 
>> think it has anything to do with the actual files it's accessing.
>>   
>>     
> It looks like for some reason there is a problem with printing 
> goodlist1. I can't think of why that would happen. (At first I thought, 
> maybe there are special chars in the data, but printing a list prints 
> the repr() of the list elements, so any special chars should be escaped. 
> I also suspected the length of goodlist1 but it sounds like you have 
> tried with a smaller subset of the data.)
>   

IDLE becomes **very** unresponsive when printing long lists/strings. 
Great doses of patience and a good processor usually let you live 
through (Idle uses 100%, you have to take out of view the long text to 
make it become responsive again). At least, this happens on Windows 
(maybe other platforms don't have this problem?). I get this a lot when 
working with long HTML.
There must be something wrong in the way IDLE prints long strings...

Ismael

From ag at adamgomaa.com  Sat Aug  5 20:13:10 2006
From: ag at adamgomaa.com (Adam Gomaa)
Date: Sat, 05 Aug 2006 14:13:10 -0400
Subject: [Tutor] IDLE Crashing
In-Reply-To: <44D4D47E.20209@adinet.com.uy>
References: <44D37E6A.7030409@adamgomaa.com> <44D48754.5020804@tds.net>
	<44D4D47E.20209@adinet.com.uy>
Message-ID: <44D4DFB6.70802@adamgomaa.com>


> IDLE becomes **very** unresponsive when printing long lists/strings. 
> Great doses of patience and a good processor usually let you live 
> through (Idle uses 100%, you have to take out of view the long text to 
> make it become responsive again). At least, this happens on Windows 
> (maybe other platforms don't have this problem?). I get this a lot when 
> working with long HTML.
> There must be something wrong in the way IDLE prints long strings...
>
> Ismael
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   
Yes, as it turns out this was the issue. I entered the script 
line-by-line, and it finished the loops just fine- but at the 'print 
goodlist1' line, it froze. (it has to print about 1300 entries)

I'm rewriting the script so it writes the list to an external file 
within the loop, so I won't have to deal with such huge lists inside idle.

Thanks for everyone's help!

Adam

From josipl2000 at yahoo.com  Sat Aug  5 19:11:48 2006
From: josipl2000 at yahoo.com (josip)
Date: Sat, 5 Aug 2006 10:11:48 -0700 (PDT)
Subject: [Tutor] forum
Message-ID: <20060805171148.15741.qmail@web60819.mail.yahoo.com>

look at this
  www.python-forum.org

 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060805/1a9805f0/attachment.html 

From john at fouhy.net  Sun Aug  6 01:20:29 2006
From: john at fouhy.net (John Fouhy)
Date: Sun, 6 Aug 2006 11:20:29 +1200
Subject: [Tutor] (*args, **kwargs)
In-Reply-To: <44D37A88.1080109@cancer.org.uk>
References: <20060804143807.96438.qmail@web55615.mail.re4.yahoo.com>
	<44D37A88.1080109@cancer.org.uk>
Message-ID: <5e58f2e40608051620m53f76603xd9c634f651fdd563@mail.gmail.com>

On 05/08/06, Matt Williams <matthew.williams at cancer.org.uk> wrote:
> I guess the next question is _how_ do you use it intelligently? I'm
> interested because I'm trying to put stuff into a db using sqlobject.

One common place to use it is when you are dealing with inheritance.

For example, suppose I'm writing a Tkinter program, and I want to make
my own GUI component.  I might write:

class MyCustomFrame(Tkinter.Frame):
    def __init__(self, parent, foo, bar, baz=None, **kw):
        Tkinter.Frame.__init__(self, parent, **kw)
        # do something with foo, bar, baz; etc.

The reason for doing this is that Tkinter objects support all kinds of
keyword arguments, and this lets me support them in my custom code
without having to explicitely list them all.

Of course, I could also set/override some of the Tkinter keyword
arguments.  eg, I could make a frame with a pink background like this:

class PinkFrame(Tkinter.Frame):
    def __init__(self, parent, **kw):
        kw['background'] = 'pink'         # line 2
        Tkinter.Frame.__init__(self, parent, **kw)

(note that I can't skip line 2, and replace line 3 with
"Tkinter.Frame.__init__(self, parent, background='pink', **kw)"
because if kw already contains a value for background, python will get
confused and throw an exception..)

> class MyClass:
>
>      def __init__(self,**kw)
>          self.property1 = self.kw['property1']
>         self.property2 = self.kw['property2']
>         etc....
>
> Does anyone know of an example of this ?

I'm not sure there's much value in using **kw if you know exactly what
keyword arguments you're expecting.  Although you can be a bit fancy,
eg:

    def __init__(self, **kw):
        for key in **kw:
            setattr(self, key, kw[key])

But you run the risk of writing obscure code that's hard to follow..

If you were implementing the range() function, you would use *args.
Perhaps something like this:

def range(*args):
    if len(args) == 1:
        return _range(0, args[0], 1)
    elif len(args) == 2:
        return _range(args[0], args[1], 1)
    else:
        return _range(args[0], args[1], args[2])    # could replace
this with: return _range(*args)

def _range(start, stop, step):
    # etc

HTH!

-- 
John.

From john at fouhy.net  Sun Aug  6 01:22:32 2006
From: john at fouhy.net (John Fouhy)
Date: Sun, 6 Aug 2006 11:22:32 +1200
Subject: [Tutor] how to use
In-Reply-To: <20060804202942.49301.qmail@web55909.mail.re3.yahoo.com>
References: <20060804202942.49301.qmail@web55909.mail.re3.yahoo.com>
Message-ID: <5e58f2e40608051622q1181fffle548ce30d86fffe3@mail.gmail.com>

On 05/08/06, anil maran <anilmrn at yahoo.com> wrote:
> list comprehensions to return a dictionary

Well, hyou can use the dict function.  eg:

dict((x, x**x) for x in range(10))

-- 
John.

From brian at daviesinc.com  Sun Aug  6 02:22:06 2006
From: brian at daviesinc.com (Brian Gustin)
Date: Sat, 05 Aug 2006 20:22:06 -0400
Subject: [Tutor] forum
In-Reply-To: <20060805171148.15741.qmail@web60819.mail.yahoo.com>
References: <20060805171148.15741.qmail@web60819.mail.yahoo.com>
Message-ID: <44D5362E.8080301@daviesinc.com>

Signed up, but it never send me the confirmation email (yes, I used a 
valid email address) . It's been 2 hours, and still no email.

How the HECK does one contact the forum admin to ask them to activate my 
account?  I signed up with support at phplogix.com

Grrr.. I really hate forums that have admins that dont post contact 
information or provide some way to contact them when there's a 
registration issue. :(



josip wrote:
> look at this
> www.python-forum.org <http://www.python-forum.org>
> 
> ------------------------------------------------------------------------
> Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great 
> rates starting at 1?/min. !DSPAM:44d500e691801941725006! 
> <http://us.rd.yahoo.com/mail_us/taglines/postman7/*http://us.rd.yahoo.com/evt=39666/*http://messenger.yahoo.com>
> 
> 
>  <http://us.rd.yahoo.com/mail_us/taglines/postman7/*http://us.rd.yahoo.com/evt=39666/*http://messenger.yahoo.com>
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> !DSPAM:44d500e691801941725006!
>  <http://us.rd.yahoo.com/mail_us/taglines/postman7/*http://us.rd.yahoo.com/evt=39666/*http://messenger.yahoo.com>

From gwhjr at cox.net  Sun Aug  6 03:44:26 2006
From: gwhjr at cox.net (Grady Henry)
Date: Sat, 5 Aug 2006 18:44:26 -0700
Subject: [Tutor] This will run on Outlook but not Outlook Express
Message-ID: <000701c6b8f9$d9d329e0$8b4a6244@valued61da873e>

The following script will run on Microsoft Outlook but not on Outlook Express:

from win32com.client import Dispatch
s=Dispatch("Mapi.Session")
s.Logon()
newMsg = s.Outbox.Messages.Add("Hi from Python", "Hello")
recip = newMsg.Recipients.Add("Greg Hart", "SMTP:gwhjr at rock.com")
newMsg.Send()
s.DeliverNow()

I was wondering if I could write a script that would run on both Outlook and Outlook Express.

Can anybody help?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060805/7fcdb528/attachment.htm 

From anilmrn at yahoo.com  Sun Aug  6 08:48:39 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sat, 5 Aug 2006 23:48:39 -0700 (PDT)
Subject: [Tutor] help regarding forms...
Message-ID: <20060806064839.11558.qmail@web55902.mail.re3.yahoo.com>

 <form method="post" action="/newtodo"> 
 i did by mistake 
 <form method="/newtodo"> 
 
and i got an empty page 
 
http://localhost/newtodo?category= 
 
can one of you guys explain what this is and tell me if this can be 
 usefully used like 
 
http://groups.google.com/group/webpy/post?_done=%2Fgroup%2Fwebpy%3F&_... 
 
and if Yes 
 how to use this 
 http://localhost/newtodo?category= 
 http://localhost/todo?category="health"&length=10 
 
and how to do the 
 class todo: 
       def GET 
 
and 
 class newtodo: 
       def POST: 
 
thanks a lot 
 		
---------------------------------
Do you Yahoo!?
 Everyone is raving about the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060805/4073090d/attachment.html 

From anilmrn at yahoo.com  Sun Aug  6 08:53:22 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sat, 5 Aug 2006 23:53:22 -0700 (PDT)
Subject: [Tutor] how to use
In-Reply-To: <44D49745.2030308@tds.net>
Message-ID: <20060806065322.55820.qmail@web55907.mail.re3.yahoo.com>

TABLE RSS TITLES:
Greg Reinacker's Weblog  and it s url
 The Design of Software  and its url
Paul Graham 
Wingedpig.com - Mark Fletcher's Blog  
Aaron Swartz: The Weblog  
 BusinessWeek Online -- New Tech in Asia 

TABLE 2 has all the feedposts for eg.,

     Simple Tips for Longer Living  -->
     What is going on here?  -->
     Nutrition Basics  -->
     I Love the University  -->
     On Losing Weight 
     Digg reddit  
     Where's the Outrage?  Around the Corner in a Cafe with Power.  
     What Drives Bloggers?  
     Paul Graham Eats Breakfast (Director's Cut)  
     Being Copied  
one in bold is pg, rsest is aaron,
when i get out contents of blog by select and query sql statements they return lists indexed by numbers and hence it is difficult to map to the original title - i have to do monkeypatching
so i want a dictionary indexed by the url http://paulgraham.infogami.com/blog/atom.xml

and another element indexed by http://www.aaronsw.com/weblog/index.xml
thanks

Kent Johnson <kent37 at tds.net> wrote: I still don't understand what you are trying to do. Can you post a short 
example of the data you have and the dictionary you would like to create 
from it?

Kent

anil maran wrote:
> the program has several groups
>  i hav a table with titles
>  and contents are in different table content_table
>
>  each title -> is title_id in content_table
>
>  so every time i display a group, i have to select title and then
>  select all messagesw with title_id
>
>  now the problem is, I have to display more than one group in a single
>  page in cheetah,
>
>  so after displaying the title, i have to now choose the message to 
> display
>
>  since i have a list of [] of messages
>
>  i need to index into them
>  so i thought i will make them return a dictionary indexed with URL
>  which is unique
>
>  thanks
>
>     > anil maran wrote:
>     > > list comprehensions to return a dictionary
>     >
>     > A list comprehension creates a list. Can you explain why you want
>     > this?
>     >
>     > Kent
>     >
>     > _______________________________________________
>     > Tutor maillist - Tutor at python.org
>     > http://mail.python.org/mailman/listinfo/tutor
>
> ------------------------------------------------------------------------
> Yahoo! Messenger with Voice. Make PC-to-Phone Calls 
>  
> to the US (and 30+ countries) for 2???/min or less.
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


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


 		
---------------------------------
Do you Yahoo!?
 Next-gen email? Have it all with the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060805/43bf50d4/attachment.htm 

From anilmrn at yahoo.com  Sun Aug  6 08:54:34 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sat, 5 Aug 2006 23:54:34 -0700 (PDT)
Subject: [Tutor] how to use
In-Reply-To: <5e58f2e40608051622q1181fffle548ce30d86fffe3@mail.gmail.com>
Message-ID: <20060806065434.48463.qmail@web55912.mail.re3.yahoo.com>

what does

 x**x) do?

2nd) what is the key for the dictionary, i assume x is the value of the dictionary



John Fouhy <john at fouhy.net> wrote: On 05/08/06, anil maran  wrote:
> list comprehensions to return a dictionary

Well, hyou can use the dict function.  eg:

dict((x, x**x) for x in range(10))

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


 		
---------------------------------
Groups are talking. We&acute;re listening. Check out the handy changes to Yahoo! Groups. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060805/ad385238/attachment.html 

From anilmrn at yahoo.com  Sun Aug  6 09:58:07 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sun, 6 Aug 2006 00:58:07 -0700 (PDT)
Subject: [Tutor] error, i m unable to find the error for past 1week,
	this doesnt work, please help me out
Message-ID: <20060806075807.41593.qmail@web55905.mail.re3.yahoo.com>

You can override the web.internalerror function to have it to do other 
 interesting things. For example, I have infogami send me an email with 
 the full debugerror traceback whenever there's a crash: 
 olderror = web.internalerror 
 def error(): 
     olderror() 
     import sys, traceback 
     tb = sys.exc_info() 
     text = """From: the bugman <y... at example.com> 
 To: the bugfixer <y... at example.com> 
 Subject: bug: %s: %s (%s) 
 Content-Type: multipart/mixed; boundary="----here----" 
 
------here---- 
 Content-Type: text/plain 
 Content-Disposition: inline 
 
%s 
 
%s 
 
------here---- 
 Content-Type: text/html; name="bug.html" 
 Content-Disposition: attachment; filename="bug.html" 
 
""" % (tb[0], tb[1], web.ctx.path, web.ctx.method+' '+web.ctx.home+web.ctx.f 
 ullpath, 
      ''.join(traceback.format_exception(*tb)), 
     text += str(web.djangoerror()) 
     utils.send('... at example.com', '... at example.com', text) 
 
web.internalerror = error    

 		
---------------------------------
Yahoo! Music Unlimited - Access over 1 million songs.Try it free. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060806/c9079525/attachment.htm 

From anilmrn at yahoo.com  Sun Aug  6 10:00:55 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sun, 6 Aug 2006 01:00:55 -0700 (PDT)
Subject: [Tutor] can you explain string replacement syntax and comma
	separated statements
Message-ID: <20060806080055.3019.qmail@web55901.mail.re3.yahoo.com>

    text = """From: the bugman <y... at example.com> 
 To: the bugfixer <y... at example.com> 
 Subject: bug: %s: %s (%s) 
 Content-Type: multipart/mixed; boundary="----here----" 
 
------here---- 
 Content-Type: text/plain 
 Content-Disposition: inline 
 
%s 
 
%s 
 
------here---- 
 Content-Type: text/html; name="bug.html" 
 Content-Disposition: attachment; filename="bug.html" 
 
""" % (tb[0], tb[1], web.ctx.path, web.ctx.method+' '+web.ctx.home+web.ctx.f 
 ullpath, 
      ''.join(traceback.format_exception(*tb)), 
     text += str(web.djangoerror()) 



 		
---------------------------------
Do you Yahoo!?
 Everyone is raving about the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060806/7a85df7a/attachment.html 

From alan.gauld at freenet.co.uk  Sun Aug  6 10:00:48 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 6 Aug 2006 09:00:48 +0100
Subject: [Tutor] This will run on Outlook but not Outlook Express
References: <000701c6b8f9$d9d329e0$8b4a6244@valued61da873e>
Message-ID: <002801c6b92e$6e5c3a50$0201a8c0@XPpro>

> from win32com.client import Dispatch
> s=Dispatch("Mapi.Session")

I don't think Outlook express uses MAPI.
MAPI is a strictly Microsoft protocol and only used in Outlook 
and a few other clients that try to talk to Exchange servers.

Outlook Express is a much more conventional mailtool 
that talks POP/SMTP (and maybe IMAP?)

> I was wondering if I could write a script that would run on 
> both Outlook and Outlook Express.

Trying to use a COM object model for that will be extemely difficult.
I'd look at using the standard email tools with Python since both 
Outlook and OE talk standard internet mail protocols.

Alan G.

From rfquerin at gmail.com  Sun Aug  6 15:52:13 2006
From: rfquerin at gmail.com (Richard Querin)
Date: Sun, 6 Aug 2006 09:52:13 -0400
Subject: [Tutor] Raw files and jpeg thumbnail extraction
Message-ID: <7d81675b0608060652y2982cd99n6bda808f394e0e24@mail.gmail.com>

I am interested in extracting jpeg thumbnails that are stored in my camera's
Canon .CR2 raw files. Does anybody know of any python libraries with this
kind of functionality? Is dcraw the only way to implement this
functionality? I'm writing a simple gui to selectively process raw files
into jpegs, but I really would like to pick the photos based on thumbnails.
I read somewhere that most digital camera raw files contain jpeg thumbnails
that would be much quicker to load than doing an on-the-fly conversion just
to get the thumbnails.

Can anybody point me in a good direction on this?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060806/bdbd32b1/attachment.htm 

From alan.gauld at freenet.co.uk  Sun Aug  6 17:31:41 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 6 Aug 2006 16:31:41 +0100
Subject: [Tutor] how to use
References: <20060806065434.48463.qmail@web55912.mail.re3.yahoo.com>
Message-ID: <003201c6b96d$6ae368a0$0201a8c0@XPpro>

Hi Anil,

Are you reading a tutorial?
Most of the questions you are asking should be covered
in any standard tutorial.

> what does
>
> x**x) do?

Its equivalent to

pow(x,x)
ie raises x to the power x.

> 2nd) what is the key for the dictionary, i assume x is the value of 
> the dictionary

> dict((x, x**x) for x in range(10))

x is the key and x**x is the value.

HTH,

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


From alan.gauld at freenet.co.uk  Sun Aug  6 17:42:19 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 6 Aug 2006 16:42:19 +0100
Subject: [Tutor] can you explain string replacement syntax and
	commaseparated statements
References: <20060806080055.3019.qmail@web55901.mail.re3.yahoo.com>
Message-ID: <005001c6b96e$e6fab910$0201a8c0@XPpro>

> can you explain string replacement syntax and commaseparated 
> statements

string substitution replaces the 5 %s comvbinations with the 5
values after the % sign

A simplied example is:

s = "hello %s, welcome to %s" % ('world','python')

Your example just uses triple quotes to allow the string
to wrap and has more substitutions. The 5 values are also
less direct but all yield strings eventually!

The comma separated assignment looks like a mistake to me!
A simplified form looks like:

s = "Hello", s += "world"

Which yields a syntax error.
Are you sure its not a semi-colon, in which case it just combines
the two instructions on a single line.

If so its very bad coding style IMHO but is legal.

HTH,

Alan G.

>    text = """From: the bugman <y... at example.com>
> To: the bugfixer <y... at example.com>
> Subject: bug: %s: %s (%s)
> Content-Type: multipart/mixed; boundary="----here----"
>
> ------here---- 
> Content-Type: text/plain
> Content-Disposition: inline
>
> %s
>
> %s
>
> ------here---- 
> Content-Type: text/html; name="bug.html"
> Content-Disposition: attachment; filename="bug.html"
>
> """ % (tb[0], tb[1], web.ctx.path, web.ctx.method+' 
> '+web.ctx.home+web.ctx.f
> ullpath,
>      ''.join(traceback.format_exception(*tb)),
>     text += str(web.djangoerror())
>
>
>
>
> ---------------------------------
> Do you Yahoo!?
> Everyone is raving about the  all-new Yahoo! Mail Beta. 


From dyoo at hkn.eecs.berkeley.edu  Sun Aug  6 22:17:44 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 6 Aug 2006 13:17:44 -0700 (PDT)
Subject: [Tutor] help regarding forms...
In-Reply-To: <20060806064839.11558.qmail@web55902.mail.re3.yahoo.com>
References: <20060806064839.11558.qmail@web55902.mail.re3.yahoo.com>
Message-ID: <Pine.LNX.4.64.0608061305050.7607@hkn.eecs.berkeley.edu>



On Sat, 5 Aug 2006, anil maran wrote:

> http://localhost/newtodo?category=
>
> can one of you guys explain what this is

Hi Anil,

Are you taking some kind of internet web-development class?  You seem to 
be asking a lot of web-development questions.  In the absence of context, 
I'm not sure what to do other than to point you to the standard RFC on 
Uniform Resource Locators:

     http://www.faqs.org/rfcs/rfc1738.html

and see if that addresses your question.


> class todo:
>       def GET
>
> and
> class newtodo:
>       def POST:


Have you looked at any Python CGI tutorials yet?

     http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/

From dyoo at hkn.eecs.berkeley.edu  Sun Aug  6 22:27:38 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 6 Aug 2006 13:27:38 -0700 (PDT)
Subject: [Tutor] can you explain string replacement syntax and comma
 separated statements
In-Reply-To: <20060806080055.3019.qmail@web55901.mail.re3.yahoo.com>
References: <20060806080055.3019.qmail@web55901.mail.re3.yahoo.com>
Message-ID: <Pine.LNX.4.64.0608061318200.7607@hkn.eecs.berkeley.edu>



On Sun, 6 Aug 2006, anil maran wrote:

>    text = """From: the bugman <y... at example.com>
> To: the bugfixer <y... at example.com>
> Subject: bug: %s: %s (%s)
> Content-Type: multipart/mixed; boundary="----here----"

[text example cut]

Hi Anil,

Anil, take a look at:

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

Does this address your question?


On a high-level view of your questions so far:  Are you running into 
problems because you can't find the documentation?  Or is the issue that 
the documentation is unclear?

From bob.nienhuis at gmail.com  Sun Aug  6 23:56:29 2006
From: bob.nienhuis at gmail.com (Bob Nienhuis)
Date: Sun, 6 Aug 2006 14:56:29 -0700
Subject: [Tutor] Community documentation framework?
Message-ID: <45109da50608061456v67580f30oc42d1d18453f1226@mail.gmail.com>

Have you had the experience of finding a nifty bit of code on the
web, trying it out, and then discovering that technique
only worked in version X.YY, or requires module Z that
is no longer available?

Well perhaps we can address this situation.

I would like to see an online system that facilitates
the collaborative production, cataloging and updating of
community documentation. See an article, "Rethinking Community
Documentation" by Andy Oram
<
http://www.onlamp.com/pub/a/onlamp/2006/07/06/rethinking-community-documentation.html
>.

Features I would like to see:
    A Wikipedia-like capacity for community update-ability/modifiability
    of documentation submissions.

    Database for cataloging available packages, modules, FAQs, How-Tos
    tutorials, cookbook code fragments etc. Should have capacity for
    developers to add and others to add to their contributions.

    Oram suggests a rating system for submissions so users can assess
    the quality of submissions, and point to parts that need modification
    or clarification..

    Might use TurboGears, Django AJAX or other web framework?

I think main Python documentation is great, but there is a lot
of stuff out there that isn't documented so well, or needs
updating. This project is intended to adress that need.

What would you like to see?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060806/a4225c50/attachment.html 

From Hans.Dushanthakumar at navman.com  Mon Aug  7 01:27:35 2006
From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar)
Date: Mon, 7 Aug 2006 11:27:35 +1200
Subject: [Tutor] Python for basic web-testing
Message-ID: <6054E9239B849044B9544941B2F8DDD9994A80@bnt-nav-akl-exh.navman.bnt.local>

Hi,
   How do I use python for basic web-tasks like inputting data or
clicking buttons on web-pages. For eg, how do I enter my username and
password and click on the "OK" button on the yahoo mail page?
I had a look at the webbrowser module documentation
(http://www.python.org/doc/current/lib/module-webbrowser.html), but it
doesnt seem to support clicking buttons or sending data.
Thanks,
Hans
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060807/7a3374fe/attachment.html 

From python-tutor at v.igoro.us  Mon Aug  7 01:44:39 2006
From: python-tutor at v.igoro.us (Dustin J. Mitchell)
Date: Sun, 06 Aug 2006 18:44:39 -0500
Subject: [Tutor] Python for basic web-testing
In-Reply-To: <6054E9239B849044B9544941B2F8DDD9994A80@bnt-nav-akl-exh.navman.bnt.local>
References: <6054E9239B849044B9544941B2F8DDD9994A80@bnt-nav-akl-exh.navman.bnt.local>
Message-ID: <44D67EE7.1040207@v.igoro.us>

Hans Dushanthakumar wrote:
> Hi,
>    How do I use python for basic web-tasks like inputting data or
> clicking buttons on web-pages. For eg, how do I enter my username and
> password and click on the "OK" button on the yahoo mail page?
> I had a look at the webbrowser module documentation
> (http://www.python.org/doc/current/lib/module-webbrowser.html), but it
> doesnt seem to support clicking buttons or sending data.

All the stuff you need is right here:

http://wwwsearch.sourceforge.net/

Specifically, the clicking buttons part is in ClientForm.

Dustin

From jordangreenberg at gmail.com  Mon Aug  7 01:45:18 2006
From: jordangreenberg at gmail.com (Jordan Greenberg)
Date: Sun, 06 Aug 2006 19:45:18 -0400
Subject: [Tutor] Python for basic web-testing
In-Reply-To: <6054E9239B849044B9544941B2F8DDD9994A80@bnt-nav-akl-exh.navman.bnt.local>
References: <6054E9239B849044B9544941B2F8DDD9994A80@bnt-nav-akl-exh.navman.bnt.local>
Message-ID: <44D67F0E.3090600@gmail.com>

Hans Dushanthakumar wrote:
> Hi,
>    How do I use python for basic web-tasks like inputting data or
> clicking buttons on web-pages. For eg, how do I enter my username and
> password and click on the "OK" button on the yahoo mail page?
> I had a look at the webbrowser module documentation
> (http://www.python.org/doc/current/lib/module-webbrowser.html), but it
> doesnt seem to support clicking buttons or sending data.
> Thanks,
> Hans
>  

Hi Hans,
	I'm sure its possible, though i haven't a clue how you'd go about doing
it. If its just for testing and you don't need it integrated with
python, you might want to check out Greasemonkey
(http://greasemonkey.mozdev.org/) or Chickenfoot
(http://groups.csail.mit.edu/uid/chickenfoot/) which make those kinds of
tasks absurdly easy.


From Hans.Dushanthakumar at navman.com  Mon Aug  7 02:19:21 2006
From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar)
Date: Mon, 7 Aug 2006 12:19:21 +1200
Subject: [Tutor] Python for basic web-testing
Message-ID: <6054E9239B849044B9544941B2F8DDD9994A81@bnt-nav-akl-exh.navman.bnt.local>

Have been doing some googling myself..The Selenium tool looks good. It
appears to be a record-and-play extension to the firefox
browser...Anyone have any experience with the Selnium Remote Control?
I'm having difficulty installing it.
Cheers
Hans

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
Behalf Of Dustin J. Mitchell
Sent: Monday, 7 August 2006 11:45 a.m.
To: tutor at python.org
Subject: Re: [Tutor] Python for basic web-testing

Hans Dushanthakumar wrote:
> Hi,
>    How do I use python for basic web-tasks like inputting data or 
> clicking buttons on web-pages. For eg, how do I enter my username and 
> password and click on the "OK" button on the yahoo mail page?
> I had a look at the webbrowser module documentation 
> (http://www.python.org/doc/current/lib/module-webbrowser.html), but it

> doesnt seem to support clicking buttons or sending data.

All the stuff you need is right here:

http://wwwsearch.sourceforge.net/

Specifically, the clicking buttons part is in ClientForm.

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

From nephish at gmail.com  Mon Aug  7 06:21:59 2006
From: nephish at gmail.com (shawn bright)
Date: Sun, 6 Aug 2006 23:21:59 -0500
Subject: [Tutor] quick OO pointer
Message-ID: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com>

Hello there,

a while back i wrote a module called DbConnector.py that allowed me to run
different types of SQL queries. Cool enough.
i did it mostly to handle the open and close of a db connection so i
wouldn't have to worry about 'too many connection' errors.
it makes a connection, runs a query, then closes the connection.
The reason i write this, is that i know how the module works to make a
connection 'object'
now, i have a few functions in some scripts that i would like to reuse
across the board. But, they dont really fit the "object" thing, i dont
thing. Basically, i have a bunch of functions that do different things and i
would like one script to hold them all.
do i need to define a class for this, or can you import a function from
another script ?

like if i have

def write_something_to_log(logfile, something)
    f = open(logfile, 'a')
    f.write('%s\n' % something)
    f.close()
    return 'success'

and i wanted to use this same function in about four different scripts, do i
need a class ? Do i need to just create a script full of common functions
that i can access ? and if so, how ?
usually in the tutorials i read, they deal with OO and classes. Most
commonly a class called Person. Then person has different attributes. But
these functions are just bits of code that i want to reuse
what is the cleanest way to do something like this ?

thanks

sk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060806/74ccaee9/attachment.htm 

From jordangreenberg at gmail.com  Mon Aug  7 09:07:23 2006
From: jordangreenberg at gmail.com (Jordan Greenberg)
Date: Mon, 07 Aug 2006 03:07:23 -0400
Subject: [Tutor] quick OO pointer
In-Reply-To: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com>
References: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com>
Message-ID: <44D6E6AB.5010402@gmail.com>

shawn bright wrote:
> Hello there,
> 
> a while back i wrote a module called DbConnector.py that allowed me to run
> different types of SQL queries. Cool enough.
> i did it mostly to handle the open and close of a db connection so i
> wouldn't have to worry about 'too many connection' errors.
> it makes a connection, runs a query, then closes the connection.
> The reason i write this, is that i know how the module works to make a
> connection 'object'
> now, i have a few functions in some scripts that i would like to reuse
> across the board. But, they dont really fit the "object" thing, i dont
> thing. Basically, i have a bunch of functions that do different things
> and i
> would like one script to hold them all.
> do i need to define a class for this, or can you import a function from
> another script ?
> 
> like if i have
> 
> def write_something_to_log(logfile, something)
>    f = open(logfile, 'a')
>    f.write('%s\n' % something)
>    f.close()
>    return 'success'
> 
> and i wanted to use this same function in about four different scripts,
> do i
> need a class ? Do i need to just create a script full of common functions
> that i can access ? and if so, how ?
> usually in the tutorials i read, they deal with OO and classes. Most
> commonly a class called Person. Then person has different attributes. But
> these functions are just bits of code that i want to reuse
> what is the cleanest way to do something like this ?
> 
> thanks
> 
> sk

If your function write_something_to_log is in file myfunctions.py you
can just do:
from myfunctions import write_something_to_log

and then use write_something_to_log() just like it was defined in that file.

Example:
#file: test1.py
def spam():
	print "Spam, eggs, and toast"

#file: myscript.py
from test1 import spam
spam()
#prints "Spam, eggs, and toast"

Hope this helps!
-Jordan Greenberg


From janos.juhasz at VELUX.com  Mon Aug  7 10:11:06 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Mon, 7 Aug 2006 10:11:06 +0200
Subject: [Tutor] os.system() with NO_WAIT
In-Reply-To: <mailman.33421.1154909966.27774.tutor@python.org>
Message-ID: <OF2046A35A.AE298937-ONC12571C3.002C238D-C12571C3.002CF64C@velux.com>

Dear Guys,

I have a small script that is running on a terminal server's client 
session.

#######
import os
import time
import glob

def send():
    print 'I am checking %s' % time.ctime()
    if len(glob.glob(r'U:\ediout\DESADV\*.doc')) > 0:
        os.system('vedicom.exe')

if __name__ == '__main__':
    os.chdir(r'U:\vedicom\DESADV\\')
    while 1:
        send()
        time.sleep(30)
#######

As you can see, it is just start a windows program from a folder, when 
there are files in that folder.
My problem comes when the network connection is broken. In that case, this 
program wait a user interaction to push a button.
When the connection come back, it is just waiting to push the button and 
we are missing to send the EDI documents.

Have you got any idea how I can strart this windows GUI program with not 
waiting its return.




Yours sincerely, 
______________________________
J?nos Juh?sz 
VELUX Magyarorsz?g Fert?di ?p?t?komponens Kft. 
IT Department
Malom K?z 1, H-9431 Fert?d 
Telephone direct:      +36 99 537 939
Telephone office:      +36 99 537 920
Office fax:                +36 99 537 921
Telephone mobile:    +36 30 682 6331
@                             janos.juhasz at VELUX.com
www                        www.VELUX.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060807/530d068c/attachment.htm 

From reddazz at gmail.com  Mon Aug  7 13:14:43 2006
From: reddazz at gmail.com (William Mhlanga)
Date: Mon, 7 Aug 2006 12:14:43 +0100
Subject: [Tutor] Invoking bash from python
Message-ID: <f70bccff0608070414x7efd1bf0r97cf0421aa8bfd90@mail.gmail.com>

I'd like to write an app that helps a user install a program on Linux after
fetching it from a remote site. The program is packaged as a bin file and
when run from bash, the user has to agree to a licence agreement by entering
"y" or "n" and enter a path for installation. It seems like I need to find a
way for my program to invoke bash so that the user can enter the input
required. So far, I've figured out that I can use urllib to fetch the file
and the commands module to execute some system commands. Any ideas on how I
can envoke bash and pass on the users input to bash.

Thanks for your input.

Will
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060807/393cbd46/attachment.html 

From reddazz at gmail.com  Mon Aug  7 13:26:40 2006
From: reddazz at gmail.com (William Mhlanga)
Date: Mon, 7 Aug 2006 12:26:40 +0100
Subject: [Tutor] Invoking bash from python
In-Reply-To: <f70bccff0608070414x7efd1bf0r97cf0421aa8bfd90@mail.gmail.com>
References: <f70bccff0608070414x7efd1bf0r97cf0421aa8bfd90@mail.gmail.com>
Message-ID: <f70bccff0608070426h55ce98fcx7f4e162fe550d71d@mail.gmail.com>

I think I found a solution to my problem and thats to use the os module (
os.system function). I'm still open to any suggestions you may have.

--Will

On 8/7/06, William Mhlanga <reddazz at gmail.com> wrote:
>
> I'd like to write an app that helps a user install a program on Linux
> after fetching it from a remote site. The program is packaged as a bin file
> and when run from bash, the user has to agree to a licence agreement by
> entering "y" or "n" and enter a path for installation. It seems like I need
> to find a way for my program to invoke bash so that the user can enter the
> input required. So far, I've figured out that I can use urllib to fetch the
> file and the commands module to execute some system commands. Any ideas on
> how I can envoke bash and pass on the users input to bash.
>
> Thanks for your input.
>
> Will
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060807/92d3b69d/attachment.htm 

From alan.gauld at freenet.co.uk  Mon Aug  7 14:12:22 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 7 Aug 2006 13:12:22 +0100
Subject: [Tutor] quick OO pointer
References: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com>
Message-ID: <001201c6ba1a$bdc7ecf0$0201a8c0@XPpro>

> now, i have a few functions in some scripts that i would like to 
> reuse
> across the board. But, they dont really fit the "object" thing, i 
> dont
> thing. Basically, i have a bunch of functions that do different 
> things and i
> would like one script to hold them all.

You can put normal functions in a module and reuse them sure.
If they operate on the same kinds of data then a class would be
more appropriate but otherwise functions are fine.

Its probably good to try to group them into families if possible.
And you definitely want to use Functional Programming principles
to maximise reuse. By that I mean:
1) No use of global variables
2) Pass everything in by parameters
3) Use default values to minimise the number of values the user sets
4) pass multiple values back in tuples where appropriate
5) make sure that the same set of input values always
    returns the same value - no hidden state

Consider a number of smaller modules with related functionns too.
Its tempting to just create a module called mystuff or similar that
holds everything, but you then wind up with every project
depending on mystuiff and small changes affect lots of code.
Better to have small modules with only a few functions that can
be imported as needed. Grouping the functions around the kind
of data they manipulate is a good start - but that brings us back
to objects again :-)


> def write_something_to_log(logfile, something)
>    f = open(logfile, 'a')
>    f.write('%s\n' % something)
>    f.close()
>    return 'success'
>
> and i wanted to use this same function in about four different 
> scripts, do i
> need a class ? Do i need to just create a script full of common 
> functions
> that i can access ? and if so, how ?

##############
# file: mylogger.py
def write_something_to_log(logfile, something)
    f = open(logfile, 'a')
    f.write('%s\n' % something)
    f.close()
    return 'success'
######################

#############
# file myprog.py
import mylogger

mylogger.write_something('logfile.txt', 'hello world')
##############

As simple as that!
Just make sure the module file is where it can be found by import...

More on creating modules in my tutorial topic on "Functions & 
Modules".

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


From nephish at gmail.com  Mon Aug  7 14:45:39 2006
From: nephish at gmail.com (shawn bright)
Date: Mon, 7 Aug 2006 07:45:39 -0500
Subject: [Tutor] quick OO pointer
In-Reply-To: <001201c6ba1a$bdc7ecf0$0201a8c0@XPpro>
References: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com>
	<001201c6ba1a$bdc7ecf0$0201a8c0@XPpro>
Message-ID: <384c93600608070545i53c9cf28r8a0e405289fc06ac@mail.gmail.com>

Way cool, thanks a lot. I have one more small question.
If my script that needs to call a function from another module, and the
module itself both require, say, the string module.... do i need to import
it in both?
If i just import string on my original script, will the module know what to
do with it?
and if so, is that good practice ?

thanks again
shawn


On 8/7/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
> > now, i have a few functions in some scripts that i would like to
> > reuse
> > across the board. But, they dont really fit the "object" thing, i
> > dont
> > thing. Basically, i have a bunch of functions that do different
> > things and i
> > would like one script to hold them all.
>
> You can put normal functions in a module and reuse them sure.
> If they operate on the same kinds of data then a class would be
> more appropriate but otherwise functions are fine.
>
> Its probably good to try to group them into families if possible.
> And you definitely want to use Functional Programming principles
> to maximise reuse. By that I mean:
> 1) No use of global variables
> 2) Pass everything in by parameters
> 3) Use default values to minimise the number of values the user sets
> 4) pass multiple values back in tuples where appropriate
> 5) make sure that the same set of input values always
>     returns the same value - no hidden state
>
> Consider a number of smaller modules with related functionns too.
> Its tempting to just create a module called mystuff or similar that
> holds everything, but you then wind up with every project
> depending on mystuiff and small changes affect lots of code.
> Better to have small modules with only a few functions that can
> be imported as needed. Grouping the functions around the kind
> of data they manipulate is a good start - but that brings us back
> to objects again :-)
>
>
> > def write_something_to_log(logfile, something)
> >    f = open(logfile, 'a')
> >    f.write('%s\n' % something)
> >    f.close()
> >    return 'success'
> >
> > and i wanted to use this same function in about four different
> > scripts, do i
> > need a class ? Do i need to just create a script full of common
> > functions
> > that i can access ? and if so, how ?
>
> ##############
> # file: mylogger.py
> def write_something_to_log(logfile, something)
>     f = open(logfile, 'a')
>     f.write('%s\n' % something)
>     f.close()
>     return 'success'
> ######################
>
> #############
> # file myprog.py
> import mylogger
>
> mylogger.write_something('logfile.txt', 'hello world')
> ##############
>
> As simple as that!
> Just make sure the module file is where it can be found by import...
>
> More on creating modules in my tutorial topic on "Functions &
> Modules".
>
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060807/5e2d93cc/attachment.html 

From dyoo at hkn.eecs.berkeley.edu  Mon Aug  7 16:53:04 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 7 Aug 2006 07:53:04 -0700 (PDT)
Subject: [Tutor] help regarding forms... (fwd)
Message-ID: <Pine.LNX.4.64.0608070753020.17958@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Mon, 7 Aug 2006 00:28:50 -0700 (PDT)
From: anil maran <anilmrn at yahoo.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] help regarding forms...

dear danny yoo
thanks a lot for replying
can you explain post methods and actions
i wasnt able to find out how it works
thanks a lot
sincerely
anil

Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:

On Sat, 5 Aug 2006, anil maran wrote:

> http://localhost/newtodo?category=
>
> can one of you guys explain what this is

Hi Anil,

Are you taking some kind of internet web-development class?  You seem to
be asking a lot of web-development questions.  In the absence of context,
I'm not sure what to do other than to point you to the standard RFC on
Uniform Resource Locators:

      http://www.faqs.org/rfcs/rfc1738.html

and see if that addresses your question.


> class todo:
>       def GET
>
> and
> class newtodo:
>       def POST:


Have you looked at any Python CGI tutorials yet?

      http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/


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

From dyoo at hkn.eecs.berkeley.edu  Mon Aug  7 16:53:06 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 7 Aug 2006 07:53:06 -0700 (PDT)
Subject: [Tutor] can you explain string replacement syntax and comma
 separated statements (fwd)
Message-ID: <Pine.LNX.4.64.0608070753050.17958@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Mon, 7 Aug 2006 00:33:08 -0700 (PDT)
From: anil maran <anilmrn at yahoo.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] can you explain string replacement syntax and comma
     separated statements

Dear danny yoo
The help page doesnt take about multiline string replacement and this example doesnt work for me - it gives an error on text+ line
Please help me out
thanks a lot
Anil



olderror = web.internalerror
  def error():
      olderror()
      import sys, traceback
      tb = sys.exc_info()
      text = """From: the bugman <y... at example.com>
  To: the bugfixer <y... at example.com>
  Subject: bug: %s: %s (%s)
  Content-Type: multipart/mixed; boundary="----here----"

------here----
  Content-Type: text/plain
  Content-Disposition: inline

%s

%s

------here----
  Content-Type: text/html; name="bug.html"
  Content-Disposition: attachment; filename="bug.html"

""" % (tb[0], tb[1], web.ctx.path, web.ctx.method+' '+web.ctx.home+web.ctx.f
  ullpath,
       ''.join(traceback.format_exception(*tb)),
      text += str(web.djangoerror())
      utils.send('... at example.com', '... at example.com', text)

web.internalerror = error

Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:

On Sun, 6 Aug 2006, anil maran wrote:

>    text = """From: the bugman
> To: the bugfixer
> Subject: bug: %s: %s (%s)
> Content-Type: multipart/mixed; boundary="----here----"

[text example cut]

Hi Anil,

Anil, take a look at:

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

Does this address your question?


On a high-level view of your questions so far:  Are you running into
problems because you can't find the documentation?  Or is the issue that
the documentation is unclear?



---------------------------------
Do you Yahoo!?
  Next-gen email? Have it all with the  all-new Yahoo! Mail Beta.

From alan.gauld at freenet.co.uk  Mon Aug  7 19:22:51 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 7 Aug 2006 18:22:51 +0100
Subject: [Tutor] quick OO pointer
References: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com>
	<001201c6ba1a$bdc7ecf0$0201a8c0@XPpro>
	<384c93600608070545i53c9cf28r8a0e405289fc06ac@mail.gmail.com>
Message-ID: <000b01c6ba46$1cb37d80$0201a8c0@XPpro>

> If my script that needs to call a function from another module, and 
> the
> module itself both require, say, the string module.... do i need to 
> import
> it in both?

Yes, importing just makes the name visible in the module where it is 
imported.

So if you import your module the stuff that it imported is not 
visible.

But you really need to look at all the options around importing
because there are several options:

import mymodule
import mymodule as anothername
from my module import myfunc
from mymodule import *

The last technique is frowned upon except in special cases.
But you should really read about all the options to understand
exactly what each does for you.

> If i just import string on my original script, will the module
> know what to do with it?

Not sure what you mean. The module does nothing with it.
Its up to you to write code that uses it. It will be available
inside the module after the import and you can access its
functions in turn by prefixing them.

Think of it a bit like a bit containment graph where each
node in the graph can refer to any other node. Where you
get cycles then you can get problems so you should try to
avoid those situations.

HTH,

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


From pythontut at pusspaws.net  Mon Aug  7 20:10:27 2006
From: pythontut at pusspaws.net (dave s)
Date: Mon, 7 Aug 2006 18:10:27 +0000
Subject: [Tutor] creating a method name on the fly
Message-ID: <200608071810.28043.pythontut@pusspaws.net>

I need to scan a long list of QT tickboxes in a dialog. I need to execute 
pseudo code something like ...


		list = ['error_button',  'print_button' ... etc  ] 
		for key in list:
		 	button= list[key]
			print button, self.button.isChecked()


where self.button.isChecked() becomes self.error_button.isChecked() ... 
self.print_button.isChecked() ....  etc etc

Can anyone tell me how to do this ? I have looked at apply but with no luck

Thanks

Dave
	

From dyoo at hkn.eecs.berkeley.edu  Mon Aug  7 20:19:06 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 7 Aug 2006 11:19:06 -0700 (PDT)
Subject: [Tutor] help regarding forms... (fwd)
In-Reply-To: <Pine.LNX.4.64.0608070753020.17958@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0608070753020.17958@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.64.0608071110050.16142@hkn.eecs.berkeley.edu>

> can you explain post methods and actions i wasnt able to find out how it 
> works

Hi Anil,

Please do not email me directly.  I don't have much time these days to 
help on Tutor.  It is better to send replies back to the Tutor list, so 
that others there can continue helping you.  Also, apologies for my 
slightly curt tone; I'm getting much busier these days, and I simply don't 
have the time for in-depth replies.

Have you looked at:

     http://hoohoo.ncsa.uiuc.edu/cgi/forms.html

GET and POST are particular ways that web browsers send data to the web 
server.  They differ in the particulars in how they send that data, but 
conceptually, they do the same sort of thing in sending a "request" off to 
the server.

There is already a module in Python to handle some of the ugly details of 
the CGI protocol; from the point of the CGI program, you shouldn't have to 
worry about POST or GET unless you really want to be concerned about it. 
See the 'cgi' module for some details:

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

From dyoo at hkn.eecs.berkeley.edu  Mon Aug  7 20:23:51 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 7 Aug 2006 11:23:51 -0700 (PDT)
Subject: [Tutor] can you explain string replacement syntax and comma
 separated statements (fwd)
In-Reply-To: <Pine.LNX.4.64.0608070753050.17958@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0608070753050.17958@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.64.0608071119100.16142@hkn.eecs.berkeley.edu>



> The help page doesnt take about multiline string replacement and this 
> example doesnt work for me

Hi Anil,

Please be more specific and as informative as you can; we can't look over 
your shoulder, and the only information we see is what you send us.

When you say, "This example doesn't work for me; it gives an error", don't 
just tell us this, but show us what you have done. Show us what example 
you have typed in, and what the literal error message is.

From metaperl at gmail.com  Mon Aug  7 20:25:00 2006
From: metaperl at gmail.com (Terrence Brannon)
Date: Mon, 7 Aug 2006 14:25:00 -0400
Subject: [Tutor] help regarding forms... (fwd)
In-Reply-To: <Pine.LNX.4.64.0608071110050.16142@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0608070753020.17958@hkn.eecs.berkeley.edu>
	<Pine.LNX.4.64.0608071110050.16142@hkn.eecs.berkeley.edu>
Message-ID: <a8e52b650608071125p6ff15c96oc864572ba96c7747@mail.gmail.com>

On 8/7/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
> Hi Anil,
>
> Please do not email me directly.


this list is setup to send to the poster by default. I made the
mistake of doing such a thing earlier myself.
I know this is a huge item of contention, but do people favor having
the default be to send replies
to the list?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060807/e2c535cd/attachment.html 

From python at venix.com  Mon Aug  7 20:36:44 2006
From: python at venix.com (Python)
Date: Mon, 07 Aug 2006 14:36:44 -0400
Subject: [Tutor] creating a method name on the fly
In-Reply-To: <200608071810.28043.pythontut@pusspaws.net>
References: <200608071810.28043.pythontut@pusspaws.net>
Message-ID: <1154975804.28304.835.camel@www.venix.com>

On Mon, 2006-08-07 at 18:10 +0000, dave s wrote:
> I need to scan a long list of QT tickboxes in a dialog. I need to execute 
> pseudo code something like ...
> 
> 
> 		list = ['error_button',  'print_button' ... etc  ] 
> 		for key in list:
> 		 	button= list[key]
> 			print button, self.button.isChecked()
> 
> 
list = ['error_button',  'print_button' ... etc  ]
 	for key in list:
		 	button= getattr(self, key)
			print button, button.isChecked()

You can't use a string directly in an object reference, so self.key and
self.button will not work.  You want to use the value in the string to
look up an attribute.  The getattr function supports that ability.  (See
also setattr and hasattr).

key will be bound to each of the button attribute names in turn.  The
getattr call returns the button object.  NOTE: you no longer need to
specify self.  Then simply use the button object.

> 
> where self.button.isChecked() becomes self.error_button.isChecked() ... 
> self.print_button.isChecked() ....  etc etc
> 
> Can anyone tell me how to do this ? I have looked at apply but with no luck
> 
> Thanks
> 
> Dave
> 	
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp


From mahesh.akarapu at gmail.com  Mon Aug  7 20:41:11 2006
From: mahesh.akarapu at gmail.com (Mahesh)
Date: Tue, 8 Aug 2006 00:11:11 +0530
Subject: [Tutor] Beginner's question
Message-ID: <f1994e540608071141s413480a9k4ad91f298c217d89@mail.gmail.com>

Hi All,

To start with, please forgive me if this question is already answered.
I am totally new to Python. I heard about Python some 3 years back,
but did not give importance to it. I am hearing a lot about Python
again recently. I was wondering what Python is good for and how will
it help me, since I am already comfortable with C.

Could someone tell me how Python is useful and why is it a good
language to learn apart from C. Also please point me to a good
starting point for learning Python.

Thanks
Mahesh

From alan.gauld at freenet.co.uk  Mon Aug  7 20:50:24 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 7 Aug 2006 19:50:24 +0100
Subject: [Tutor] Invoking bash from python
References: <f70bccff0608070414x7efd1bf0r97cf0421aa8bfd90@mail.gmail.com>
Message-ID: <001e01c6ba52$581fc700$0201a8c0@XPpro>

> required. So far, I've figured out that I can use urllib to fetch 
> the file
> and the commands module to execute some system commands.
> Any ideas on how Ican envoke bash and pass on the users input to 
> bash.

Look at the Subprocess module and the Popen class.

Check the examples of how tyo simulate the now deprecated
popen functions. Basically they allow you to execute an external
program and control the stdin/stdout streams from your program.

You can also read some introductory stuff with examples on my
tutor site under the OS topic.

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


From alan.gauld at freenet.co.uk  Mon Aug  7 20:51:31 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 7 Aug 2006 19:51:31 +0100
Subject: [Tutor] Invoking bash from python
References: <f70bccff0608070414x7efd1bf0r97cf0421aa8bfd90@mail.gmail.com>
	<f70bccff0608070426h55ce98fcx7f4e162fe550d71d@mail.gmail.com>
Message-ID: <002a01c6ba52$7fb96960$0201a8c0@XPpro>

>I think I found a solution to my problem and thats to use the os 
>module (
> os.system function). I'm still open to any suggestions you may have.

os system() will just run the bash program. Not too much avanytage.
If you want to control the program from Python you need the popen
functions - or the new Subprocess module.

Alan G.

>
> --Will
>
> On 8/7/06, William Mhlanga <reddazz at gmail.com> wrote:
>>
>> I'd like to write an app that helps a user install a program on 
>> Linux
>> after fetching it from a remote site. The program is packaged as a 
>> bin file
>> and when run from bash, the user has to agree to a licence 
>> agreement by
>> entering "y" or "n" and enter a path for installation. It seems 
>> like I need
>> to find a way for my program to invoke bash so that the user can 
>> enter the
>> input required. So far, I've figured out that I can use urllib to 
>> fetch the
>> file and the commands module to execute some system commands. Any 
>> ideas on
>> how I can envoke bash and pass on the users input to bash.
>>
>> Thanks for your input.
>>
>> Will
>>
> 


From rabidpoobear at gmail.com  Mon Aug  7 20:53:26 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 07 Aug 2006 13:53:26 -0500
Subject: [Tutor] help regarding forms... (fwd)
In-Reply-To: <a8e52b650608071125p6ff15c96oc864572ba96c7747@mail.gmail.com>
References: <Pine.LNX.4.64.0608070753020.17958@hkn.eecs.berkeley.edu>	<Pine.LNX.4.64.0608071110050.16142@hkn.eecs.berkeley.edu>
	<a8e52b650608071125p6ff15c96oc864572ba96c7747@mail.gmail.com>
Message-ID: <44D78C26.3090409@gmail.com>

Terrence Brannon wrote:
>
>
> On 8/7/06, *Danny Yoo* <dyoo at hkn.eecs.berkeley.edu 
> <mailto:dyoo at hkn.eecs.berkeley.edu>> wrote:
>
>
>     Hi Anil,
>
>     Please do not email me directly.  
>
>
> this list is setup to send to the poster by default. I made the mistake of doing such a thing earlier myself. 
> I know this is a huge item of contention, but do people favor having the default be to send replies 
>
> to the list?
/vote default-reply-to-list

From metaperl at gmail.com  Mon Aug  7 21:02:45 2006
From: metaperl at gmail.com (Terrence Brannon)
Date: Mon, 7 Aug 2006 15:02:45 -0400
Subject: [Tutor] Beginner's question
In-Reply-To: <f1994e540608071141s413480a9k4ad91f298c217d89@mail.gmail.com>
References: <f1994e540608071141s413480a9k4ad91f298c217d89@mail.gmail.com>
Message-ID: <a8e52b650608071202x774a34abnb922918341b75f85@mail.gmail.com>

On 8/7/06, Mahesh <mahesh.akarapu at gmail.com> wrote:
>
> Hi All,


Hi Mahesh

To start with, please forgive me if this question is already answered.
> I am totally new to Python. I heard about Python some 3 years back,
> but did not give importance to it.


Similar to my story. I have been a 100% Perl professional for 6 years
and did not pay much attention to other
agile languages during that time.

I am hearing a lot about Python
> again recently.


Amen, me too! It all started when all the mailing lists starting preferring
mailman over majordomo... even Perl ones!

I was wondering what Python is good for and how will
> it help me, since I am already comfortable with C.


Well, I just got serious as a heart attack about Python because I really
needed to go beyond building websites page by page and nothing in Perl was
up to the task. So I started with Drupal and Joomla, both PHP products, but
really found Plone to be a more scaleable product and Python to be a more
sane language than PHP.

Could someone tell me how Python is useful and why is it a good
> language to learn apart from C.


Python is good for:
- clean code: just look at the syntactic requirements
- high quality flexible object oriented programming - I really like
the approach to controlling objects with things
like __init__ - and if you look at the plone videos, you see how
default public accessors can have policies added
to them by writing the accessor method. He also goes over why he opted
on a Python CMS over PHP
and even Ruby.
- Rapid web app development - Quixote, Django, Turbo Gears, CherryPy and
even Plone
- Content mgmt - Plone
- Large scale development - the import mechanism is very clean and concise
compared to Perl's ExtUtils::MakeMaker. The regularity of code is ensured
regardless of chosen editor.
- The C++ crowd loves to script their code with Python.
- google uses Python heavily
- TwistedMatrix is a powerful generic server appliance
- the community does not have nearly as much elitism as I found in the Perl
world.

The only difficult thing about Python is that the community discussions and
source repositories are highly, highly distributed. In Perl, you have CPAN
and Perlmonks.org and maybe a few mailing lists. It was very easy to keep on
top of all new Perl developments on a daily basis. With Python, people all
keep their source at their repo. Or you have to go through a lot of places
like Codezoo, Sourceforge, and others.

But Perl has basically run out of steam. Perl 5 was a great language for
mixing C and Shell concepts. But Perl has lost control of the webapp space,
and for object-oriented programming, the approach is far more manual,
especially in the area of creating getters and setters (the leading product
for this in Perl is Class::Accessor - just look at how difficult it is to
use). Perl 6 is a cryptic imitation of Python and Ruby that will not appeal
to Perl 5 fans or anyone seeking a simple easy to use language. And industry
will be squeamish over a completely new codebase and a language that looks
and has semantics quite different from Perl 5.

Also please point me to a good
> starting point for learning Python.


I started with "Think Like a Computer Scientist" but it has typos and
the author never got back to me when
I emailed him about them. I think in retrospect, just reading the
Tutorial and Library Reference at
python.org
is all you need. Then some articles like "Functional Programming in Python"
http://www.amk.ca/python/writing/functional
are good from there.

And be sure to read comp.lang.python every day - lots of good Q/A there. And
I though ASPN Python Cookbook was a good resource, but the programs are
quite buggy based on IRC #python discussions.


Thanks
> Mahesh
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060807/43907b27/attachment.htm 

From metaperl at gmail.com  Mon Aug  7 21:05:11 2006
From: metaperl at gmail.com (Terrence Brannon)
Date: Mon, 7 Aug 2006 15:05:11 -0400
Subject: [Tutor] Invoking bash from python
In-Reply-To: <002a01c6ba52$7fb96960$0201a8c0@XPpro>
References: <f70bccff0608070414x7efd1bf0r97cf0421aa8bfd90@mail.gmail.com>
	<f70bccff0608070426h55ce98fcx7f4e162fe550d71d@mail.gmail.com>
	<002a01c6ba52$7fb96960$0201a8c0@XPpro>
Message-ID: <a8e52b650608071205q3379fbb1m7893272a73a66195@mail.gmail.com>

I was thinking that Python would have an expect-like clone and they do:
http://pexpect.sourceforge.net/

Don't know how good it is though.

On 8/7/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
> >I think I found a solution to my problem and thats to use the os
> >module (
> > os.system function). I'm still open to any suggestions you may have.
>
> os system() will just run the bash program. Not too much avanytage.
> If you want to control the program from Python you need the popen
> functions - or the new Subprocess module.
>
> Alan G.
>
> >
> > --Will
> >
> > On 8/7/06, William Mhlanga <reddazz at gmail.com> wrote:
> >>
> >> I'd like to write an app that helps a user install a program on
> >> Linux
> >> after fetching it from a remote site. The program is packaged as a
> >> bin file
> >> and when run from bash, the user has to agree to a licence
> >> agreement by
> >> entering "y" or "n" and enter a path for installation. It seems
> >> like I need
> >> to find a way for my program to invoke bash so that the user can
> >> enter the
> >> input required. So far, I've figured out that I can use urllib to
> >> fetch the
> >> file and the commands module to execute some system commands. Any
> >> ideas on
> >> how I can envoke bash and pass on the users input to bash.
> >>
> >> Thanks for your input.
> >>
> >> Will
> >>
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060807/04a93119/attachment.html 

From metaperl at gmail.com  Mon Aug  7 21:18:21 2006
From: metaperl at gmail.com (Terrence Brannon)
Date: Mon, 7 Aug 2006 15:18:21 -0400
Subject: [Tutor] true and false
Message-ID: <a8e52b650608071218n23d676edu5f82b77dbf24a9a9@mail.gmail.com>

What values represent true in Python?


>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060807/df650b24/attachment.htm 

From wescpy at gmail.com  Mon Aug  7 21:48:12 2006
From: wescpy at gmail.com (wesley chun)
Date: Mon, 7 Aug 2006 12:48:12 -0700
Subject: [Tutor] true and false
In-Reply-To: <a8e52b650608071218n23d676edu5f82b77dbf24a9a9@mail.gmail.com>
References: <a8e52b650608071218n23d676edu5f82b77dbf24a9a9@mail.gmail.com>
Message-ID: <78b3a9580608071248s5ce4b6abgd86974d6d1b1ecf@mail.gmail.com>

> What values represent true in Python?

good question.  let's look at it from the other way as it's easier:

a Boolean False value is any zero or empty container while True is
anything *other* than those values.  at the risk of plagarizing
myself, here is a clip from chapter 4 of "Core Python:"

CORE NOTE: Boolean values

All standard type objects can be tested for truth value and compared
to objects of the same type. Objects have inherent True or False
values. Objects take a False
value when they are empty, any numeric representation of zero, or the
Null object,
None. The following are defined as having false values in Python:

? None
? False (Boolean)
? 0 (integer)
? 0.0 (float)
? 0L (long integer)
? 0.0+0.0j (complex)
? "" (empty string)
? [] (empty list)
? () (empty tuple)
? {} (empty dictionary)
(? other empty objects)

Any value for an object other than the those above is considered to
have a true value, i.e., non-empty, non-zero, etc. User-created class
instances have a false value when their nonzero (__nonzero__()) or
length (__len__()) special methods, if defined, return a zero value.

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

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

From wescpy at gmail.com  Mon Aug  7 22:08:59 2006
From: wescpy at gmail.com (wesley chun)
Date: Mon, 7 Aug 2006 13:08:59 -0700
Subject: [Tutor] Beginner's question
In-Reply-To: <f1994e540608071141s413480a9k4ad91f298c217d89@mail.gmail.com>
References: <f1994e540608071141s413480a9k4ad91f298c217d89@mail.gmail.com>
Message-ID: <78b3a9580608071308j5d83caccgf8bdff621f35402f@mail.gmail.com>

hi mahesh,

welcome to python... once you're here, there is no turning back.  :-)

> I am hearing a lot about Python
> again recently.

please tell us how and where you are hearing about Python now... the
community is always interested in hearing interesting stories, such as
Terrence's.

> I was wondering what Python is good for and how will
> it help me, since I am already comfortable with C.
>
> Could someone tell me how Python is useful and why is it a good
> language to learn apart from C. Also please point me to a good
> starting point for learning Python.

i was a C programmer myself... had over 8 years of experience, then
began experimenting with C++, Java, Perl, Tcl, etc.  the one draw to
moving to any language that is more "scriptive" in nature, whether it
be Perl, Python or Ruby is that for a slight performance hit (nothing
in life is free), you are gaining much more in terms of productivity.
you are coding and solving problems at a much more rapid rate than in
standard compiled languages like C, C++, and Java. i finally found
Python 10 years ago, and have tried to avoid programming in anything
else since.  :D

you are not wasting any (or much) time with boilerplate code, memory
management, construction and destruction of primitive and/or
heterogeneous data structures, etc.  these things are already there
for you, so the only things you need to worry about are solving your
problems and which algorithms to use.  then you can think about all
the extra days of vacation you can take because you are not sitting in
front of a computer and debugging.

another feature of Python is its clean and simple but robust syntax.
yes it can do everything that all those other languages can do, but
with a syntax as simple as VB or JavaScript? makes others' code easier
to read, including your own!  you don't have to pull reference books
off your shelf to figure out a piece of code you did several months
ago.

there are many places to start learning Python.  since you are already
a programmer, you can jump into various online tutorials, such as dive
into python ( http://diveintopython.org ), alan gauld's (
http://www.freenetpages.co.uk/hp/alan.gauld/ ), as well as the
tutorial in the official docs.

if you want to read a book, check out pilgrim's dive into python (same
as tutorial above), hetland's beginning python, wrox's (norton et
al.), ascher's/lutz's learning python.  all are good as python intros
for experienced programmers.  if you want to dig deeper and not only
learn Python, but gain an insight on how things work under the covers,
you can also try out my book, core python. it's pretty comprehensive
but i try to expose you to enough of how the interpreter works with a
goal of making you as *effective* of a Python developer as possible,
even as a beginner.

as far as Terrence's comment about where things are, in addition to
the resources he mentioned, there are two main places to check for
existing code: the vaults of parnassus, and PyPI (Python Package
Index) aka the Cheeseshop. the latter is the closest thing we have to
a "CPAN" at this time.

again, welcome to python... we hope you're here to stay.  :-)
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

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

From wescpy at gmail.com  Mon Aug  7 22:17:15 2006
From: wescpy at gmail.com (wesley chun)
Date: Mon, 7 Aug 2006 13:17:15 -0700
Subject: [Tutor] creating a method name on the fly
In-Reply-To: <1154975804.28304.835.camel@www.venix.com>
References: <200608071810.28043.pythontut@pusspaws.net>
	<1154975804.28304.835.camel@www.venix.com>
Message-ID: <78b3a9580608071317n3034b84tef06a95a8ebece9d@mail.gmail.com>

> >               list = ['error_button',  'print_button' ... etc  ]
> >               for key in list:
> >                       button= list[key]
> >                       print button, self.button.isChecked()
> >
> list = ['error_button',  'print_button' ... etc  ]
>         for key in list:
>                         button= getattr(self, key)
>                         print button, button.isChecked()
>
> You can't use a string directly in an object reference, so self.key and
> self.button will not work.  You want to use the value in the string to
> look up an attribute.  The getattr function supports that ability.  (See
> also setattr and hasattr).

dave,

lloyd's suggestion is the way one "turns a string into an object," by
using getattr(). you are basically saying, i want to look up the
"printButton" attribute of self, and if it exists, give that object
back to me (as 'button').  then when you access button, you are really
manipulating self.printButton directly.

also, calling "print button" is only going to give you either the
object reference, i.e., "<object ... at ...>," not extremely useful
unless you've defined your __str__ special method.

the only other suggestion i'd give here is to not use "list" as a
variable name. that is the name of a Python data type and its
corresponding factory function, and by overriding it, you're
effectively "shadowing" it, so you can't use "list()" to make a list
anymore, and it also breaks typechecking with isintance().

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

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

From pythontut at pusspaws.net  Mon Aug  7 22:22:34 2006
From: pythontut at pusspaws.net (dave s)
Date: Mon, 7 Aug 2006 20:22:34 +0000
Subject: [Tutor] creating a method name on the fly
In-Reply-To: <200608071810.28043.pythontut@pusspaws.net>
References: <200608071810.28043.pythontut@pusspaws.net>
Message-ID: <200608072022.34946.pythontut@pusspaws.net>

Thanks for all your input - the discussion wandered off list a bit !

This solution works a treat ...

button= getattr(self, 'error_button')
print button, button.isChecked()

Cheers

Dave

From wescpy at gmail.com  Mon Aug  7 22:28:11 2006
From: wescpy at gmail.com (wesley chun)
Date: Mon, 7 Aug 2006 13:28:11 -0700
Subject: [Tutor] os.system() with NO_WAIT
In-Reply-To: <OF2046A35A.AE298937-ONC12571C3.002C238D-C12571C3.002CF64C@velux.com>
References: <mailman.33421.1154909966.27774.tutor@python.org>
	<OF2046A35A.AE298937-ONC12571C3.002C238D-C12571C3.002CF64C@velux.com>
Message-ID: <78b3a9580608071328q42b3d4ecif5ea45bd96f37a0@mail.gmail.com>

>         os.system('vedicom.exe')
>
> Have you got any idea how I can strart this windows GUI program with not
> waiting its return.

instead of os.system(), you want to use the subprocess module if you
are using Python 2.4+:
http://docs.python.org/lib/module-subprocess.html

calling subprocess.Popen(["/bin/mycmd", "myarg"]) is "no wait."

to save the PID:

pid = subprocess.Popen(["/bin/mycmd", "myarg"]).pid

if you are using Python 2.3.x and older, you have to use spawn*():

pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")

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

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

From alan.gauld at freenet.co.uk  Mon Aug  7 22:29:15 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 7 Aug 2006 21:29:15 +0100
Subject: [Tutor] creating a method name on the fly
References: <200608071810.28043.pythontut@pusspaws.net>
Message-ID: <003901c6ba60$26fefe30$0201a8c0@XPpro>


>I need to scan a long list of QT tickboxes in a dialog. I need to 
>execute
> pseudo code something like ...
>
> list = ['error_button',  'print_button' ... etc  ]
> for key in list:
> button= list[key]
> print button, self.button.isChecked()
>
>
> where self.button.isChecked() becomes self.error_button.isChecked() 
> ...
> self.print_button.isChecked() ....  etc etc
>
> Can anyone tell me how to do this ? I have looked at apply but with 
> no luck

Why not just add the buttons to a list as you create them then
iterate over the list? Or better still use a dictionary with the name
as key.

buttons['error'] = Button(.....)
buttons['print'] = Button(.....)

then

for name in buttons:
     print name, "button is",
if buttons[name].isChecked(): print "checked"
else: print "unchecked"

No need to mess around trying to dynamically construct buton names 
etc.

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


From alan.gauld at freenet.co.uk  Mon Aug  7 22:43:45 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 7 Aug 2006 21:43:45 +0100
Subject: [Tutor] help regarding forms... (fwd)
References: <Pine.LNX.4.64.0608070753020.17958@hkn.eecs.berkeley.edu><Pine.LNX.4.64.0608071110050.16142@hkn.eecs.berkeley.edu>
	<a8e52b650608071125p6ff15c96oc864572ba96c7747@mail.gmail.com>
Message-ID: <004901c6ba62$2dca1ea0$0201a8c0@XPpro>

> this list is setup to send to the poster by default. I made the
> mistake of doing such a thing earlier myself.
> I know this is a huge item of contention, but do people favor having
> the default be to send replies to the list?

OK, I've got to ask. This comes up every so often and I really
don't understand it.

I've been on the internet for over 20 years now and every mail
tool/newreader I've ever used has (at least) two reply options:
1) Reply = reply to the original sender
2) Reply All = reply to everyone

The same principle has always worked for all of the mailing lists
I've ever been on.

So why do people seem to expect some other kind of response?
Are there mail clients out there that don't offer a Reply All option?
Why would anyone want a mailing list that didn't offer two options,
one for private reply and the other to include everyone?

I don't understand why this seems to come as a surprise?
What am I missing?

Alan G.



From alan.gauld at freenet.co.uk  Mon Aug  7 22:50:54 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 7 Aug 2006 21:50:54 +0100
Subject: [Tutor] Beginner's question
References: <f1994e540608071141s413480a9k4ad91f298c217d89@mail.gmail.com>
Message-ID: <004f01c6ba63$2d726c40$0201a8c0@XPpro>

> but did not give importance to it. I am hearing a lot about Python
> again recently. I was wondering what Python is good for and how will
> it help me, since I am already comfortable with C.

One line of Python ~= 10 lines of C
So in terms of delivering results quickly Python is much faster than 
C.
Python is also much more reliable than C since there is almost no
memory management so you don't get NULL pointers, buffer
overruns etc.

But, Python is about 5-10 times slower than C and doesn't play well
with direct memory access or hardware access, so if you need that
stick with C. Or at least write those functions in C and access them
from Python...

> Could someone tell me how Python is useful and why is it a good
> language to learn apart from C.

There is an promotional section on the python web site giving the plus 
points.
They are mostly the same plus points you find for any scripting 
language
but python adds readability, modularity and a good OOP model - 
certainly
better than C++ and java etc.

> Also please point me to a good starting point for learning Python.

If you know C just start with the official tutorial at

www.python.org

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


From alan.gauld at freenet.co.uk  Mon Aug  7 22:58:15 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 7 Aug 2006 21:58:15 +0100
Subject: [Tutor] Invoking bash from python
References: <f70bccff0608070414x7efd1bf0r97cf0421aa8bfd90@mail.gmail.com>
	<f70bccff0608070426h55ce98fcx7f4e162fe550d71d@mail.gmail.com>
	<002a01c6ba52$7fb96960$0201a8c0@XPpro>
	<a8e52b650608071205q3379fbb1m7893272a73a66195@mail.gmail.com>
Message-ID: <006901c6ba64$34251820$0201a8c0@XPpro>

>I was thinking that Python would have an expect-like clone and they 
>do:
> http://pexpect.sourceforge.net/
>
> Don't know how good it is though.

Pretty reasonable, its been around for a while.

But if you know the order of requests expect is overkill. Expect is
really for those situations where you have a dialog with the app
and don't know which of many possible prompts you will get back.
Its a bit like awk for streams

but if you know exactly what you will be asked for and when
then simple popen functionality is perfectly adequate and
much simpler to code.

PS.
As an intermediate you can use the telnet module which
allow simple checks for prompts ala expect but doesn't
have all the timer/timeout richness of expect.

Alan G.

>
> On 8/7/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>>
>> >I think I found a solution to my problem and thats to use the os
>> >module (
>> > os.system function). I'm still open to any suggestions you may 
>> > have.
>>
>> os system() will just run the bash program. Not too much avanytage.
>> If you want to control the program from Python you need the popen
>> functions - or the new Subprocess module.
>>
>> Alan G.
>>
>> >
>> > --Will
>> >
>> > On 8/7/06, William Mhlanga <reddazz at gmail.com> wrote:
>> >>
>> >> I'd like to write an app that helps a user install a program on
>> >> Linux
>> >> after fetching it from a remote site. The program is packaged as 
>> >> a
>> >> bin file
>> >> and when run from bash, the user has to agree to a licence
>> >> agreement by
>> >> entering "y" or "n" and enter a path for installation. It seems
>> >> like I need
>> >> to find a way for my program to invoke bash so that the user can
>> >> enter the
>> >> input required. So far, I've figured out that I can use urllib 
>> >> to
>> >> fetch the
>> >> file and the commands module to execute some system commands. 
>> >> Any
>> >> ideas on
>> >> how I can envoke bash and pass on the users input to bash.
>> >>
>> >> Thanks for your input.
>> >>
>> >> Will
>> >>
>> >
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> 


From alan.gauld at freenet.co.uk  Mon Aug  7 23:07:20 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 7 Aug 2006 22:07:20 +0100
Subject: [Tutor] true and false
References: <a8e52b650608071218n23d676edu5f82b77dbf24a9a9@mail.gmail.com>
Message-ID: <009601c6ba65$791c7850$0201a8c0@XPpro>


> What values represent true in Python?

True

Its a built-in boolean type value.

But empty strings, lists, tuples etc are considered False
Similarly zero and None are considered False

The library reference has a full list somewhere, but it's pretty 
much what intuition would tell you. "Empty" things are false 
anything else is true.

Alan G.

From john at fouhy.net  Mon Aug  7 23:50:14 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 8 Aug 2006 09:50:14 +1200
Subject: [Tutor] creating a method name on the fly
In-Reply-To: <003901c6ba60$26fefe30$0201a8c0@XPpro>
References: <200608071810.28043.pythontut@pusspaws.net>
	<003901c6ba60$26fefe30$0201a8c0@XPpro>
Message-ID: <5e58f2e40608071450m6d6df37ci66dab043336a2cf8@mail.gmail.com>

On 08/08/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> Why not just add the buttons to a list as you create them then
> iterate over the list? Or better still use a dictionary with the name
> as key.

You can do nice things with tuples.

A simple example would be:

# (label, callback)
buttons = [('OK', self.OnOk), ('Cancel', self.OnCancel)]

for label, callback in buttons:
    b = Button(self, label=label, ...)
    # place b in your GUI
    b.Bind(..., self.OnCancel)

Obviously, the exact syntax and stuffw ill depend on the GUI toolkit
you are using.

Also you can put more information in your data structure if you want
(eg, information on placing the button, styles for the button, etc).
And, if you need to save the Button objects themselves, you could add
them to a dict in the body of the loop:

self.buttons = {}
for label, callback in buttons:
    # ...
    self.buttons[label] = b

It means that all the information about your GUI is brought together
in one place where it's easy to see, and all the mechanical work is
pushed off to one side :-)

-- 
John.

From wescpy at gmail.com  Tue Aug  8 00:28:44 2006
From: wescpy at gmail.com (wesley chun)
Date: Mon, 7 Aug 2006 15:28:44 -0700
Subject: [Tutor] creating a method name on the fly
In-Reply-To: <5e58f2e40608071450m6d6df37ci66dab043336a2cf8@mail.gmail.com>
References: <200608071810.28043.pythontut@pusspaws.net>
	<003901c6ba60$26fefe30$0201a8c0@XPpro>
	<5e58f2e40608071450m6d6df37ci66dab043336a2cf8@mail.gmail.com>
Message-ID: <78b3a9580608071528y1b913a5dk978bab08afa7ee38@mail.gmail.com>

> Also you can put more information in your data structure if you want
> (eg, information on placing the button, styles for the button, etc).
> And, if you need to save the Button objects themselves, you could add
> them to a dict in the body of the loop:
>
> self.buttons = {}
> for label, callback in buttons:
>     # ...
>     self.buttons[label] = b
>
> It means that all the information about your GUI is brought together
> in one place where it's easy to see, and all the mechanical work is
> pushed off to one side :-)


on a separate but related tangent, wait till y'all see PFA (partial
function application) coming up in 2.5.  you can use PFAs to
"templatize" GUI development.  for example, if you want all the
buttons to have the similar look-n-feel except for perhaps the text,
you can do something like (here's another clip from Core Python,
Example 11.6, pfaGUI.py):

#!/usr/bin/env python

from functools import partial
import Tkinter

root = Tkinter.Tk()
MyButton = partial(Tkinter.Button, root, fg='white', bg='blue')
b1 = MyButton(text='Button 1')
b2 = MyButton(text='Button 2')
qb = MyButton(text='QUIT', bg='red', command=root.quit)
b1.pack()
b2.pack()
qb.pack(fill=Tkinter.X, expand=True)
root.title('PFAs!')
root.mainloop()

"MyButton" contains all the common stuff for all buttons while the
others can take the defaults or override them! it sure looks cleaner
than having lots of duplicated code:

b1 = Tkinter.Button(root, fg='white', bg='blue', text='Button 1')
b2 = Tkinter.Button(root, fg='white', bg='blue', text='Button 2')
qb = Tkinter.Button(root, fg='white', text='QUIT', bg='red', command=root.quit)

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

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

From h.finucane at gmail.com  Tue Aug  8 00:41:48 2006
From: h.finucane at gmail.com (Henry Finucane)
Date: Mon, 7 Aug 2006 15:41:48 -0700
Subject: [Tutor] Community documentation framework?
In-Reply-To: <45109da50608061456v67580f30oc42d1d18453f1226@mail.gmail.com>
References: <45109da50608061456v67580f30oc42d1d18453f1226@mail.gmail.com>
Message-ID: <f24e65d60608071541q79257b92ycd8638b446a079e1@mail.gmail.com>

On 8/6/06, Bob Nienhuis <bob.nienhuis at gmail.com> wrote:
>
>  Have you had the experience of finding a nifty bit of code on the
>  web, trying it out, and then discovering that technique
>  only worked in version X.YY, or requires module Z that
>  is no longer available?
>
>  Well perhaps we can address this situation.
>
>  I would like to see an online system that facilitates
>  the collaborative production, cataloging and updating of
>  community documentation. See an article, "Rethinking Community
>  Documentation" by Andy Oram
> <http://www.onlamp.com/pub/a/onlamp/2006/07/06/rethinking-community-documentation.html>.
>
>  Features I would like to see:
>      A Wikipedia-like capacity for community update-ability/modifiability
>      of documentation submissions.
>
>      Database for cataloging available packages, modules, FAQs, How-Tos
>      tutorials, cookbook code fragments etc. Should have capacity for
>      developers to add and others to add to their contributions.
>
>      Oram suggests a rating system for submissions so users can assess
>      the quality of submissions, and point to parts that need modification
>      or clarification..
>
>      Might use TurboGears, Django AJAX or other web framework?
>
>  I think main Python documentation is great, but there is a lot
>  of stuff out there that isn't documented so well, or needs
>  updating. This project is intended to adress that need.
>
>  What would you like to see?

Sounds neat. Personally, I would like to see a bit of consolidation in
ways you can look for help. There are oodles of web forums, the Tutor
mailing list, the comp.lang.python mailing list, tutorials scattered
all about the web, etc. Something like this could either prompt
consolidation (good), or simply create more fragmentation (not so
great, but acceptable).

It all depends on how it gets advertised.


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


-- 
--H.F.
My penguin is bigger than yours, mister...

From john at fouhy.net  Tue Aug  8 00:44:58 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 8 Aug 2006 10:44:58 +1200
Subject: [Tutor] creating a method name on the fly
In-Reply-To: <78b3a9580608071528y1b913a5dk978bab08afa7ee38@mail.gmail.com>
References: <200608071810.28043.pythontut@pusspaws.net>
	<003901c6ba60$26fefe30$0201a8c0@XPpro>
	<5e58f2e40608071450m6d6df37ci66dab043336a2cf8@mail.gmail.com>
	<78b3a9580608071528y1b913a5dk978bab08afa7ee38@mail.gmail.com>
Message-ID: <5e58f2e40608071544n2c4121bdt267fee553a9e8d31@mail.gmail.com>

On 08/08/06, wesley chun <wescpy at gmail.com> wrote:
> import Tkinter
>
> root = Tkinter.Tk()
> MyButton = partial(Tkinter.Button, root, fg='white', bg='blue')
> b1 = MyButton(text='Button 1')
> b2 = MyButton(text='Button 2')
> qb = MyButton(text='QUIT', bg='red', command=root.quit)
>
> "MyButton" contains all the common stuff for all buttons while the
> others can take the defaults or override them! it sure looks cleaner
> than having lots of duplicated code:
>
> b1 = Tkinter.Button(root, fg='white', bg='blue', text='Button 1')
> b2 = Tkinter.Button(root, fg='white', bg='blue', text='Button 2')
> qb = Tkinter.Button(root, fg='white', text='QUIT', bg='red', command=root.quit)

I sometimes do this:

buttonOpts = { 'fg':'white', 'bg':'blue' }
packOpts = { I forget :-) }
buttons = [('Button 1', None), ('Button 2', None), ('Button 3', root.quit)]

for label, callback in buttons:
    b = Tkinter.Button(label, command=callback, **buttonOpts)
    b.pack(**packOpts)

But, yeah, partial application will be cool :-)

-- 
John.

From dyoo at hkn.eecs.berkeley.edu  Tue Aug  8 00:48:30 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 7 Aug 2006 15:48:30 -0700 (PDT)
Subject: [Tutor] help regarding forms... (fwd)
In-Reply-To: <a8e52b650608071125p6ff15c96oc864572ba96c7747@mail.gmail.com>
References: <Pine.LNX.4.64.0608070753020.17958@hkn.eecs.berkeley.edu>
	<Pine.LNX.4.64.0608071110050.16142@hkn.eecs.berkeley.edu>
	<a8e52b650608071125p6ff15c96oc864572ba96c7747@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0608071540420.18174@hkn.eecs.berkeley.edu>

> this list is setup to send to the poster by default. I made the
> mistake of doing such a thing earlier myself.

Hi Terrence,

Most email clients have a separate "Reply to All" or "Reply to group" 
command that's suitable for mailing lists.  Check to see if your mail 
client has this feature.


> I know this is a huge item of contention, but do people favor having the 
> default be to send replies to the list?

There are good reasons for keeping the status quo:

     http://www.unicom.com/pw/reply-to-harmful.html

There's no technical reason why we couldn't switch to reply-to munging --- 
Mailman supports it --- but I haven't heard anything compelling enough 
that addresses the issues raised by that article above.


Best of wishes!

From bgailer at alum.rpi.edu  Tue Aug  8 01:03:05 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 07 Aug 2006 16:03:05 -0700
Subject: [Tutor] true and false
In-Reply-To: <009601c6ba65$791c7850$0201a8c0@XPpro>
References: <a8e52b650608071218n23d676edu5f82b77dbf24a9a9@mail.gmail.com>
	<009601c6ba65$791c7850$0201a8c0@XPpro>
Message-ID: <44D7C6A9.2040503@alum.rpi.edu>

Alan Gauld wrote:
>> What values represent true in Python?
>>     
>
> True
>
> Its a built-in boolean type value.
>
> But empty strings, lists, tuples etc are considered False
> Similarly zero and None are considered False
>   
Let us be precise here. Empty things are considered False when used 
where a boolean value is expected.
In the language reference, under the if statement I quote:"It selects 
exactly one of the suites by evaluating the expressions one by one until 
one is found to be true (see section 5.10 <Booleans.html#Booleans> for 
the definition of true and false)"

5:10: "In the context of Boolean operations, and also when expressions 
are used by control flow statements, the following values are 
interpreted as false: |False|, |None|, numeric zero of all types, and 
empty strings and containers (including strings, tuples, lists, 
dictionaries, sets and frozensets). All other values are interpreted as 
true."

The 2 flow control statements that use expressions in this way are if 
and while. Boolean operations are or, and, not.

So in "if [1]: print 1" [1] will be interpreted as True. However in  
"[1]  == True" it will NOT be interpreted as True.

-- 
Bob Gailer
510-978-4454


From anilmrn at yahoo.com  Tue Aug  8 01:51:22 2006
From: anilmrn at yahoo.com (anil maran)
Date: Mon, 7 Aug 2006 16:51:22 -0700 (PDT)
Subject: [Tutor] sending emails with html attachment
In-Reply-To: <Pine.LNX.4.64.0608071119100.16142@hkn.eecs.berkeley.edu>
Message-ID: <20060807235122.71529.qmail@web55904.mail.re3.yahoo.com>

hi guys
What is the best way to construct an email in python and also attach a html file

the file is not on disk, but should be dynamically constructed in the python script

thanks a lot

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

From broek at cc.umanitoba.ca  Tue Aug  8 04:11:52 2006
From: broek at cc.umanitoba.ca (Brian van den Broek)
Date: Mon, 07 Aug 2006 22:11:52 -0400
Subject: [Tutor] help regarding forms... (fwd)
In-Reply-To: <004901c6ba62$2dca1ea0$0201a8c0@XPpro>
References: <Pine.LNX.4.64.0608070753020.17958@hkn.eecs.berkeley.edu><Pine.LNX.4.64.0608071110050.16142@hkn.eecs.berkeley.edu>	<a8e52b650608071125p6ff15c96oc864572ba96c7747@mail.gmail.com>
	<004901c6ba62$2dca1ea0$0201a8c0@XPpro>
Message-ID: <44D7F2E8.8020305@cc.umanitoba.ca>

Alan Gauld said unto the world upon 07/08/06 04:43 PM:
>> this list is setup to send to the poster by default. I made the
>> mistake of doing such a thing earlier myself.
>> I know this is a huge item of contention, but do people favor having
>> the default be to send replies to the list?
> 
> OK, I've got to ask. This comes up every so often and I really
> don't understand it.
> 
> I've been on the internet for over 20 years now and every mail
> tool/newreader I've ever used has (at least) two reply options:
> 1) Reply = reply to the original sender
> 2) Reply All = reply to everyone
> 
> The same principle has always worked for all of the mailing lists
> I've ever been on.
> 
> So why do people seem to expect some other kind of response?
> Are there mail clients out there that don't offer a Reply All option?
> Why would anyone want a mailing list that didn't offer two options,
> one for private reply and the other to include everyone?
> 
> I don't understand why this seems to come as a surprise?
> What am I missing?


Hi all,

Alan, I think you are judging based on technical lists, no? In my 
experience, the further from computing-technical the domain of a 
mailing list, the more likely it is to be set up with a munged `reply 
to' header.

It could be worse; there is a photography list I've been occasionally 
on for a decade or so where the list-denizens are steadfast in their 
reply to list preference and have to cope with 2-3 ``How do I 
subscribers?'' emails a week. (This despite instructions being 
provided in the footer of each and every message posted on the list.)

Best,

Brian vdB


From cspears2002 at yahoo.com  Tue Aug  8 07:42:46 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Mon, 7 Aug 2006 22:42:46 -0700 (PDT)
Subject: [Tutor] Rock, Paper, Scissors
Message-ID: <20060808054246.54903.qmail@web51606.mail.yahoo.com>

I have been looking for a new project to tackle when I
came across this link:
http://www.ibiblio.org/obp/pyBiblio/practice/wilson/rockpaperscissors.php.

Here is some sample output that was provided at the
webpage:

Welcome to Rock, Paper, Scissors!

How many points are required for a win? 3

Choose (R)ock, (P)aper, or (S)cissors? r
Human: rock    Computer: paper        Computer wins!

Score: Human 0   Computer 1
Choose (R)ock, (P)aper, or (S)cissors? r

Human: rock    Computer: scissors     Human wins!

Score: Human 1   Computer 1
Choose (R)ock, (P)aper, or (S)cissors? p

Human: paper   Computer: paper        A draw

Score: Human 1   Computer 1
Choose (R)ock, (P)aper, or (S)cissors? s

Human: scissors  Computer: paper      Human wins!

Score: Human 2   Computer 1
Choose (R)ock, (P)aper, or (S)cissors? r

Human: rock      Computer: scissors   Human wins!

Final Score: Human 3   Computer 1

This looks like a fun project to work on.  From
reading the description, I feel this would be pretty
straight forward game to program.  However, I have no
idea how the computer would decide if it wanted a
rock, paper, or a pair of scissors.  Any hints?

From john at fouhy.net  Tue Aug  8 07:54:36 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 8 Aug 2006 17:54:36 +1200
Subject: [Tutor] Rock, Paper, Scissors
In-Reply-To: <20060808054246.54903.qmail@web51606.mail.yahoo.com>
References: <20060808054246.54903.qmail@web51606.mail.yahoo.com>
Message-ID: <5e58f2e40608072254q6044e5f9yb8ffcceb176a5e5d@mail.gmail.com>

On 08/08/06, Christopher Spears <cspears2002 at yahoo.com> wrote:
> This looks like a fun project to work on.  From
> reading the description, I feel this would be pretty
> straight forward game to program.  However, I have no
> idea how the computer would decide if it wanted a
> rock, paper, or a pair of scissors.  Any hints?

Well, the easiest way to do it would be to make it random --- have a
look at the random module in the standard library.

For example, random.randrange(3) will give you a random integer in [0,
1, 2], which you could map to rock/paper/scissors.

[the random module also has a function randint, which is similar to
randrange.  I prefer randrange, because the arguments match the
arguments to range(), whereas randint is a bit different]

Or random.choice(['rock', 'paper', 'scissors']) will give you a string.

Of course, if you want to be more clever, I understand that RSP
programs that always pick what the human picked in the previous round
tend to do better than random (unless the human notices, at which
point they start doing very badly :-) ).

-- 
John.

From jordangreenberg at gmail.com  Tue Aug  8 08:00:37 2006
From: jordangreenberg at gmail.com (Jordan Greenberg)
Date: Tue, 08 Aug 2006 02:00:37 -0400
Subject: [Tutor] Rock, Paper, Scissors
In-Reply-To: <20060808054246.54903.qmail@web51606.mail.yahoo.com>
References: <20060808054246.54903.qmail@web51606.mail.yahoo.com>
Message-ID: <44D82885.1080904@gmail.com>

Christopher Spears wrote:
<SNIP>
> This looks like a fun project to work on.  From
> reading the description, I feel this would be pretty
> straight forward game to program.  However, I have no
> idea how the computer would decide if it wanted a
> rock, paper, or a pair of scissors.  Any hints?


Since theres no real strategy to rock paper scissors, just generate a
random number from 0-2 like this:

import random

random.seed()

choice=random.randint(0, 2)
if choice==0:
	#do whatever for rock
elif choice==1:
	#do whatever for paper
else:
	#do whatever for scissors

That'll take care of the basics for ya. Later you could try and keep
frequency counts over a bunch of trials, see if the human has a
preference, and then weight your response appropriately to try and beat
them ;)

-Jordan Greenberg


From janos.juhasz at VELUX.com  Tue Aug  8 10:22:55 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Tue, 8 Aug 2006 10:22:55 +0200
Subject: [Tutor] os.system() with NO_WAIT
In-Reply-To: <78b3a9580608071328q42b3d4ecif5ea45bd96f37a0@mail.gmail.com>
Message-ID: <OF5F79BC50.0312AFA9-ONC12571C4.002B55AE-C12571C4.002E0A49@velux.com>

Thanks Wesley,

 I lokked for subprocess.Popen.

os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") was to complicated 
for me based on the manual.


Yours sincerely, 
______________________________
J?nos Juh?sz 
VELUX Magyarorsz?g Fert?di ?p?t?komponens Kft. 
IT Department
Malom K?z 1, H-9431 Fert?d 
Telephone direct:      +36 99 537 939
Telephone office:      +36 99 537 920
Office fax:                +36 99 537 921
Telephone mobile:    +36 30 682 6331
@                             janos.juhasz at VELUX.com
www                        www.VELUX.com




"wesley chun" <wescpy at gmail.com> 

2006.08.07 22:28

To
"J?nos Juh?sz" <janos.juhasz at velux.com>
cc
tutor at python.org
Subject
Re: [Tutor] os.system() with NO_WAIT



>         os.system('vedicom.exe')
>
> Have you got any idea how I can strart this windows GUI program with not
> waiting its return.

instead of os.system(), you want to use the subprocess module if you
are using Python 2.4+:
http://docs.python.org/lib/module-subprocess.html

calling subprocess.Popen(["/bin/mycmd", "myarg"]) is "no wait."

to save the PID:

pid = subprocess.Popen(["/bin/mycmd", "myarg"]).pid

if you are using Python 2.3.x and older, you have to use spawn*():

pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")

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

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060808/a7461a4b/attachment.html 

From member at dorch.wanadoo.co.uk  Mon Aug  7 11:02:14 2006
From: member at dorch.wanadoo.co.uk (David Wilson)
Date: Mon,  7 Aug 2006 11:02:14 +0200 (CEST)
Subject: [Tutor] python
Message-ID: <20443208.1154941334662.JavaMail.www@wwinf3101>

can you explain functions in python to me and give me some examples


From kent37 at tds.net  Tue Aug  8 15:48:01 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 8 Aug 2006 9:48:01 -0400
Subject: [Tutor] Community documentation framework?
Message-ID: <20060808134801.WJBN22195.outaamta02.mail.tds.net@smtp.tds.net>

> 
> From: "Bob Nienhuis" <bob.nienhuis at gmail.com>
> 

> Features I would like to see:
>     A Wikipedia-like capacity for community update-ability/modifiability
>     of documentation submissions.

Fredrik Lundh has started wikis for the Python docs. I'm on vacation and don't have the links but you should be able to find them in the blog archives at effbot.org.

Kent

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


From bashu at yandex.ru  Tue Aug  8 16:23:43 2006
From: bashu at yandex.ru (Basil Shubin)
Date: Tue, 08 Aug 2006 21:23:43 +0700
Subject: [Tutor] Regex search in HTML data
Message-ID: <44D89E6F.2080805@yandex.ru>

Hi friends,

Please, see the attachment and examine a code I have provide. The 
problem is, I want fetch data from <H2>Comments</H2> until the first 
</TD> occurrence , but with my code data fetchind until the last </TD> 
in htmlData variable, but that is not what I want. So question is, what 
is my mistake?

Thanks in advance.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test.py
Type: text/x-python
Size: 2108 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060808/cba5f438/attachment.py 

From cappy2112 at gmail.com  Tue Aug  8 18:00:59 2006
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Tue, 8 Aug 2006 09:00:59 -0700
Subject: [Tutor] Unusual behavior in readline
Message-ID: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com>

I don't understand why readline is producing such unusual behavior.
I don't remember it working like this previously. The docs say it is
supposed to read a line at a time.

this function

def ProcessFile(self, Inputfile, Outputfile=None):

        try:
            fh=open(Inputfile,"r")
        except IOError:
            print"\nError ocurred opening %s for input\n" % Inputfile
        else:
            FixedEntry = []
            Entry = ""
            for Entry in fh.readline():
                print"Entry = %s" % Entry

            fh.close()

is producing this result

Entry = A
Entry = l
Entry = i
Entry = a
Entry = s
Entry = ,
Entry = P
Entry = h
Entry = o
Entry = n
Entry = e

With this input file
Alias,Phone
JANE SMITH,12131234567

Readline is supposed to read an entire line on each call, yet it is only
reading one character.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060808/d7f7e0a7/attachment.htm 

From Mike.Hansen at atmel.com  Tue Aug  8 18:49:22 2006
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Tue, 8 Aug 2006 10:49:22 -0600
Subject: [Tutor] Community documentation framework?
Message-ID: <57B026980605A64F9B23484C5659E32E25503B@poccso.US.ad.atmel.com>

 

	From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]
On Behalf Of Bob Nienhuis
	Sent: Sunday, August 06, 2006 3:56 PM
	To: tutor at python.org
	Subject: [Tutor] Community documentation framework?
	
	

	Have you had the experience of finding a nifty bit of code on
the
	web, trying it out, and then discovering that technique
	only worked in version X.YY, or requires module Z that
	is no longer available?
	
	Well perhaps we can address this situation.
	
	I would like to see an online system that facilitates
	the collaborative production, cataloging and updating of 
	community documentation. See an article, "Rethinking Community 
	Documentation" by Andy Oram 
	
<http://www.onlamp.com/pub/a/onlamp/2006/07/06/rethinking-community-docu
mentation.html>.
	
	Features I would like to see:
	    A Wikipedia-like capacity for community
update-ability/modifiability
	    of documentation submissions.
	
	    Database for cataloging available packages, modules, FAQs,
How-Tos
	    tutorials, cookbook code fragments etc. Should have capacity
for 
	    developers to add and others to add to their contributions. 
	
	    Oram suggests a rating system for submissions so users can
assess
	    the quality of submissions, and point to parts that need
modification
	    or clarification..
	
	    Might use TurboGears, Django AJAX or other web framework?
	
	I think main Python documentation is great, but there is a lot
	of stuff out there that isn't documented so well, or needs
	updating. This project is intended to adress that need.
	
	What would you like to see?
	
----
You might take a look at

http://pyfaq.infogami.com/

Mike	


From alan.gauld at freenet.co.uk  Tue Aug  8 18:59:33 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 8 Aug 2006 17:59:33 +0100
Subject: [Tutor] help regarding forms... (fwd)
References: <Pine.LNX.4.64.0608070753020.17958@hkn.eecs.berkeley.edu><Pine.LNX.4.64.0608071110050.16142@hkn.eecs.berkeley.edu>	<a8e52b650608071125p6ff15c96oc864572ba96c7747@mail.gmail.com><004901c6ba62$2dca1ea0$0201a8c0@XPpro>
	<44D7F2E8.8020305@cc.umanitoba.ca>
Message-ID: <001501c6bb0c$065a7130$0201a8c0@XPpro>

>> I've been on the internet for over 20 years now and every mail
>> tool/newreader I've ever used has (at least) two reply options:
>> ...
>> I don't understand why this seems to come as a surprise?
>> What am I missing?
>
> Alan, I think you are judging based on technical lists, no?

There are other kinds?!! :-)

> mailing list, the more likely it is to be set up with a munged 
> `reply to' header.

What exactly does this mean? I still don't quite see how it works.
Does this mean a user hits Reply to reply to the whole list and
then Reply All - does what???? The same? What a waste!

Alan G. 


From alan.gauld at freenet.co.uk  Tue Aug  8 19:00:53 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 8 Aug 2006 18:00:53 +0100
Subject: [Tutor] Rock, Paper, Scissors
References: <20060808054246.54903.qmail@web51606.mail.yahoo.com>
Message-ID: <001b01c6bb0c$37df2390$0201a8c0@XPpro>

> This looks like a fun project to work on.  From
> reading the description, I feel this would be pretty
> straight forward game to program.  However, I have no
> idea how the computer would decide if it wanted a
> rock, paper, or a pair of scissors.  Any hints?

Assign a value to rock, paper and scissors.
then use the random module to generate one of the 3 values at random.

Alan G.

From rabidpoobear at gmail.com  Tue Aug  8 20:51:13 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 08 Aug 2006 13:51:13 -0500
Subject: [Tutor] Unusual behavior in readline
In-Reply-To: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com>
References: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com>
Message-ID: <44D8DD21.9010107@gmail.com>

Tony Cappellini wrote:
>
> I don't understand why readline is producing such unusual behavior.
> I don't remember it working like this previously. The docs say it is 
> supposed to read a line at a time.
It does :)
>
> this function
>
> def ProcessFile(self, Inputfile, Outputfile=None):
>        
>         try:
>             fh=open(Inputfile,"r")
>         except IOError:
>             print"\nError ocurred opening %s for input\n" % Inputfile
>         else:
>             FixedEntry = []
>             Entry = ""
>             for Entry in fh.readline():
what you're saying in this line is:
1. call the readline method of fh.
2. iterate over each item in the returned value, and assign each item 
the name 'Entry' while in the loop.

What does the readline method of fh return?
it returns a single line.
So you're looping over a single line,
which means that each time through the loop Entry points to a single 
character.

What you want to do is call readline through each iteration of the loop.
or, to make it much easier, you could just use readlines :)
'for Entry in fh.readlines():'

> [snip stuff]
> Readline is supposed to read an entire line on each call, yet it is 
> only reading one character.
>
No, it is, in fact, reading an entire line on _each_ call, the only 
problem being that you only call it once.
HTH,
-Luke

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


From hugonz-lists at h-lab.net  Tue Aug  8 20:57:45 2006
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Tue, 08 Aug 2006 13:57:45 -0500
Subject: [Tutor] python
In-Reply-To: <20443208.1154941334662.JavaMail.www@wwinf3101>
References: <20443208.1154941334662.JavaMail.www@wwinf3101>
Message-ID: <44D8DEA9.8060207@h-lab.net>

Hi David,

Have you read the grat explanation in Alan's tutorial? What problem 
specifically are you having with functions?

http://www.freenetpages.co.uk/hp/alan.gauld/

Get back to us with any questions...

David Wilson wrote:
> can you explain functions in python to me and give me some examples
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From asdlinux at yahoo.se  Tue Aug  8 22:13:00 2006
From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=)
Date: Tue, 08 Aug 2006 22:13:00 +0200
Subject: [Tutor] try & except
Message-ID: <44D8F04C.5040306@yahoo.se>

Hi

I'm playing around with try: and except: i have a code like this
        try:
            bibl=os.listdir("c:\\klientdata\\")
        except:
            wx.MessageBox("Kunde inte l?sa k?ll 
biblioteket.","S?kerhetskopiering",wx.OK|wx.ICON_ERROR)

(yeah ... it's swedish :) )

So far i get how to use it but i would like to be able to execute the 
try block again after it jumped to the exception. How can i make it 
retry to read the directory?
Thanks
Magnus

From dyoo at hkn.eecs.berkeley.edu  Tue Aug  8 22:18:36 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 8 Aug 2006 13:18:36 -0700 (PDT)
Subject: [Tutor] python
In-Reply-To: <20443208.1154941334662.JavaMail.www@wwinf3101>
References: <20443208.1154941334662.JavaMail.www@wwinf3101>
Message-ID: <Pine.LNX.4.64.0608080833240.14001@hkn.eecs.berkeley.edu>



On Mon, 7 Aug 2006, David Wilson wrote:

> can you explain functions in python to me and give me some examples

Hi David,

Have you looked into a Python tutorial yet?

     http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Most of the tutorials there talk about functions.  If you could give us an 
example of what you're having trouble with, that would help us to give 
more specific examples that target that problem.

From broek at cc.umanitoba.ca  Tue Aug  8 22:31:47 2006
From: broek at cc.umanitoba.ca (Brian van den Broek)
Date: Tue, 08 Aug 2006 16:31:47 -0400
Subject: [Tutor] help regarding forms... (fwd)
In-Reply-To: <001501c6bb0c$065a7130$0201a8c0@XPpro>
References: <Pine.LNX.4.64.0608070753020.17958@hkn.eecs.berkeley.edu><Pine.LNX.4.64.0608071110050.16142@hkn.eecs.berkeley.edu>	<a8e52b650608071125p6ff15c96oc864572ba96c7747@mail.gmail.com><004901c6ba62$2dca1ea0$0201a8c0@XPpro>
	<44D7F2E8.8020305@cc.umanitoba.ca>
	<001501c6bb0c$065a7130$0201a8c0@XPpro>
Message-ID: <44D8F4B3.8020007@cc.umanitoba.ca>

Alan Gauld said unto the world upon 08/08/06 12:59 PM:
>>> I've been on the internet for over 20 years now and every mail
>>> tool/newreader I've ever used has (at least) two reply options:
>>> ...
>>> I don't understand why this seems to come as a surprise?
>>> What am I missing?
>>
>> Alan, I think you are judging based on technical lists, no?
> 
> There are other kinds?!! :-)

:-)

>> mailing list, the more likely it is to be set up with a munged `reply 
>> to' header.
> 
> What exactly does this mean? I still don't quite see how it works.
> Does this mean a user hits Reply to reply to the whole list and
> then Reply All - does what???? The same? What a waste!
> 

I've never actually tried `Reply to all' on a munged list. But, since 
on such lists `Reply' is, in effect, an alias for `Reply to all' I 
assume that in addition to breaking expectations, munging is also, as 
you suspect, brought to you by the Department of Redundancy Department.

FWIW, the munging preference is pretty runs pretty deep, I think. I my 
case it took public shame caused by a `private' message that wasn't to 
see the light. :-[

Burned by the memory, I refuse to munge the class mailing lists I 
administer. But one day the complaints will wear me down . . . .

Best,

Brian vdB

From alan.gauld at freenet.co.uk  Tue Aug  8 22:56:02 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 8 Aug 2006 21:56:02 +0100
Subject: [Tutor] python
References: <20443208.1154941334662.JavaMail.www@wwinf3101>
Message-ID: <001101c6bb2d$10241380$0201a8c0@XPpro>


> can you explain functions in python to me and give me some examples

There are many tutorials that do that, including mine.

Take a look at the Modules and functions topic...

Or if you are experienced in other programming 
languages try the official tutorial at python.org.

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

From alan.gauld at freenet.co.uk  Tue Aug  8 23:06:47 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 8 Aug 2006 22:06:47 +0100
Subject: [Tutor] Regex search in HTML data
References: <44D89E6F.2080805@yandex.ru>
Message-ID: <002101c6bb2e$8fa40a60$0201a8c0@XPpro>

> Please, see the attachment and examine a code I have provide. The
> problem is, I want fetch data from <H2>Comments</H2> until the first
> </TD> occurrence ,

Do you mean the unmatched /td that occurs after the dd section?

> import re
> import string
>
> htmlData = """
> <h2>Instructions</h2>....
> <h2>Comments</h2>
>
> <dl>
>  <dd>None
> </dd></dl>
> </td>

To this one here?
Its probably a bad idea to use a regular tag as a marker,
some browsers get confused by unmatched tags.
Using a comment is usually better.


> <td valign="top" width="50%"><h2>Classification</h2>
>
> <h2><table border="1" cellpadding="1" cellspacing="0" height="60" 
> width="100%">
> <tbody><tr>
> <td width="50%"><b>&nbsp;Utility:</b></td>

But regex don;t like working with nested tags, you have
a table cell inside another and writing regexs to match
that can get very tricky. So if you want to search into
this part of the string you should probably look at
using Beautiful Soup or similar HTML parser.

> if __name__ == '__main__':
>    # Extract comments
>    p = re.search('<H2>Comments</H2>(.+)</TD>', htmlData,
>                  re.I | re.S | re.M)

Looks like you are getting caught out by the "greedy" nature
of regex - they grab as much as they can.

You can control that by adding a ? immediately after the +
but given the nature of your html I'd try using BeautifulSoup instead.

You'll find a short section on greedy expressions in my regex
topic on my tutorial site.

HTH,

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


From john at fouhy.net  Tue Aug  8 23:11:02 2006
From: john at fouhy.net (John Fouhy)
Date: Wed, 9 Aug 2006 09:11:02 +1200
Subject: [Tutor] try & except
In-Reply-To: <44D8F04C.5040306@yahoo.se>
References: <44D8F04C.5040306@yahoo.se>
Message-ID: <5e58f2e40608081411maf21514l2dc4107821faeae@mail.gmail.com>

On 09/08/06, Magnus Wirstr?m <asdlinux at yahoo.se> wrote:
> Hi
>
> I'm playing around with try: and except: i have a code like this
>        try:
>            bibl=os.listdir("c:\\klientdata\\")
>        except:
>            wx.MessageBox("Kunde inte l?sa k?ll
> biblioteket.","S?kerhetskopiering",wx.OK|wx.ICON_ERROR)
>
> (yeah ... it's swedish :) )
>
> So far i get how to use it but i would like to be able to execute the
> try block again after it jumped to the exception. How can i make it
> retry to read the directory?

What logic are you looking for?  Is it ---

  "Try to read directory.  If it doesn't work, try again.  If it still
doesn't work, abort."

or ---

   "Try to read directory.  If it doesn't work, keep trying until it does."

In the former case, you could just put another try block in your except block:

       try:
           bibl=os.listdir("c:\\klientdata\\")
       except:
           wx.MessageBox("Kunde inte l?sa k?ll
biblioteket.","S?kerhetskopiering",wx.OK|wx.ICON_ERROR)
           try:
               bibl=os.listdir("c:\\klientdata\\")
           except:
               wx.MessageBox("Kunde inte l?sa k?ll
biblioteket.","S?kerhetskopiering",wx.OK|wx.ICON_ERROR)

In the latter case, you probably want some kind of loop:

success = False
while not success:
       try:
           bibl=os.listdir("c:\\klientdata\\")
           success = True
       except:
           wx.MessageBox("Kunde inte l?sa k?ll
biblioteket.","S?kerhetskopiering",wx.OK|wx.ICON_ERROR)

Of course, it would be nice to give the users another way out of the loop :-)

HTH!

-- 
John.

From alan.gauld at freenet.co.uk  Tue Aug  8 23:12:39 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 8 Aug 2006 22:12:39 +0100
Subject: [Tutor] Unusual behavior in readline
References: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com>
Message-ID: <003501c6bb2f$61bf45a0$0201a8c0@XPpro>


>I don't understand why readline is producing such unusual behavior.
> I don't remember it working like this previously. The docs say it is
> supposed to read a line at a time.

It does.

> def ProcessFile(self, Inputfile, Outputfile=None):
>
>        try:
>            fh=open(Inputfile,"r")
>        except IOError:
>            print"\nError ocurred opening %s for input\n" % Inputfile
>        else:
>            FixedEntry = []
>            Entry = ""

You don't need to initialise Entry, the for loop does that for you.


>            for Entry in fh.readline():

readline returns a string and the for loop iterates over it.
You need readl;ines to return all of the strings in the file.
Or nowadays just use

               for Entry in fh:

>                print"Entry = %s" % Entry

BTW Why not just put all this stuff in the body of the try?
Thats what try/except is for, to stop cluttering up the code with
error handling sections and move that to the end out of the way....
You should very rarely need an else clause when using try/except.

> Readline is supposed to read an entire line on each call,
> yet it is only reading one character.

No, it is reading a line, you are then iterating over that line
one character at a time.

HTH,

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


From alan.gauld at freenet.co.uk  Tue Aug  8 23:29:10 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 8 Aug 2006 22:29:10 +0100
Subject: [Tutor] try & except
References: <44D8F04C.5040306@yahoo.se>
Message-ID: <004301c6bb31$b07e80f0$0201a8c0@XPpro>

> I'm playing around with try: and except: i have a code like this
>        try:
>            bibl=os.listdir("c:\\klientdata\\")
>        except:
>            wx.MessageBox("Kunde inte l?sa k?ll ...
>
> So far i get how to use it but i would like to be able to execute 
> the try block again after it jumped to the exception.

Yes, thats a common desire, unfortunately it isn't possible,
at least not directly.

One way round this is to put the try inside a function then
call the function inside an outer try, like this:

def mylistdir(d):
     try:   bibl = os.listdir(d)
     except: raise

try:
    mylistdir("C:\\....")
except:
    print 'oops!'
    mylistdir(default)

But even here you only get wo bites at the pie.

If you need more you need to write a loop:

success = False
while not success
      try:
            mylistdir(d)
            success = True
      except: print 'oops!'


But I agree a retry option would be nice. But I've never found a
language yet that supports it. (There are some good reasons why
this is the case BTW, to do with the uncertain state of the code
block that you exit.)

HTH,

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


From wescpy at gmail.com  Tue Aug  8 23:59:33 2006
From: wescpy at gmail.com (wesley chun)
Date: Tue, 8 Aug 2006 14:59:33 -0700
Subject: [Tutor] Unusual behavior in readline
In-Reply-To: <003501c6bb2f$61bf45a0$0201a8c0@XPpro>
References: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com>
	<003501c6bb2f$61bf45a0$0201a8c0@XPpro>
Message-ID: <78b3a9580608081459n319f4d98q302c329e30f49f51@mail.gmail.com>

summarizing what folks have already said plus a few more tweaks such
as moving the close() to finally (2.5+), following the style guideline
of variable non-titlecasing, removing unused variables, etc.:

#!/usr/bin/env python2.5

def processFile(inputfile):
    try:
        fh = open(inputfile, "r")
        for entry in fh:
            print "Entry = %s" % entry.strip()
    except IOError, e:
        print "\nError occurred opening %s for input\n" % inputfile
    finally:
        fh.close()

if __name__ == '__main__':
    processFile('phone')

we get this output:

$ tony.py
Entry = Alias,Phone
Entry = JANE SMITH,12131234567

the try-except-finally statement was unified (again) coming up in 2.5.
 i say again because it was actually there before but removed in
version 0.9.6.  :-)

how about some 2.6 fun and using the with statement to get rid of
finally and closing the file, as a 2.5 preview?

#!/usr/bin/env python2.5

from __future__ import with_statement

def processFile(inputfile):
    try:
        with open(inputfile, "r") as fh:
            for entry in fh:
                print "Entry = %s" % entry.strip()
    except IOError, e:
        print "\nError occurred opening %s for input\n" % inputfile

the context management of the with statement will automagically close
the file regardless of exceptions so you do not need to worry about
it.  in 2.6, both 'with' and 'as' become keywords -- you will be
warned in 2.5.

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

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

From anilmrn at yahoo.com  Wed Aug  9 01:48:19 2006
From: anilmrn at yahoo.com (anil maran)
Date: Tue, 8 Aug 2006 16:48:19 -0700 (PDT)
Subject: [Tutor] searching for a string in a dictionary
Message-ID: <20060808234819.11532.qmail@web55913.mail.re3.yahoo.com>


all_types:
<Storage {'type': 'childcare', 'id': 1, 'created': datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
<Storage {'type': 'household', 'id': 2, 'created': datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
.....
<Storage {'type': 'knews', 'id': 10, 'created': datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
there is such a list

how do i search for a particular string say teststring in this list

i tried

if teststring in all_types:
if teststring in all_types.type: 
it doesnt work


please help me out here
should i use lambda


 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060808/b36677ca/attachment.htm 

From kermit at polaris.net  Wed Aug  9 04:54:58 2006
From: kermit at polaris.net (Kermit Rose)
Date: Tue, 8 Aug 2006 22:54:58 -0400 (Eastern Daylight Time)
Subject: [Tutor] Exercise in writing a python function.
Message-ID: <44D94E82.000013.00176@YOUR-4105E587B6>

 Hello all.
 
 
I feel more familar with Python now, and when I recently went back to
reading
the tutorial,  I could actually read it without being overwhelmed by too
much new detail.
 
 
I've been staring at the specs for a python function for a while.
 
I wrote one version of it and it worked.
 
Then I changed the specs, and now need to reconstruct my original work.
 
I'm sure I can do it fairly easily.
 
I'm not asking anyone to write the function for me.
 
It did occur to me that it could be a classroom exercise for other students.
 
The current specifications for the function are:
 
 
def incr(mult,z,zlim,mpylist):
# mult is a vector of exponents for the multipliers in mpylist.
# z is a positive odd  integer.
# zlim is the upper bound  critical value for the sum of  ( mpylist[k][0] *
mpylist[k][1] ) 
# where kth multiplier is mpylist [k][0]
# and kth  multiplier index is mpylist [k][1]
 
# function incr returns the next value of vector mult.
# mult may be thought as a number written in a variable base.
# mult[0] is the least significant and matches multiplier mpylist[0][0]
# adding one to mult would mean adding 1 to mult[0]
# unless doing so would make sum of multiplier * index exceed zlim.
# in that case mult[0] is set to zero, and 1 is added to mult[1]
# unless doing so would make sum of multilier * index exceed zlim
# in that case, mult[0] and mult[1] is set to zero,
# and 1 is added to mult[2]
# unless . . .
 

# mult[0] is set to -1 to indicate that the largest possible value of mult
has been exceeded.
# mpylist[0][0] = 2 and all other multipliers  in mpylist are odd.
# mult[0], the index on multiplier 2, must not equal 1.  It may equal zero,
or any integer > 1, 
# provided the zlim constraint is met.
 
 
 
 
 
 


From john at fouhy.net  Wed Aug  9 05:37:46 2006
From: john at fouhy.net (John Fouhy)
Date: Wed, 9 Aug 2006 15:37:46 +1200
Subject: [Tutor] Exercise in writing a python function.
In-Reply-To: <44D94E82.000013.00176@YOUR-4105E587B6>
References: <44D94E82.000013.00176@YOUR-4105E587B6>
Message-ID: <5e58f2e40608082037iad27a01gfa1ce20272acbda8@mail.gmail.com>

On 09/08/06, Kermit Rose <kermit at polaris.net> wrote:
> def incr(mult,z,zlim,mpylist):
> # mult is a vector of exponents for the multipliers in mpylist.
> # z is a positive odd  integer.
> # zlim is the upper bound  critical value for the sum of  ( mpylist[k][0] *
> mpylist[k][1] )
> # where kth multiplier is mpylist [k][0]
> # and kth  multiplier index is mpylist [k][1]
>
> # function incr returns the next value of vector mult.
> # mult may be thought as a number written in a variable base.
> # mult[0] is the least significant and matches multiplier mpylist[0][0]
> # adding one to mult would mean adding 1 to mult[0]
> # unless doing so would make sum of multiplier * index exceed zlim.
> # in that case mult[0] is set to zero, and 1 is added to mult[1]
> # unless doing so would make sum of multilier * index exceed zlim
> # in that case, mult[0] and mult[1] is set to zero,
> # and 1 is added to mult[2]
> # unless . . .
>
>
> # mult[0] is set to -1 to indicate that the largest possible value of mult
> has been exceeded.
> # mpylist[0][0] = 2 and all other multipliers  in mpylist are odd.
> # mult[0], the index on multiplier 2, must not equal 1.  It may equal zero,
> or any integer > 1,
> # provided the zlim constraint is met.

Hi Kermit,

Is there anything particular that you're stuck on?

I think I understand your function, although I'm not sure what role z
plays.  Are you looking for help on how to translate the description
you've given into logic suitable for programming?

-- 
John.

From john at fouhy.net  Wed Aug  9 06:04:27 2006
From: john at fouhy.net (John Fouhy)
Date: Wed, 9 Aug 2006 16:04:27 +1200
Subject: [Tutor] Exercise in writing a python function.
In-Reply-To: <44D95C9D.000015.00176@YOUR-4105E587B6>
References: <5e58f2e40608082037iad27a01gfa1ce20272acbda8@mail.gmail.com>
	<44D95C9D.000015.00176@YOUR-4105E587B6>
Message-ID: <5e58f2e40608082104w6ebefe62h5cfd5310a5175b31@mail.gmail.com>

On 09/08/06, Kermit Rose <kermit at polaris.net> wrote:
> Hello John.
>
> Thanks for replying.
>
> In my previous version,  I used z as the critical value,.
>
> Since I created zlim,  a function of z, to be passed in as a parameter, I no
> longer need z
>
> in the parameter list.
>
> In another part of the program, z is multiplied by
>
> product of mpylist[ k][0] ** mult[k] for k  in range(len(mpylist)).
>
>
> I'm feeling something akin to writer's block when I sit down and attempt to
> start the code.
>
> I know that if I can just get started then the rest of the code will begin
> to flow in my thoughts.
>
> I did not really expect anyone to help me, but if you wish to  indicate the
> first few lines of
>
> either python or psuedo code
> for this routine, it probably will help me get started.
>
>
> Kermit   <  kermit at polaris.net  >

Hi Kermit,

Your basic data structure is a list (actually, several related lists),
which you work your way through.  So I would start off with a for
loop:

    for k in range(len(mult)):

Then, in the body of the loop, your basic logic is:

    Add 1 to mult[k].
    If mult[k] is not too big, exit.
    Otherwise, ...

Hmm, actually, I'm not sure I do understand.  Does mpylist ever
change?  How is mult related to zlim?

-- 
John.

From alan.gauld at freenet.co.uk  Wed Aug  9 09:14:24 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 08:14:24 +0100
Subject: [Tutor] searching for a string in a dictionary
References: <20060808234819.11532.qmail@web55913.mail.re3.yahoo.com>
Message-ID: <003101c6bb83$7195cb30$0201a8c0@XPpro>

> all_types:
> <Storage {'type': 'childcare', 'id': 1, 'created': 
> datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
> <Storage {'type': 'household', 'id': 2, 'created': 
> datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
> .....
> <Storage {'type': 'knews', 'id': 10, 'created': 
> datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
> there is such a list
>
> how do i search for a particular string say teststring in this list

This isn't a list in any sense that Python will recognise.
Can you show us the actual data structures please?

> if teststring in all_types:

This would only work if teststring was exactly equal to a
whole string in your list, partial string matches only work against a 
single string:

>>> if "fred" in ["fred", "jack"]: print True
True
>>> if "red"  in ["fred", "jack"]: print True
>>>

>>> for item in ["fred", "jack"]:
>>>      if "red" in item: print item
...
fred
>>>

> if teststring in all_types.type:

No idea what you think this would do.
lists don't have a type attribute and you can't access bits
of strings that way either.

What Python tutorial are you reading?
Almost all the tutorials cover string searching and list access.

> should i use lambda

Almost certainly not.
Why do you think lambda would be useful here?

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


From alan.gauld at freenet.co.uk  Wed Aug  9 09:30:03 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 08:30:03 +0100
Subject: [Tutor] Exercise in writing a python function.
References: <44D94E82.000013.00176@YOUR-4105E587B6>
Message-ID: <003501c6bb85$a13ea6c0$0201a8c0@XPpro>

> The current specifications for the function are:
>
> def incr(mult,z,zlim,mpylist):
> # mult is a vector of exponents for the multipliers in mpylist.
> # z is a positive odd  integer.
> # zlim is the upper bound  critical value for the sum of  ( 
> mpylist[k][0] *
> mpylist[k][1] )

Just to clarify what this means.
you have mpylist = [(2,3),(3,5),(5,7)]
So the products list is: [6,15,35]
So zlim in this case should be greater than the
sum of products: 6+15+35 = 56

Have I got that right?

> # where kth multiplier is mpylist [k][0]
> # and kth  multiplier index is mpylist [k][1]

Not sure what you mean by the multiplier index?
The sum above shows mpylist[k][1] being used in the multiplication,
not as an index?

> # function incr returns the next value of vector mult.

I'm still not clear what mult does, your example above doesn't
refer to mult anywhere?

> # mult may be thought as a number written in a variable base.
> # mult[0] is the least significant and matches multiplier 
> mpylist[0][0]
> # adding one to mult would mean adding 1 to mult[0]
> # unless doing so would make sum of multiplier * index exceed zlim.
> # in that case mult[0] is set to zero, and 1 is added to mult[1]
> # unless doing so would make sum of multilier * index exceed zlim
> # in that case, mult[0] and mult[1] is set to zero,
> # and 1 is added to mult[2]
> # unless . . .

Sorry, you lost me there, can you provide a concrete example?
Or maybe some of our resident math experts recognise what
you are up to and can explain? Brian? Danny?

> # mult[0] is set to -1 to indicate that the largest possible value 
> of mult
> has been exceeded.
> # mpylist[0][0] = 2 and all other multipliers  in mpylist are odd.
> # mult[0], the index on multiplier 2, must not equal 1.  It may 
> equal zero,
> or any integer > 1,
> # provided the zlim constraint is met.

The only guidance I'd give in this kind of situation is that I'd adopt
functional programming approaches and try to copy the structure
of the spec in my code. This will be a bitch to test/debug unless
you have a wealth of manually validated examples to use as test
cases!

HTH

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


From john at fouhy.net  Wed Aug  9 09:41:56 2006
From: john at fouhy.net (John Fouhy)
Date: Wed, 9 Aug 2006 19:41:56 +1200
Subject: [Tutor] searching for a string in a dictionary
In-Reply-To: <003101c6bb83$7195cb30$0201a8c0@XPpro>
References: <20060808234819.11532.qmail@web55913.mail.re3.yahoo.com>
	<003101c6bb83$7195cb30$0201a8c0@XPpro>
Message-ID: <5e58f2e40608090041q526b8e93uab1c620e4b40b74f@mail.gmail.com>

On 09/08/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> > all_types:
> > <Storage {'type': 'childcare', 'id': 1, 'created':
> > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
> > <Storage {'type': 'household', 'id': 2, 'created':
> > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
> > .....
> > <Storage {'type': 'knews', 'id': 10, 'created':
> > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
> > there is such a list
> >
> > how do i search for a particular string say teststring in this list
>
> This isn't a list in any sense that Python will recognise.
> Can you show us the actual data structures please?

I think what he wants is:

    if 'teststring' in [s.type for s in all_types]

...

-- 
John.

From alan.gauld at freenet.co.uk  Wed Aug  9 09:42:48 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 08:42:48 +0100
Subject: [Tutor] Unusual behavior in readline
References: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com>
	<003501c6bb2f$61bf45a0$0201a8c0@XPpro>
	<8249c4ac0608081705m317ba719g8de1eef84e1b4ce5@mail.gmail.com>
Message-ID: <004101c6bb87$69490510$0201a8c0@XPpro>

<CCing back to the list>

>>>You don't need to initialise Entry, the for loop does that for you.
>
> just a habit- I've always initialized my vars up front.
> so I know they are initialized.

Fair enough, good practice for other languages certainly.

>> >>BTW Why not just put all this stuff in the body of the try?
>
> Because the try is only setup to catch an IO error.
> If something other than an IOerror were to occur, it would be
> missed unless other exceptions were trapped.

Its missed in the else clause too.
But the else clause adds two extra control structures
(the except and the else) to the code for the reader to
negotiate which significantly impairs comprehension
of the main execution path.

> The most probable is the IOerror, which is why I trapped it.

Which is fine but no reason to put the except clause immediately
after the try line, that just clutters the code block.

>>>You should very rarely need an else clause when using try/except.

> If the exception doesn't happen, then what ?

The code just goes through:

try:
   if False: raise ValueError    # never happens
   print 'hello'
   print 'world'
   print 'this code is pretty safe'
except ValueError: print 'its a mistake!"

No need for an else clause.

> That's what the else clause is for

Nope, the else clause is for a few unusual cases where you
need to do stuff if no exception occurs that is not part of the
main processing. I've only ever seen a real valid use of it
once in dealing with housekeeping of sockets, and even
there a finally block could have been used at the cost of
an extra try statement. The else just kept it a bit tidier.

But else should not be used for mainstream processing.
One of the biggest advantages of try/except handling is that
it removes all the error processing out of the way of the
reader to the bottom of the block. You can just write the
happy path stuff as a continuous sequence without worrying
about error paths. (FWIW This is also the recommended
practice in writing use cases, for the same reasons)

Of course else can be used as you did and the code will
work, but you lose a big advantage of try/except style.

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


From alan.gauld at freenet.co.uk  Wed Aug  9 10:03:58 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 09:03:58 +0100
Subject: [Tutor] searching for a string in a dictionary
References: <20060808234819.11532.qmail@web55913.mail.re3.yahoo.com>
	<003101c6bb83$7195cb30$0201a8c0@XPpro>
	<5e58f2e40608090041q526b8e93uab1c620e4b40b74f@mail.gmail.com>
Message-ID: <000301c6bb8a$5e867970$0201a8c0@XPpro>


> On 09/08/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>> > all_types:
>> > <Storage {'type': 'childcare', 'id': 1, 'created':
>> > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
>> >
>> > how do i search for a particular string say teststring in this 
>> > list
>>

> I think what he wants is:
>
>    if 'teststring' in [s.type for s in all_types]

But type is still not accessible as an attribute.
It looked to me like he wanted a list of dictionaries
in which case it wouyld be:

if teststring in [s['type'] for s in all_types]

But the submitted data is not in any usable format so far
as Python is concxerned and the data structure will be
critical to how the code works.

Anil, we need to get more specific information from you
about your code and error messages, we can't guess
what you have done.

Alan G 


From john at fouhy.net  Wed Aug  9 10:14:51 2006
From: john at fouhy.net (John Fouhy)
Date: Wed, 9 Aug 2006 20:14:51 +1200
Subject: [Tutor] searching for a string in a dictionary
In-Reply-To: <000301c6bb8a$5e867970$0201a8c0@XPpro>
References: <20060808234819.11532.qmail@web55913.mail.re3.yahoo.com>
	<003101c6bb83$7195cb30$0201a8c0@XPpro>
	<5e58f2e40608090041q526b8e93uab1c620e4b40b74f@mail.gmail.com>
	<000301c6bb8a$5e867970$0201a8c0@XPpro>
Message-ID: <5e58f2e40608090114n44bcd2d6xb38dc5953a52d759@mail.gmail.com>

On 09/08/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> But type is still not accessible as an attribute.
> It looked to me like he wanted a list of dictionaries
> in which case it wouyld be:
>
> if teststring in [s['type'] for s in all_types]

Err, that is what I meant :-)

-- 
John.

From hokkakada at khmeros.info  Wed Aug  9 10:36:05 2006
From: hokkakada at khmeros.info (kakada)
Date: Wed, 09 Aug 2006 15:36:05 +0700
Subject: [Tutor] python import problem
Message-ID: <44D99E75.3010902@khmeros.info>

Hi all,

I have problem with import statement.

supposed that I have two files in different folders : modules/myfile.py
and translate/factory.py.


the folders modules and translate are in the same level, so if I want to
import factory.py into myfile.py, how can I do?


I have already done in myfile.py:

from translate import factory

but it is still not work. Any solution?

Thanks and regards,
da

From anilmrn at yahoo.com  Wed Aug  9 11:55:11 2006
From: anilmrn at yahoo.com (anil maran)
Date: Wed, 9 Aug 2006 02:55:11 -0700 (PDT)
Subject: [Tutor] searching for a string in a dictionary
In-Reply-To: <000301c6bb8a$5e867970$0201a8c0@XPpro>
Message-ID: <20060809095511.39539.qmail@web55904.mail.re3.yahoo.com>

if teststring in [s['type'] for s in all_types]:
                print 'contained'
            else:
                print 'notcontained'

this worked
thanks a lot guys
pyTutor rocks
Alan Gauld <alan.ga uld at freenet.co.uk> wrote: 
> On 09/08/06, Alan Gauld  wrote:
>> > all_types:
>> > 
>> > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
>> >
>> > how do i search for a particular string say teststring in this 
>> > list
>>

> I think what he wants is:
>
>    if 'teststring' in [s.type for s in all_types]

But type is still not accessible as an attribute.
It looked to me like he wanted a list of dictionaries
in which case it wouyld be:

if teststring in [s['type'] for s in all_types]

But the submitted data is not in any usable format so far
as Python is concxerned and the data structure will be
critical to how the code works.

Anil, we need to get more specific information from you
about your code and error messages, we can't guess
what you have done.

Alan G 



 		
---------------------------------
Get your email and more, right on the  new Yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060809/5a7561d2/attachment.html 

From anilmrn at yahoo.com  Wed Aug  9 11:59:53 2006
From: anilmrn at yahoo.com (anil maran)
Date: Wed, 9 Aug 2006 02:59:53 -0700 (PDT)
Subject: [Tutor] searching for a string in a dictionary
In-Reply-To: <000301c6bb8a$5e867970$0201a8c0@XPpro>
Message-ID: <20060809095953.3795.qmail@web55911.mail.re3.yahoo.com>

doesTypeExist=filter(lambda x: typeofstring in x.type, all_types)

 if 'teststring' in [s.type for s in all_types]
this works which is better in terms of speed???

for+in or filter+lambda

thanks a lot

Alan Gauld <alan.gauld at freenet.co.uk> wrote: 
> On 09/08/06, Alan Gauld  wrote:
>> > all_types:
>> > 
>> > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}>
>> >
>> > how do i search for a particular string say teststring in this 
>> > list
>>

> I think what he wants is:
>
>    if 'teststring' in [s.type for s in all_types]

But type is still not accessible as an attribute.
It looked to me like he wanted a list of dictionaries
in which case it wouyld be:

if teststring in [s['type'] for s in all_types]

But the submitted data is not in any usable format so far
as Python is concxerned and the data structure will be
critical to how the code works.

Anil, we need to get more specific information from you
about your code and error messages, we can't guess
what you have done.

Alan G 



 				
---------------------------------
Want to be your own boss? Learn how on  Yahoo! Small Business. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060809/a5094310/attachment.htm 

From anilmrn at yahoo.com  Wed Aug  9 12:00:51 2006
From: anilmrn at yahoo.com (anil maran)
Date: Wed, 9 Aug 2006 03:00:51 -0700 (PDT)
Subject: [Tutor] html file - construct attach send... email python
Message-ID: <20060809100051.12465.qmail@web55903.mail.re3.yahoo.com>

What is the best way to construct an email in python and also attach a html file

the html file to be attached is not on disk, but should be dynamically constructed in the python script

thanks a lot
 		
---------------------------------
Stay in the know. Pulse on the new Yahoo.com.  Check it out. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060809/ab52339d/attachment.html 

From asdlinux at yahoo.se  Wed Aug  9 12:28:58 2006
From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=)
Date: Wed, 09 Aug 2006 12:28:58 +0200
Subject: [Tutor] Global Variables
Message-ID: <44D9B8EA.9040600@yahoo.se>

Hi

I know that this was in the list in the last days but i deleted it by 
mistake. How to use global variables? Or perhaps you could point me to 
another solution. I'm converting a packup app that i made to a gui 
driven app. The console app was very straight forward and didn't use any 
own functions. That was working fine then but i discover now that i 
probably have to rethink that because i need to communicate to different 
events. I'm new to all this so i have a problem to approach this. I 
would be really happy if you could give me hints and tips or suggestions 
how to make this. The gui i want to work with is wxPython and i'm using 
Boa Constructor to build my gui and app.

Thanks
Magnus


From samrobertsmith at gmail.com  Wed Aug  9 12:49:15 2006
From: samrobertsmith at gmail.com (linda.s)
Date: Wed, 9 Aug 2006 03:49:15 -0700
Subject: [Tutor] about tkinter
Message-ID: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com>

Is that possible to open two Tkinter from one python shell?

From alan.gauld at freenet.co.uk  Wed Aug  9 13:11:44 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 12:11:44 +0100
Subject: [Tutor] searching for a string in a dictionary
References: <20060809095953.3795.qmail@web55911.mail.re3.yahoo.com>
Message-ID: <001301c6bba4$99e85a50$0201a8c0@XPpro>

> doesTypeExist=filter(lambda x: typeofstring in x.type, all_types)
>
> if 'teststring' in [s.type for s in all_types]
> this works which is better in terms of speed???

These do two different things.
The first returns a list of all_types entries that match
The second returns true or false if *any* string matches.

The first can be rewritten without lambda using a list comprehension:

[ item for item in all_types if teststring in item['type'] ]

Calling functions in python is usually fairly slow so using 
filter/lambda
with its function call per item is probably slower than either of the
list comprehension methods. If in doubt measure it...

Alan G.


From alan.gauld at freenet.co.uk  Wed Aug  9 13:16:03 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 12:16:03 +0100
Subject: [Tutor] python import problem
References: <44D99E75.3010902@khmeros.info>
Message-ID: <003501c6bba5$3418db40$0201a8c0@XPpro>

> the folders modules and translate are in the same level, so if I 
> want to
> import factory.py into myfile.py, how can I do?

You need to make your folders into packages.
Its fairly simple, you basically create an init.py file
But its worth reading about packages in the docs
Come back here ifv you have any questions after that.

The other way would be to add each folder to
your PYTHONPATH

HTH,

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


From kermit at polaris.net  Wed Aug  9 16:02:53 2006
From: kermit at polaris.net (Kermit Rose)
Date: Wed, 9 Aug 2006 10:02:53 -0400 (Eastern Daylight Time)
Subject: [Tutor] Exercise in writing a python function.
References: <003501c6bb85$a13ea6c0$0201a8c0@XPpro>
Message-ID: <44D9EB0D.000007.03316@YOUR-4105E587B6>

 
 
From: Alan Gauld 
Date: 08/09/06 03:30:28 
To: Kermit Rose; tutor at python.org 
Subject: Re: [Tutor] Exercise in writing a python function. 
 
> The current specifications for the function are: 
> 
> def incr(mult,z,zlim,mpylist): 
> # mult is a vector of exponents for the multipliers in mpylist. 
> # z is a positive odd integer. 
> # zlim is the upper bound critical value for the sum of ( 
> mpylist[k][0] * 
> mpylist[k][1] ) 
 
Just to clarify what this means. 
you have mpylist = [(2,3),(3,5),(5,7)] 
So the products list is: [6,15,35] 
So zlim in this case should be greater than the 
sum of products: 6+15+35 = 56 
 
*******
 
Oops.  That is what  I said.
 
I made a mistake in the specificiations.
 
I should have specified that 
for this example
that
3*mult[0] + 5 * mult[1] + 7 * mult[2] must be < zlim.
 
>>>>>
 
 
 
# where kth multiplier is mpylist [k][0] 
> # and kth multiplier index is mpylist [k][1] 
 
Not sure what you mean by the multiplier index? 
The sum above shows mpylist[k][1] being used in the multiplication, 
not as an index? 
 
 
******
 
Yes.  It's confusing because of my mistake of confusing mpylist[k][1] with
mult[k].
 
 
>>>>
 
> # function incr returns the next value of vector mult. 
 
I'm still not clear what mult does, your example above doesn't 
refer to mult anywhere? 
 
 
*****
 
Yes, another consequence of my mistake in the specifications.
 
 
Kermit   <  kermit at polaris.net   >
 
 


From kermit at polaris.net  Wed Aug  9 16:13:20 2006
From: kermit at polaris.net (Kermit Rose)
Date: Wed, 9 Aug 2006 10:13:20 -0400 (Eastern Daylight Time)
Subject: [Tutor] Exercise in writing a python function
Message-ID: <44D9ED80.00000B.03316@YOUR-4105E587B6>

  
Message: 2
Date: Wed, 9 Aug 2006 16:04:27 +1200
From: "John Fouhy" <john at fouhy.net>
Subject: Re: [Tutor] Exercise in writing a python function.
To: "Tutor mailing list" <tutor at python.org>
 
 
Hi Kermit,
 
Your basic data structure is a list (actually, several related lists),
which you work your way through.  So I would start off with a for
loop:
 
    for k in range(len(mult)):
 
Then, in the body of the loop, your basic logic is:
 
    Add 1 to mult[k].
    If mult[k] is not too big, exit.
    Otherwise, ...
 
Hmm, actually, I'm not sure I do understand.  Does mpylist ever
change?  How is mult related to zlim?
 
--
John.
 
*****
 
Thank you.
 
I confused things by my mistake in the specifications.
 
The criterion for exiting the outer loop is that
 
mpylist[0][1] * mult[0] + mpylist[1][1] * mult[1] + mpylist[2][1] * mult[2]
+ . . . 
 
be > zlim.
 
 
 
 
 


From tpwilson at hotmail.co.uk  Tue Aug  8 16:53:10 2006
From: tpwilson at hotmail.co.uk (Tom Wilson)
Date: Tue, 08 Aug 2006 15:53:10 +0100
Subject: [Tutor] python
Message-ID: <BAY15-F70E703606F7CAEB5A039C96540@phx.gbl>

could someone explain to me how the "import" function works?

tom

_________________________________________________________________
The new Windows Live Toolbar helps you guard against viruses 
http://toolbar.live.com/?mkt=en-gb


From kermit at polaris.net  Wed Aug  9 16:46:59 2006
From: kermit at polaris.net (Kermit Rose)
Date: Wed, 9 Aug 2006 10:46:59 -0400 (Eastern Daylight Time)
Subject: [Tutor] programming exercise in Python
Message-ID: <44D9F563.00000F.03316@YOUR-4105E587B6>

 
 
Thanks to John,
 
I've written tenative code for the incr routine.
 
Now to test and possibly debug it.
 
Here is the routine.  It's very short.
 
#
#
# def incr(mult,zlim,mpylist):
# # mult is a vector of exponents for the multipliers in mpylist.
# # z is the integer to be factored
# # zlim is the critical value for the sum of multiplier * index
# # where kth multiplier is mpylist [k][0]
# # and kth index is mpylist [k][1]
#
# # function incr returns the next value of vector mult.
# # mult may be thought as a number written in a variable base.
# # mult[0] is the least significant and matches multiplier mpylist[0][0]
# # adding one to mult would mean adding 1 to mult[0]
# # unless doing so would make sum of mpylist[k][1] * mult[k] exceed zlim.
# # in that case mult[0] is set to zero, and 1 is added to mult[1]
# # unless doing so would make sum of multilier * index exceed zlim
# # in that case, mult[0] and mult[1] is set to zero,
# # and 1 is added to mult[2]
# # unless . . .
#
#
# # mult[0] is set to -1 to indicate that the largest possible value of mult
has been exceeded.
# # mpylist[0] = 2 and all other values in mpylist are odd.
# # mult[0], the index on multiplier 2, must not equal 1.  It may equal zero
 or any integer > 1,
# # provided it meets the zlim constraint.
#
#     lenmult = len(mult)
#     for k in range(lenmult):
#         mult[k] = mult[k] + 1
#         if k == 0:
#             if mult[k] == 1:
#                mult[k] = 2 
#         testsum = 0
#         if k > 0:
#             mult[k-1] = 0
#         for j in range(k,lenmult):
#             testsum = testsum + mpylist[j][1] * mult[j]
#         if testsum < zlim:
#             return mult
#     mult[0] = -1
#     return mult
#
#


From dyoo at hkn.eecs.berkeley.edu  Wed Aug  9 17:00:55 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 9 Aug 2006 08:00:55 -0700 (PDT)
Subject: [Tutor] programming exercise in Python
In-Reply-To: <44D9F563.00000F.03316@YOUR-4105E587B6>
References: <44D9F563.00000F.03316@YOUR-4105E587B6>
Message-ID: <Pine.LNX.4.64.0608090757460.18371@hkn.eecs.berkeley.edu>



On Wed, 9 Aug 2006, Kermit Rose wrote:


> I've written tenative code for the incr routine.
>
> Now to test and possibly debug it.

Just as a note: it's usually a much better idea to write your test cases 
first, even before writing any code.  It'll give you a better idea of what 
you want your function to do.

(It'll also probably give the other here a better idea of what the 
function is supposed to do.  I myself don't quite know either what it's 
supposed to do based solely on the description.  *grin*)


What are some small test cases you're thinking of for this function?

From dyoo at hkn.eecs.berkeley.edu  Wed Aug  9 17:05:09 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 9 Aug 2006 08:05:09 -0700 (PDT)
Subject: [Tutor] python
In-Reply-To: <BAY15-F70E703606F7CAEB5A039C96540@phx.gbl>
References: <BAY15-F70E703606F7CAEB5A039C96540@phx.gbl>
Message-ID: <Pine.LNX.4.64.0608090801040.18371@hkn.eecs.berkeley.edu>



On Tue, 8 Aug 2006, Tom Wilson wrote:

> could someone explain to me how the "import" function works?

Hi Tom,

Take a look at:

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

and see if that helps; if not, come back and please feel free to ask more 
questions about it.  In a short summary: import allows us to load 
additional "modules" into our program.  These modules are often written by 
other people, and provide a lot of interesting functions.  There are a set 
of modules that come standard with each Python distribution:

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

For example, if we wanted to get an approximate value for pi, we could 
find that in the 'math' module:

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

and to use it, we'd use 'import' to first pull math support into our 
program:

######
import math
######

after which we can reach in and get a piece of pi:

######
print math.pi
######

From dyoo at hkn.eecs.berkeley.edu  Wed Aug  9 17:07:45 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 9 Aug 2006 08:07:45 -0700 (PDT)
Subject: [Tutor] about tkinter
In-Reply-To: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com>
References: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0608090805520.18371@hkn.eecs.berkeley.edu>



On Wed, 9 Aug 2006, linda.s wrote:

> Is that possible to open two Tkinter from one python shell?


It is possible to open more Tkinter "toplevel" windows.  Is this what you 
are asking for?  See:

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

If we build a new Toplevel, we should see a new window on our screen.

From dyoo at hkn.eecs.berkeley.edu  Wed Aug  9 17:18:30 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 9 Aug 2006 08:18:30 -0700 (PDT)
Subject: [Tutor] html file - construct attach send... email python
In-Reply-To: <20060809100051.12465.qmail@web55903.mail.re3.yahoo.com>
References: <20060809100051.12465.qmail@web55903.mail.re3.yahoo.com>
Message-ID: <Pine.LNX.4.64.0608090808370.18371@hkn.eecs.berkeley.edu>



On Wed, 9 Aug 2006, anil maran wrote:

> What is the best way to construct an email in python and also attach a 
> html file


Hi Anil,

This is a repeat of one of your previous questions; you just sent this 
question out yesterday:

     http://mail.python.org/pipermail/tutor/2006-August/048452.html

We are forgetful, but we're not THAT senile yet.

Please do not repost your questions so early: give some people more time 
to construct a good answer for you.  Repeating a question so soon like 
this tends to demotivate people.


Have you looked at the 'email' module?

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

And in general, do you know about the Standard Library, or the Python 
Cookbook?

     http://www.python.org/doc/lib/
     http://aspn.activestate.com/ASPN/Python/Cookbook/

I want to make sure you know about these documentation resources.


Good luck to you.

From alan.gauld at freenet.co.uk  Wed Aug  9 18:36:42 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 17:36:42 +0100
Subject: [Tutor] about tkinter
References: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com>
Message-ID: <001d01c6bbd1$ff361050$0201a8c0@XPpro>

Linda,

> Is that possible to open two Tkinter from one python shell?

Tkinter is a python module. You can't really open a Tkinter, 
you can only import the module. What you can do is write 
a Tkinter application with multiple windows.

You can have as many Tkinter applications running as 
you like but they will all be separate processes.

Can you be clearer about what exactly you want to do?

Alan G.

From kermit at polaris.net  Wed Aug  9 18:39:24 2006
From: kermit at polaris.net (Kermit Rose)
Date: Wed, 9 Aug 2006 12:39:24 -0400 (Eastern Daylight Time)
Subject: [Tutor] programming exercise in Python
References: <Pine.LNX.4.64.0608090757460.18371@hkn.eecs.berkeley.edu>
Message-ID: <44DA0FBC.000011.03316@YOUR-4105E587B6>

 
 
From: Danny Yoo 
Date: 08/09/06 11:01:14 
To: Kermit Rose 
Cc: tutor at python.org 
Subject: Re: [Tutor] programming exercise in Python 
 
 
 
On Wed, 9 Aug 2006, Kermit Rose wrote: 
 
 
> I've written tenative code for the incr routine. 
> 
> Now to test and possibly debug it. 
 
Just as a note: it's usually a much better idea to write your test cases 
first, even before writing any code. It'll give you a better idea of what 
you want your function to do. 
 
(It'll also probably give the other here a better idea of what the 
function is supposed to do. I myself don't quite know either what it's 
supposed to do based solely on the description. *grin*) 
 
 
What are some small test cases you're thinking of for this function? 
s function? 
 
 
********
 
Hello Danny.
 
The test cases are
 
For mpylist = [[2, 1], [3, 2], [7, 3], [5, 2], [31, 5], [127, 7]]
 

zlim = 7
 
Initial value of mult = [0,0,0,0,0,0]
 
next few values of mult are:
 
[2, 0, 0, 0, 0, 0]   because mult[0] must skip over value of 1 and 2 * 1 < 7
 
[3, 0, 0, 0, 0, 0]   because 3 * 1 < 7
[4, 0, 0, 0, 0, 0]   because 4 * 1 < 7
[5, 0, 0, 0, 0, 0]   because 5 * 1 < 7
[6, 0, 0, 0, 0, 0]   because 6 * 1 < 7
[0, 1, 0, 0, 0, 0]   because 1 * 2 < 7
[2, 1, 0, 0, 0, 0]   because 2 * 1 + 1 * 2 < 7
[3, 1, 0, 0, 0, 0]   because 3 * 1 + 1 * 2 < 7
[4, 1, 0, 0, 0, 0]   because 4 * 1 + 1 * 2 < 7
[0, 2, 0, 0, 0, 0]   because 0 * 1 + 2 * 2 < 7
[2, 2, 0, 0, 0, 0]   because 2 * 1 + 2 * 2 < 7  and mult[0] value must skip
1
[0, 3, 0, 0, 0, 0]   because 0 * 1 + 3 * 2 < 7
[0, 0, 1, 0, 0, 0]   because 0 * 1 + 0 * 2 + 1 * 3 < 7
[2, 0, 1, 0, 0, 0]   because 2 * 1 + 0 * 2 + 1 * 3 < 7
[3, 0, 1, 0, 0, 0]   because 3 * 1 + 0 * 2 + 1 * 3 < 7
[0, 1, 1, 0, 0, 0]   because 0 * 1 + 1 * 2 + 1 * 3 < 7
 
 
I had the program generate the test cases for me, and then inspected them to
verify that 
they were what I desired.
 
The subroutine passed this initial test.
 
Thanks 
 
 
 
 
 
 


From alan.gauld at freenet.co.uk  Wed Aug  9 18:39:41 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 17:39:41 +0100
Subject: [Tutor] Exercise in writing a python function
References: <44D9ED80.00000B.03316@YOUR-4105E587B6>
Message-ID: <002701c6bbd2$69cf7e10$0201a8c0@XPpro>

> I confused things by my mistake in the specifications.
>
> The criterion for exiting the outer loop is that
>
> mpylist[0][1] * mult[0] + mpylist[1][1] * mult[1] + mpylist[2][1] * 
> mult[2]
> + . . .
>
> be > zlim.

Can you try rewriting the spec correctly, because I'm still not
sure I understand it? Are you now saying that mpylist[n][0] is never 
used?

Can you show us some sample data structures - just a few entries
and how the calculations should work?

Alan G. 


From alan.gauld at freenet.co.uk  Wed Aug  9 18:41:42 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 17:41:42 +0100
Subject: [Tutor] python
References: <BAY15-F70E703606F7CAEB5A039C96540@phx.gbl>
Message-ID: <002b01c6bbd2$b2552a90$0201a8c0@XPpro>

Tom,

> could someone explain to me how the "import" function works?

Which tutorial are you reading? They should all describe import.

My tutorial gives the basic description on the Simple sequences 
topic and then much more info in the Modules & Functions topic 
and again in the Namespaces topic.

Between them and the Python documentation you should find 
all you need. But if you are still puzzled come back to us with 
specific questions.

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

From alan.gauld at freenet.co.uk  Wed Aug  9 18:53:48 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 17:53:48 +0100
Subject: [Tutor] programming exercise in Python
References: <44D9F563.00000F.03316@YOUR-4105E587B6>
Message-ID: <002f01c6bbd4$62ff57c0$0201a8c0@XPpro>

> #     lenmult = len(mult)

This is pretty redundant, it only saves two characters typing,
you might as well do

for k in range(len(mult)):

> #     for k in range(lenmult):
> #         mult[k] = mult[k] + 1


> #         if k == 0:
> #             if mult[k] == 1:
> #                mult[k] = 2

The whole of this bit only happens on the first time through
the outer loop. The effect of it is to set mult[0] to 2 if its initial
value was 0, so why not move it outside the loop and do:

if mult[0] == 0: mult[0] = 1

Then the  increment of the whole list will uplift it to 2 along
with all the other increments.

> #         testsum = 0
> #         if k > 0:
> #             mult[k-1] = 0
> #         for j in range(k,lenmult):
> #             testsum = testsum + mpylist[j][1] * mult[j]

My brain is bending with this bit! I'm not sure if its right or not...
I'm still not sure i understand what its trying to do...


> #         if testsum < zlim:
> #             return mult
> #     mult[0] = -1
> #     return mult

But I think this can be better expressed as:

              if testsum >= zlim:
                   mult[0] = -1   # failure condiotion
         return mult


As a matter of interest what does this bizarre algorithm
accomplish in a practical sense? What is its purpose?
I am truly intrigued...


HTH,

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


From kermit at polaris.net  Wed Aug  9 19:29:49 2006
From: kermit at polaris.net (Kermit Rose)
Date: Wed, 9 Aug 2006 13:29:49 -0400 (Eastern Daylight Time)
Subject: [Tutor] programming exercise in Python
References: <002f01c6bbd4$62ff57c0$0201a8c0@XPpro>
Message-ID: <44DA1B8D.000015.03316@YOUR-4105E587B6>

 
 
From: Alan Gauld 
Date: 08/09/06 12:53:59 
To: Kermit Rose; tutor at python.org 
Subject: Re: [Tutor] programming exercise in Python 
 
> # lenmult = len(mult) 
 
This is pretty redundant, it only saves two characters typing, 
you might as well do 
 
******
 
hmm....
 
I had gotten in the habit of replacing  potential multiple function calls
and array references with variable name references 
acting from the hypothesis 
that variable name references take much less time than array referrences or
function calls.
 
I agree that in this case I did not need to do so.
 
>>>>>>>
 
for k in range(len(mult)): 
 
> # for k in range(lenmult): 
> # mult[k] = mult[k] + 1 
 
 
> # if k == 0: 
> # if mult[k] == 1: 
> # mult[k] = 2 
 
The whole of this bit only happens on the first time through 
the outer loop. The effect of it is to set mult[0] to 2 if its initial 
value was 0, so why not move it outside the loop and do: 
 
if mult[0] == 0: mult[0] = 1 
 
Then the increment of the whole list will uplift it to 2 along 
with all the other increments. 
 
******
 
Yes.  I see that now.   
 
I did see that I asked the computer to do extra work by 
having it  do work conditional of the initial value of k, but did not
immediately see
how to move that work outside the loop.
 
 
 
>>>>>>>>
 
> # testsum = 0 
> # if k > 0: 
> # mult[k-1] = 0 
> # for j in range(k,lenmult): 
> # testsum = testsum + mpylist[j][1] * mult[j] 
 
My brain is bending with this bit! I'm not sure if its right or not... 
I'm still not sure i understand what its trying to do... 
 
 
for k = 0, checks to see if it may add 1 to mult[0]
for k = 1, sets mult[0] = 0, and checks to see if it may add 1 to mult[1]
for k = 2, sets mult[1] = 0, and checks to see if it may add 1 to mult[2],
etc
 
>>>>>>>>>>>>
 
> # if testsum < zlim: 
> # return mult 
> # mult[0] = -1 
> # return mult 
 
But I think this can be better expressed as: 
 
if testsum >= zlim: 
mult[0] = -1 # failure condiotion 
return mult 
 
 
*****
 
The indentation did not survive  repeated postings.
 
..    if testsum < zlim:
..        return mult
..    mult[0] = -1
..    return mult
 
if testsum < zlim I return mult
if testsum >= zlim, I advance the k loop
 
failure condition is that it get all the way through the k loop and not be
able to increment mult.
 
 
 
>>>>>>>>>
 
As a matter of interest what does this bizarre algorithm 
accomplish in a practical sense? What is its purpose? 
I am truly intrigued... 
 
 
*******
 
:)
 
The incr routine generates a vector of exponents to apply to the list
 
mpylist [n] [0]
 
m = product of   mpylist [k] [0] ** mult[k]
 
Another subroutine uses the number m 
 
in an algorithm I've devised,
 
 to find a  divisor of the number z,
 
from which I had calculated the critical value of zlim,
 
and the mpylist vector.
 
Experimentation will tell if this factor routine is as good as I would like
it to be.
 
Kermit   <  kermit at polaris.net  >
 
 
 
 
 
 
 
 
 
 
 
 
 
 


From alan.gauld at freenet.co.uk  Wed Aug  9 19:51:47 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 18:51:47 +0100
Subject: [Tutor] programming exercise in Python
References: <002f01c6bbd4$62ff57c0$0201a8c0@XPpro>
	<44DA1B8D.000015.03316@YOUR-4105E587B6>
Message-ID: <000501c6bbdc$7ca22c40$0201a8c0@XPpro>

>> # testsum = 0
>> # if k > 0:
>> # mult[k-1] = 0
>> # for j in range(k,lenmult):
>> # testsum = testsum + mpylist[j][1] * mult[j]
>
> My brain is bending with this bit! I'm not sure if its right or 
> not...
>
> for k = 0, checks to see if it may add 1 to mult[0]
> for k = 1, sets mult[0] = 0, and checks to see if it may add 1 to 
> mult[1]
> for k = 2, sets mult[1] = 0, and checks to see if it may add 1 to 
> mult[2],

So you work along mult setting each member to zero after incrementing 
it?

> The incr routine generates a vector of exponents to apply to the 
> list
>
> mpylist [n] [0]
>
> m = product of   mpylist [k] [0] ** mult[k]
>

But haven't you set all of mult[k] to zero, using the example 
algorithm above?

> Experimentation will tell if this factor routine is as good as I 
> would like
> it to be.

Its got me baffled, thats for sure! :-)

Alan G.


From kermit at polaris.net  Wed Aug  9 20:28:26 2006
From: kermit at polaris.net (Kermit Rose)
Date: Wed, 9 Aug 2006 14:28:26 -0400 (Eastern Daylight Time)
Subject: [Tutor] programming exercise in Python
References: <000501c6bbdc$7ca22c40$0201a8c0@XPpro>
Message-ID: <44DA294A.000019.03316@YOUR-4105E587B6>

 
 
 
From: Alan Gauld 
Date: 08/09/06 13:52:09 
To: Kermit Rose 
Cc: tutor at python.org 
Subject: Re: [Tutor] programming exercise in Python 
 
>> # testsum = 0 
>> # if k > 0: 
>> # mult[k-1] = 0 
>> # for j in range(k,lenmult): 
>> # testsum = testsum + mpylist[j][1] * mult[j] 
> 
> My brain is bending with this bit! I'm not sure if its right or 
> not... 
> 
> for k = 0, checks to see if it may add 1 to mult[0] 
> for k = 1, sets mult[0] = 0, and checks to see if it may add 1 to 
> mult[1] 
> for k = 2, sets mult[1] = 0, and checks to see if it may add 1 to 
> mult[2], 
 
So you work along mult setting each member to zero after incrementing 
it? 
 
 
******
 
Yes.  After each member has gone through all allowed incrementations, I
reset it to zero.
 
Remember that mult is returned as soon as any member is incremented.
 
 
>>>>>>>>>
 
> The incr routine generates a vector of exponents to apply to the 
> list 
> 
> mpylist [n] [0] 
> 
> m = product of mpylist [k] [0] ** mult[k] 
> 
 
But haven't you set all of mult[k] to zero, using the example 
algorithm above? 
 
*******
 
Ah, now I understandd how I misled you.
 
> for k = 0, checks to see if it may add 1 to mult[0] 
 
if it can add 1 to mult[0], do so, and return mult.  otherwise continue
 
> for k = 1, sets mult[0] = 0, and checks to see if it may add 1 to 
> mult[1] 
 
if it can add 1 to mult[1], do so, and return mult.  otherwise continue
 
> for k = 2, sets mult[1] = 0, and checks to see if it may add 1 to 
> mult[2], 
 
if it can add 1 to mult[2], do so, and return mult.  otherwise continue
etc
 
 
 
Kermit   <  kermit at polaris.net  >
 
 


From dyoo at hkn.eecs.berkeley.edu  Wed Aug  9 22:23:04 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 9 Aug 2006 13:23:04 -0700 (PDT)
Subject: [Tutor] programming exercise in Python
In-Reply-To: <44DA0FBC.000011.03316@YOUR-4105E587B6>
References: <Pine.LNX.4.64.0608090757460.18371@hkn.eecs.berkeley.edu>
	<44DA0FBC.000011.03316@YOUR-4105E587B6>
Message-ID: <Pine.LNX.4.64.0608091028210.18371@hkn.eecs.berkeley.edu>


> I had the program generate the test cases for me, and then inspected 
> them to verify that they were what I desired.

Hi Kermit,

Ah.  Try not to do that next time.

It's way too easy to be convinced that some test is working by just 
copying the output of the code and looking for reasonable output.  But 
it's much more useful to write out the complete test case without 
preconceptions, without the aid of the code you're trying to test.  This 
works because:

     * You can't cheat yourself.  *grin*

     * Writing out the test cases first can help in writing the
       real function.

Those test cases act as documentation that other people can look at. 
They're a form of specification --- a requirement --- that allows others 
to understand the intent of the function.

From tbrannon at utekcorp.com  Wed Aug  9 22:21:31 2006
From: tbrannon at utekcorp.com (Terrence Brannon)
Date: Wed, 9 Aug 2006 16:21:31 -0400
Subject: [Tutor] html file - construct attach send... email python
In-Reply-To: <44DA294A.000019.03316@YOUR-4105E587B6>
Message-ID: <4CB7A012BD745F4DBAAC57D05A787D073ABC56@utek-exch.utekcorp.local>

Here's a script I wrote to email myself the Python Daily webpage as
HTML:
http://dev.metaperl.com/Members/tbrannon/python/code-snippets/script-to-
email-python-daily/

From pythontut at pusspaws.net  Wed Aug  9 22:45:22 2006
From: pythontut at pusspaws.net (dave s)
Date: Wed, 9 Aug 2006 20:45:22 +0000
Subject: [Tutor] rstrip() failure ?
Message-ID: <200608092045.22580.pythontut@pusspaws.net>

I have a string problem. The following code skips the loop if the string 'app' 
is on the banned list ...

self.ban_app_list = 
[' ', 'live_dat', 'exact_sl', 'html_str', 'valid_da', 'datacore', 'check_co', 'logger']

if app in self.ban_app_list:
	continue

the string 'app' is derived from some more string splicing. All works well 
except for 'logger', the 'app' string becomes 'logger  ' so no match. So I 

app.rstrip()

thinking it would sort the problem. no go :(

len(app) is still 8. OK ... I am stuck ...

Is there a way to show the ascii values of the string - kind of hexedit for a 
string

I am sure the padding blanks are just spaces rstrip() appears to disagree

Any help greatly appreciated

Dave

From alan.gauld at freenet.co.uk  Wed Aug  9 22:45:52 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 21:45:52 +0100
Subject: [Tutor] programming exercise in Python
References: <Pine.LNX.4.64.0608090757460.18371@hkn.eecs.berkeley.edu><44DA0FBC.000011.03316@YOUR-4105E587B6>
	<Pine.LNX.4.64.0608091028210.18371@hkn.eecs.berkeley.edu>
Message-ID: <002101c6bbf4$ce7a6560$0201a8c0@XPpro>

> it's much more useful to write out the complete test case without 
> preconceptions, without the aid of the code you're trying to test. 
> This works because:

>     * Writing out the test cases first can help in writing the
>       real function.
>
> Those test cases act as documentation that other people can look at.

Can I echo that.

After I saw your test output I immediately understood how the
function was supposed to work. If you could have posted that
sample input/output data along with the spec before writing
the code we could have been much more helpful - I think... ;-)

Alan G. 


From dyoo at hkn.eecs.berkeley.edu  Wed Aug  9 23:11:52 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 9 Aug 2006 14:11:52 -0700 (PDT)
Subject: [Tutor] rstrip() failure ?
In-Reply-To: <200608092045.22580.pythontut@pusspaws.net>
References: <200608092045.22580.pythontut@pusspaws.net>
Message-ID: <Pine.LNX.4.64.0608091409500.20960@hkn.eecs.berkeley.edu>

> Is there a way to show the ascii values of the string - kind of hexedit 
> for a string

Try running repr() on the string: it will show an external 
programmer-friendly representation that should be easier to read.  For 
example:

##########################
>>> msg = 'hello\000world'
>>> print repr(msg)
'hello\x00world'
##########################

From pythontut at pusspaws.net  Wed Aug  9 23:12:28 2006
From: pythontut at pusspaws.net (dave s)
Date: Wed, 9 Aug 2006 21:12:28 +0000
Subject: [Tutor] [Doh!] rstrip() failure ?
In-Reply-To: <200608092045.22580.pythontut@pusspaws.net>
References: <200608092045.22580.pythontut@pusspaws.net>
Message-ID: <200608092112.30697.pythontut@pusspaws.net>

On Wednesday 09 August 2006 20:45, dave s wrote:
> I have a string problem. The following code skips the loop if the string
> 'app' is on the banned list ...
>
> self.ban_app_list =
> [' ', 'live_dat', 'exact_sl', 'html_str', 'valid_da', 'datacore',
> 'check_co', 'logger']
>
> if app in self.ban_app_list:
> 	continue
>
> the string 'app' is derived from some more string splicing. All works well
> except for 'logger', the 'app' string becomes 'logger  ' so no match. So I
>
> app.rstrip()
>
> thinking it would sort the problem. no go :(
>
> len(app) is still 8. OK ... I am stuck ...
>
> Is there a way to show the ascii values of the string - kind of hexedit for
> a string
>
> I am sure the padding blanks are just spaces rstrip() appears to disagree
>
> Any help greatly appreciated
>
> Dave
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Stupid basic error held me up for a couple of hours :)

app.rstrip()  should have been
app = app.rstrip()

From pythontut at pusspaws.net  Wed Aug  9 23:15:11 2006
From: pythontut at pusspaws.net (dave s)
Date: Wed, 9 Aug 2006 21:15:11 +0000
Subject: [Tutor] rstrip() failure ?
In-Reply-To: <Pine.LNX.4.64.0608091409500.20960@hkn.eecs.berkeley.edu>
References: <200608092045.22580.pythontut@pusspaws.net>
	<Pine.LNX.4.64.0608091409500.20960@hkn.eecs.berkeley.edu>
Message-ID: <200608092115.12096.pythontut@pusspaws.net>

On Wednesday 09 August 2006 21:11, you wrote:
> > Is there a way to show the ascii values of the string - kind of hexedit
> > for a string
>
> Try running repr() on the string: it will show an external
> programmer-friendly representation that should be easier to read.  For
> example:
>
> ##########################
>
> >>> msg = 'hello\000world'
> >>> print repr(msg)
>
> 'hello\x00world'
> ##########################

Thanks for that :) 

Have just found my solution without resorting to ascii strings after all but 
the above will be usefull

Thanks once again

Dave

From anilmrn at yahoo.com  Thu Aug 10 00:16:37 2006
From: anilmrn at yahoo.com (anil maran)
Date: Wed, 9 Aug 2006 15:16:37 -0700 (PDT)
Subject: [Tutor] What techniques should I use to make my code run faster?
	Informational
Message-ID: <20060809221637.63184.qmail@web55907.mail.re3.yahoo.com>

      What techniques should I use to make my code run faster?         Always profile before you optimize for speed.   You should always optimize for readability first: it's easier to tune   readable code than to read 'optimized' code, especially if the optimizations   are not effective. Before using any technique that makes the code less   readable, you should check that it's actually a bottleneck in your   application by running your application with the built-in profile.py   script. If your program spends 10% of its time running a particular   method, even if you increase its speed tenfold you've only shaved 9% off the   total running time.   
      Always use a good algorithm when it is available.   The exception to the above rule is when there are known large differences in the   time complexity of alternative algorithms. Reducing running time from   quadratic to linear, or from exponential to polynomial, is always worth   doing unless you are sure that the data sets will always be tiny (less than   a couple of dozen items).   
       Use the simplest option that could possibly work.   Don't use a regular expression if you just want to see if a string starts   with a particular substring: use .startswith instead. Don't use   .index if you just want to see if a string contains a particular   letter: use in instead. Don't use StringIO if you could   just use a list of strings. In general, keeping it simple cuts down on   bugs and makes your code more readable. Even a complicated combination of   .index calls will be much faster than a regular expression, and   probably easier to decipher if you're just matching rather than capturing   the result.   
      Build strings as a list and use ''.join at the end.   Yes, you already saw this one above under "Python Idioms", but it's such   an important one that I thought I'd mention it again.   join is a string method called on the separator,   not the list. Calling it from the empty string concatenates the pieces   with no separator, which is a Python quirk and rather surprising at first.   This is important: string building with + is quadratic time instead of    linear!   
   
Wrong: 
for s in strings: result += s
Right: 
result = ''.join(strings)
  
       Use tests for object identity when appropriate: if x is not    None rather than if x != None. It is much more efficient to   test objects for identity than equality, because identity only checks   their address in memory (two objects are identical if they are the same   object in the same physical location) and not their actual data.   
       Use dictionaries for searching, not lists. To find items in common   between two lists, make the first into a dictionary and then look for items   in the second in it. Searching a list for an item is linear-time, while   searching a dict for an item is constant time. This can often let you   reduce search time from quadratic to linear.   
       Use the built-in sort wherever possible. sort can   take a custom comparison function as a parameter, but this makes it very   slow because the function has to be called at least O(n log n) times in the   inner loop. To save time, turn the list of items into a list of tuples,   where the first element of each tuple has the precalculated value of the   function for each item (e.g. extracting a field), and the last element is the   item itself.   
      This idiom is called DSU for 'decorate-sort-undecorate.'   In the 'decorate' step, make a list of tuples   containing (transformed_value, second_key, ... , original value).   In the 'sort' step, use the built-in sort on the tuples. In the   'undecorate' step, retrieve the original list in the sorted order by   extracting the last item from each tuple. For example:   
   
aux_list = [i.Count, i.Name, ... i) for i in items]
aux_list.sort()    #sorts by Count, then Name, ... , then by item itself
sorted_list = [i[-1] for i in items] #extracts last item
  
       Use map and/or filter to apply functions to lists.   map applies a function to each item in a list (technically, sequence)   and returns a list of the results. filter applies a function to each   item in a sequence, and returns a list containing only those items for which   the function evaluated True (using the __nonzero__ built-in   method). These functions can make code much shorter. They also make it much   faster, since the loop takes place entirely in the C API and never has to   bind loop variables to Python objects.   
   
Worse:
strings = []
for d in data:
    strings.append(str(d))

Better:
strings = map(str, data)
  
       Use list comprehensions where there are conditions attached, or where    the functions are methods or take more than one parameter. These are   cases where map and filter do badly, since you have to   make up a new one-argument function that does the operation you want. This   makes them much slower, since more work is done in the Python layer. List   comprehensions are often surprisingly readable.   
   
Worse:
result = []
for d in data:
    if d.Count > 4:
        result.append[3*d.Count]

Better:
result = [3*d.Count for d in data if d.Count > 4]
  
      If you find yourself making the same list comprehension repeatedly, make   utility functions and use map and/or filter:   
   
def triple(x):
    """Returns 3 * x.Count: raises AttributeError if .Count missing."""
    return 3 * x.Count

def check_count(x):
    """Returns 1 if x.Count exists and is greater than 3, 0 otherwise."""
    try:
        return x.Count > 3
    except:
        return 0

result = map(triple, filter(check_count, data))
  
       Use function factories to create utility functions.   Often, especially if you're using map and filter a lot,   you need utility functions that convert other functions or methods to   taking a single parameter. In particular, you often want to bind some data   to the function once, and then apply it repeatedly to different objects.   In the above example, we needed a function that multiplied a particular field   of an object by 3, but what we really want is a factory that's able to return   for any field name and amount a multiplier function in that family:   
   
def multiply_by_field(fieldname, multiplier):
    """Returns function that multiplies field "fieldname" by multiplier."""
    def multiplier(x):
        return getattr(x, fieldname) * multiplier
    return multiplier

triple = multiply_by_field('Count', 3)
quadruple = multiply_by_field('Count', 4)
halve_sum = multiply_by_field('Sum', 0.5)
  
      This is a very powerful and general technique for producing functions that   might do something like search a specified field for a list of words, or   perform several actions on different fields of a particular object, etc.   It's a pain to write a lot of little functions that do very similar things,   but if they're produced by a function factory it's easy.   
       Use the operator module and reduce to get sums, products, etc.   reduce takes a function and a sequence. First it applies the   function to the first two items, then it takes the result and applies the   function to the result and the next item, takes that result and applies the   function to it and the next item, and so on until the end of the list. This   makes it very easy to accumulate items along a list (or, in fact, any   sequence). Note that Python 2.3 has a built-in sum() function (for numbers only),   making this less necessary than it used to be.   
   
Worse:
sum = 0
for d in data:
    sum += d
product = 1
for d in data:
    product *= d

Better:
from operator import add, mul
sum = reduce(add, data)
product = reduce(mul, data)
  
       Use zip and dict to map fields to names.   zip turns a pair of sequences into a list of tuples containing   the first, second, etc. values from each sequence. For example,   zip('abc', [1,2,3]) == [('a',1),('b',2),('c',3)]. You can use   this to save a lot of typing when you have fields in a known order that   you want to map to names:   
   
Bad:
fields = '|'.split(line)
gi = fields[0]
accession = fields[1]
description = fields[2]
#etc.
lookup = {}
lookup['GI'] = gi
lookup['Accession'] = accession
lookup['Description'] = description
#etc.

Good:
fieldnames = ['GI', 'Accession', 'Description'] #etc.
fields = '|'.split(line)
lookup = dict(zip(fieldnames, fields))

Ideal:
def FieldWrapper(fieldnames, delimiter, constructor=dict):
    """Returns function that splits a line and wraps it into an object.

    Field names are passed in as keyword args, so constructor must be
    expecting them as such.
    """
    def FieldsToObject(line):
        fields = [field.strip() for field in line.split(delimiter)]
        result = constructor(**dict(zip(fieldnames, fields)))
    return FieldsToObject

FastaFactory = FieldWrapper(['GI','Accession','Description'], '|', Fasta)
TaxonFactory = FieldWrapper(['TaxonID', 'ParentID', ...], '|', Taxon)
CodonFreqFactory = FieldWrapper(['UUU', 'UUC', 'UUA',...], ' ', CodonFreq)
#etc for similar data, including any database tables you care to wrap
  

 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060809/16a5be90/attachment-0001.html 

From alan.gauld at freenet.co.uk  Thu Aug 10 00:41:52 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 9 Aug 2006 23:41:52 +0100
Subject: [Tutor] What techniques should I use to make my code run
	faster?Informational
References: <20060809221637.63184.qmail@web55907.mail.re3.yahoo.com>
Message-ID: <001e01c6bc05$0435a240$0201a8c0@XPpro>

Hi Anil,

It looks like you found the info below somewhere, it would be
nice to credit the source and if possible provide a URL - not
least so we can all bookmark it and see if it gets updated
over time?... :-)

Thanks for posting,

Alan G.

----- Original Message ----- 
From: "anil maran" <anilmrn at yahoo.com>
To: <tutor at python.org>
Sent: Wednesday, August 09, 2006 11:16 PM
Subject: [Tutor] What techniques should I use to make my code run 
faster?Informational


>      What techniques should I use to make my code run faster?
Always profile before you optimize for speed.   You should always
optimize for readability first: it's easier to tune readable code than
to read 'optimized' code, etc....


From wescpy at gmail.com  Thu Aug 10 00:46:59 2006
From: wescpy at gmail.com (wesley chun)
Date: Wed, 9 Aug 2006 15:46:59 -0700
Subject: [Tutor] python import problem
In-Reply-To: <003501c6bba5$3418db40$0201a8c0@XPpro>
References: <44D99E75.3010902@khmeros.info>
	<003501c6bba5$3418db40$0201a8c0@XPpro>
Message-ID: <78b3a9580608091546u13348ff2jcde00388ea6eb453@mail.gmail.com>

> > if I want to import factory.py into myfile.py, how can I do?
>
> You need to make your folders into packages.
> Its fairly simple, you basically create an init.py file
> But its worth reading about packages in the docs
> Come back here ifv you have any questions after that.
>
> The other way would be to add each folder to
> your PYTHONPATH

the rules for importing modules in packages is going to change over
the next few releases... read up on those changes starting from here:

http://docs.python.org/dev/whatsnew/pep-328.html

the simplest solution, as alan's described, is to put all directories
that have your Python modules in the PYTHONPATH environment variable.
if you are on a Unix-based system, just set this variable in your
shell.  if you are on Win32, right-mouse My Computer -> System
Properties -> Advanced -> Environment Variables -> Edit (User or
System variables) -> Ok.

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

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

From anilmrn at yahoo.com  Thu Aug 10 01:17:58 2006
From: anilmrn at yahoo.com (anil maran)
Date: Wed, 9 Aug 2006 16:17:58 -0700 (PDT)
Subject: [Tutor] What techniques should I use to make my code run
	faster?Informational
In-Reply-To: <001e01c6bc05$0435a240$0201a8c0@XPpro>
Message-ID: <20060809231758.60043.qmail@web55913.mail.re3.yahoo.com>

http://jaynes.colorado.edu/PythonIdioms.html#idioms_efficient

Alan Gauld <alan.gauld at freenet.co.uk> wrote: Hi Anil,

It looks like you found the info below somewhere, it would be
nice to credit the source and if possible provide a URL - not
least so we can all bookmark it and see if it gets updated
over time?... :-)

Thanks for posting,

Alan G.

----- Original Message ----- 
From: "anil maran" 
To: 
Sent: Wednesday, August 09, 2006 11:16 PM
Subject: [Tutor] What techniques should I use to make my code run 
faster?Informational


>      What techniques should I use to make my code run faster?
Always profile before you optimize for speed.   You should always
optimize for readability first: it's easier to tune readable code than
to read 'optimized' code, etc....



 		
---------------------------------
Do you Yahoo!?
 Get on board. You're invited to try the new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060809/76f67263/attachment.htm 

From wescpy at gmail.com  Thu Aug 10 01:27:46 2006
From: wescpy at gmail.com (wesley chun)
Date: Wed, 9 Aug 2006 16:27:46 -0700
Subject: [Tutor] What techniques should I use to make my code run
	faster?Informational
In-Reply-To: <20060809231758.60043.qmail@web55913.mail.re3.yahoo.com>
References: <001e01c6bc05$0435a240$0201a8c0@XPpro>
	<20060809231758.60043.qmail@web55913.mail.re3.yahoo.com>
Message-ID: <78b3a9580608091627j4c68e6f3w9c017780abfb0bbb@mail.gmail.com>

the overall root document of this useful read is:

http://jaynes.colorado.edu/PythonGuidelines.html

-wesley

From dyoo at hkn.eecs.berkeley.edu  Thu Aug 10 02:58:02 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 9 Aug 2006 17:58:02 -0700 (PDT)
Subject: [Tutor] html file - construct attach send... email python (fwd)
Message-ID: <Pine.LNX.4.64.0608091757170.31895@hkn.eecs.berkeley.edu>

Can someone help Amil?  My hands won't allow me to type too long.  Thanks!

---------- Forwarded message ----------
Date: Wed, 9 Aug 2006 17:09:19 -0700 (PDT)
From: anil maran <anilmrn at yahoo.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] html file - construct attach send... email python

i wasnt able to find a useful way to construct email
i wasnt sure... abt how to use it
thanks for help


Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:

On Wed, 9 Aug 2006, anil maran wrote:

> What is the best way to construct an email in python and also attach a
> html file


Hi Anil,

This is a repeat of one of your previous questions; you just sent this
question out yesterday:

      http://mail.python.org/pipermail/tutor/2006-August/048452.html

We are forgetful, but we're not THAT senile yet.

Please do not repost your questions so early: give some people more time
to construct a good answer for you.  Repeating a question so soon like
this tends to demotivate people.


Have you looked at the 'email' module?

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

And in general, do you know about the Standard Library, or the Python
Cookbook?

      http://www.python.org/doc/lib/
      http://aspn.activestate.com/ASPN/Python/Cookbook/

I want to make sure you know about these documentation resources.


Good luck to you.



---------------------------------
Do you Yahoo!?
  Next-gen email? Have it all with the  all-new Yahoo! Mail Beta.

From hokkakada at khmeros.info  Thu Aug 10 03:11:05 2006
From: hokkakada at khmeros.info (kakada)
Date: Thu, 10 Aug 2006 08:11:05 +0700
Subject: [Tutor] python import problem
In-Reply-To: <003501c6bba5$3418db40$0201a8c0@XPpro>
References: <44D99E75.3010902@khmeros.info>
	<003501c6bba5$3418db40$0201a8c0@XPpro>
Message-ID: <44DA87A9.7040608@khmeros.info>

???????? Alan Gauld:
Hi Alan,
>> the folders modules and translate are in the same level, so if I want to
>> import factory.py into myfile.py, how can I do?
>
> You need to make your folders into packages.
> Its fairly simple, you basically create an init.py file
> But its worth reading about packages in the docs
> Come back here ifv you have any questions after that.
Sure, I can do it if I move translate folder into modules folder then
create an empty init.py file.
But I want another way, and PYTHONPATH is your right suggestion
>
> The other way would be to add each folder to
> your PYTHONPATH
It works for me now:

mport sys
import os.path
sys.path.append(os.path.join(sys.path[0] ,"translate"))



Cheers,
da

From jorge.castro at msn.com  Thu Aug 10 14:32:10 2006
From: jorge.castro at msn.com (Jorge De Castro)
Date: Thu, 10 Aug 2006 13:32:10 +0100
Subject: [Tutor] i18n Encoding/Decoding issues
Message-ID: <BAY5-F47A6D444C943E857BA744864A0@phx.gbl>

Hi all,

It seems I can't get rid of my continuous issues i18n with Python :(

I've been through:
http://docs.python.org/lib/module-email.Header.html
and
http://www.reportlab.com/i18n/python_unicode_tutorial.html
to no avail.

Basically, I'm receiving and processing mail that comes with content (from 
an utf-8 accepting form) from many locales (France, Germany, etc)

def splitMessage() does what the name indicates, and send message is the 
code below.

def sendMessage(text):
    to, From, subject, body = splitMessage(text)
    msg = MIMEText(decodeChars(body), 'plain', 'UTF-8')
    msg['From'] = From
    msg['To'] = to
    msg['Subject'] = Header(decodeChars(subject), 'UTF-8')

def decodeChars(str=""):
    if not str: return None
    for characterCode in _characterCodes.keys():
        str = str.replace(characterCode, _characterCodes[characterCode])
    return str

Now as you have noticed, this only works, ie, I get an email sent with the 
i18n characters displayed correctly, after I pretty much wrote my own 
'urldecode' map

_characterCodes ={  "%80" : "&#65533;", "%82" : "&#65533;", "%83" : 
"&#65533;", "%84" : "&#65533;", \
                    "%85" : "&#65533;", "%86" : "&#65533;",	"%87" : 
"&#65533;", "%88" : "&#65533;", \
                    "%89" : "&#65533;", "%8A" : "&#65533;", "%8B" : 
"&#65533;", "%8C" : "&#65533;", \
                    "%8E" : "&#65533;", "%91" : "&#65533;", "%92" : 
"&#65533;", "%93" : "&#65533;", \
                    "%94" : "&#65533;", "%95" : "&#65533;", "%96" : 
"&#65533;", "%97" : "&#65533;", \
...

Which feels like an horrible kludge.
Note that using urlilib.unquote doesn't do it -I get an error saying that it 
is unable to . Replacing my decodeChars

msg = MIMEText(urllib.unquote(body), 'plain', 'UTF-8')

Returns content with i18n characters mangled.

Using unicode(body, 'latin-1').encode('utf-8') doesn't work either. Besides, 
am I the only one to feel that if I want to encode something in UTF-8 it 
doesn't feel intuitive to have to convert to latin-1 first and then encode?

Any ideas? I am dry on other option and really don't want to keep my kludge 
(unless I absolutely have to)

Thanks in advance
Cheers
j

_________________________________________________________________
Download the new Windows Live Toolbar, including Desktop search! 
http://toolbar.live.com/?mkt=en-gb


From emilia12 at mail.bg  Thu Aug 10 15:47:43 2006
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Thu, 10 Aug 2006 16:47:43 +0300
Subject: [Tutor] [tutor] ipconfig
Message-ID: <1155217663.5c8b2b0d94a92@mail.bg>

hello list

is there in python an independent from the system way to
obtain the IP

i am playng around
<code>
import sys
import os
ipconfname={'nt':'ipconfig', 'posix':'ifconfig'}
ipstr = os.popen(ipconfname[os.name] ).read()
#print ipstr
</code>
but i found out that answer depends on os.name ...

in this case i have to use a different parser for each
system ... so is there another way to retrieve the IP?

regards,
e.

-----------------------------

http://www.atol.bg - ?????? ??????? ?? ????????? ? ????? ????????!


From jason.massey at gmail.com  Thu Aug 10 15:55:27 2006
From: jason.massey at gmail.com (Jason Massey)
Date: Thu, 10 Aug 2006 08:55:27 -0500
Subject: [Tutor] [tutor] ipconfig
In-Reply-To: <1155217663.5c8b2b0d94a92@mail.bg>
References: <1155217663.5c8b2b0d94a92@mail.bg>
Message-ID: <7e3eab2c0608100655w6e80c150q6b687fa09d3367e1@mail.gmail.com>

I found this on an artima forum:

http://www.artima.com/forums/flat.jsp?forum=181&thread=113874

This worked on my machine (win xp):

socket.getaddrinfo(socket.gethostname(), None)[0][4][0]

On 8/10/06, emilia12 at mail.bg <emilia12 at mail.bg> wrote:
>
> hello list
>
> is there in python an independent from the system way to
> obtain the IP
>
> i am playng around
> <code>
> import sys
> import os
> ipconfname={'nt':'ipconfig', 'posix':'ifconfig'}
> ipstr = os.popen(ipconfname[os.name] ).read()
> #print ipstr
> </code>
> but i found out that answer depends on os.name ...
>
> in this case i have to use a different parser for each
> system ... so is there another way to retrieve the IP?
>
> regards,
> e.
>
> -----------------------------
>
> http://www.atol.bg - ?????? ??????? ?? ????????? ? ????? ????????!
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060810/505c7deb/attachment.htm 

From mail at ozzmosis.com  Thu Aug 10 16:01:40 2006
From: mail at ozzmosis.com (andrew clarke)
Date: Fri, 11 Aug 2006 00:01:40 +1000
Subject: [Tutor] [tutor] ipconfig
In-Reply-To: <1155217663.5c8b2b0d94a92@mail.bg>
References: <1155217663.5c8b2b0d94a92@mail.bg>
Message-ID: <20060810140140.GA11356@ozzmosis.com>

On Thu, Aug 10, 2006 at 04:47:43PM +0300, emilia12 at mail.bg wrote:

> is there in python an independent from the system way to obtain the IP

>>> import socket
>>> hostname = socket.gethostname()
>>> ip = socket.gethostbyname(hostname)
>>> print ip
192.168.1.10

From amresh.kulkarni at gmail.com  Thu Aug 10 19:59:25 2006
From: amresh.kulkarni at gmail.com (Amresh Kulkarni)
Date: Thu, 10 Aug 2006 12:59:25 -0500
Subject: [Tutor] wx.Notebook query in wxpython
Message-ID: <da7927800608101059n219e3dd3ge366eea2e8320e97@mail.gmail.com>

Hi all,

I am developing a GUI which has a notebook with multiple tabs. The tabs are
formed by adding pages to the notebook.
I have a check menu to select/deselect the tabs(pages) i want. On checking
on an item it will must show the respective tab and unchecking should hide
it.

Simple as it may sound, i cant seem to find a hide method for notebook.
Like if i have tabs x, y, z and i have unchecked x item in menu. it will
trigger the foll  code

pageX = self.Notebook.GetPage(xid) --> xid is the id assigned to page x
xid.Show(False)

This does not work as there is no method show in Notebook. Is there a way to
make this work.

~~AMRESH~~
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060810/382e3b09/attachment.htm 

From amresh.kulkarni at gmail.com  Thu Aug 10 19:59:25 2006
From: amresh.kulkarni at gmail.com (Amresh Kulkarni)
Date: Thu, 10 Aug 2006 12:59:25 -0500
Subject: [Tutor] wx.Notebook query in wxpython
Message-ID: <da7927800608101059n219e3dd3ge366eea2e8320e97@mail.gmail.com>

Hi all,

I am developing a GUI which has a notebook with multiple tabs. The tabs are
formed by adding pages to the notebook.
I have a check menu to select/deselect the tabs(pages) i want. On checking
on an item it will must show the respective tab and unchecking should hide
it.

Simple as it may sound, i cant seem to find a hide method for notebook.
Like if i have tabs x, y, z and i have unchecked x item in menu. it will
trigger the foll  code

pageX = self.Notebook.GetPage(xid) --> xid is the id assigned to page x
xid.Show(False)

This does not work as there is no method show in Notebook. Is there a way to
make this work.

~~AMRESH~~
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060810/382e3b09/attachment.html 

From alan.gauld at freenet.co.uk  Thu Aug 10 20:57:29 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 10 Aug 2006 19:57:29 +0100
Subject: [Tutor] python import problem
References: <44D99E75.3010902@khmeros.info><003501c6bba5$3418db40$0201a8c0@XPpro>
	<44DA87A9.7040608@khmeros.info>
Message-ID: <001b01c6bcae$d461d2f0$0201a8c0@XPpro>

>> The other way would be to add each folder to
>> your PYTHONPATH
>It works for me now:

>import sys
>import os.path
>sys.path.append(os.path.join(sys.path[0] ,"translate"))

That isn't using PYTHONPATH its updaing sys.path 
which is slightly different.. This way you need to do that 
for every program usi9ng your folder but if you modify 
the PYTHONPATH environment variable you only need 
to do it once and Python will add it to sys.path for you.

HTH,

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

From klappnase at freenet.de  Thu Aug 10 21:27:30 2006
From: klappnase at freenet.de (Michael Lange)
Date: Thu, 10 Aug 2006 21:27:30 +0200
Subject: [Tutor] i18n Encoding/Decoding issues
In-Reply-To: <BAY5-F47A6D444C943E857BA744864A0@phx.gbl>
References: <BAY5-F47A6D444C943E857BA744864A0@phx.gbl>
Message-ID: <20060810212730.532e0560.klappnase@freenet.de>

Hi Jorge,


On Thu, 10 Aug 2006 13:32:10 +0100
"Jorge De Castro" <jorge.castro at msn.com> wrote:

(...)
> 
> Using unicode(body, 'latin-1').encode('utf-8') doesn't work either. Besides, 
> am I the only one to feel that if I want to encode something in UTF-8 it 
> doesn't feel intuitive to have to convert to latin-1 first and then encode?
> 

if the above does not work, it is because the original message is not
latin-1 encoded. unicode(body, 'latin-1') does not convert *to* latin-1, but
convert a latin-1 encoded string into unicode. This will obviously only work as
expected if the original string is actually latin-1.
In order to safely convert the message body into utf-8 you would have to find out
which encoding is used for the message and then do
    unicode(body, original_encoding).encode('utf-8')

Michael

From john at fouhy.net  Thu Aug 10 22:51:48 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 11 Aug 2006 08:51:48 +1200
Subject: [Tutor] wx.Notebook query in wxpython
In-Reply-To: <da7927800608101059n219e3dd3ge366eea2e8320e97@mail.gmail.com>
References: <da7927800608101059n219e3dd3ge366eea2e8320e97@mail.gmail.com>
Message-ID: <5e58f2e40608101351l1e78d262v9dea8dc9f5a492b2@mail.gmail.com>

On 11/08/06, Amresh Kulkarni <amresh.kulkarni at gmail.com> wrote:
> I am developing a GUI which has a notebook with multiple tabs. The tabs are
> formed by adding pages to the notebook.
> I have a check menu to select/deselect the tabs(pages) i want. On checking
> on an item it will must show the respective tab and unchecking should hide
> it.
[...]

Hi Amresh,

I suggest you try asking on the wxPython list,
wxPython-users at lists.wxwidgets.org  (you will probably have to
subscribe first).

The people on that list are both very knowledgable and very helpful :-)

-- 
John.

From anilmrn at yahoo.com  Thu Aug 10 23:14:23 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 10 Aug 2006 14:14:23 -0700 (PDT)
Subject: [Tutor] i18n Encoding/Decoding issues
In-Reply-To: <20060810212730.532e0560.klappnase@freenet.de>
Message-ID: <20060810211424.97519.qmail@web55902.mail.re3.yahoo.com>

how do u find out original encoding
thanks

Michael Lange <klappnase at freenet.de> wrote: Hi Jorge,


On Thu, 10 Aug 2006 13:32:10 +0100
"Jorge De Castro"  wrote:

(...)
> 
> Using unicode(body, 'latin-1').encode('utf-8') doesn't work either. Besides, 
> am I the only one to feel that if I want to encode something in UTF-8 it 
> doesn't feel intuitive to have to convert to latin-1 first and then encode?
> 

if the above does not work, it is because the original message is not
latin-1 encoded. unicode(body, 'latin-1') does not convert *to* latin-1, but
convert a latin-1 encoded string into unicode. This will obviously only work as
expected if the original string is actually latin-1.
In order to safely convert the message body into utf-8 you would have to find out
which encoding is used for the message and then do
    unicode(body, original_encoding).encode('utf-8')

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


 		
---------------------------------
How low will we go? Check out Yahoo! Messenger?s low  PC-to-Phone call rates.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060810/a9d85628/attachment.html 

From dyoo at hkn.eecs.berkeley.edu  Fri Aug 11 01:22:48 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 10 Aug 2006 16:22:48 -0700 (PDT)
Subject: [Tutor] i18n Encoding/Decoding issues
In-Reply-To: <20060810211424.97519.qmail@web55902.mail.re3.yahoo.com>
References: <20060810211424.97519.qmail@web55902.mail.re3.yahoo.com>
Message-ID: <Pine.LNX.4.64.0608101618460.11641@hkn.eecs.berkeley.edu>



On Thu, 10 Aug 2006, anil maran wrote:

> how do u find out original encoding

Read:

     http://www.joelonsoftware.com/articles/Unicode.html

In short: there's no good, reliable way to guess the encoding.  But there 
should be no need to guess:  a proper document will have the encoding 
explicitely written in there.

From cspears2002 at yahoo.com  Fri Aug 11 01:39:41 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 10 Aug 2006 16:39:41 -0700 (PDT)
Subject: [Tutor] Rock, Paper, Scissors
Message-ID: <20060810233941.76046.qmail@web51607.mail.yahoo.com>

Here is my Rock,Paper,Scissors script:

#!/usr/bin/python

import random
random.seed()

class Human:
	def __init__(self):
		self.points = 0
		self.choice = " "
		
	def plays(self):
		self.choice = raw_input("Pick (R)ock, (P)aper, or
(S)cissors! ")
		if self.choice == 'r':
			self.choice = 'rocks'
		elif self.choice == 'p':
			self.choice = 'paper'
		elif self.choice == 's':
			self.choice = 'scissors'
		else:
			print "Invalid response"
	
	

class Computer:
	def __init__(self):
		self.points = 0
		self.choice = " "
	
	def plays(self):
		comp_choice = random.randint(0,2)
		if comp_choice == 0:
			self.choice = 'rocks' #for rocks
		elif comp_choice == 1:
			self.choice = 'paper' #for paper
		else:
			self.choice = 'scissors' #for scissors
			
def compare_objects(human, computer):
	print "Human picked ", human.choice
	print "Computer picked", computer.choice
	if human.choice == computer.choice:
		print "Draw!"
	elif human.choice == 'rocks' and computer.choice ==
'paper':
		print "Computer wins!"
		computer.points = computer.points + 1
	elif human.choice == 'paper' and computer.choice ==
'rocks':
		print "Human wins!"
		human.points = human.points + 1
	elif human.choice == 'scissors' and computer.choice
== 'paper':
		print "Human wins!"
		human.points = human.points + 1
	elif human.choice == 'paper' and computer.choice ==
'scissors':
	 	print "Computer wins!"
		computer.points = computer.points + 1
	elif human.choice == 'rocks' and computer.choice ==
'scissors':
		print "Human wins!"
		human.points = human.points + 1
	else human.choice == 'scissors' and computer.choice
== 'rocks':
		print "Computer wins!"
		computer.points = computer.points + 1
		
if __name__ == "__main__":
	print "Welcome to Rock, Paper, Scissors!"
	final_points = raw_input("Play to how many points? ")
	human = Human()
	computer = Computer()
	while (human.points <= final_points or
computer.points <= final_points):
		human.plays()
		computer.plays()
		compare_objects(human, computer)
		print "Score:\tHuman: ",human.points,"\tComputer:
",computer.points
	
	
My main concern is the compare_objects function.  Is
there any easier way to write it?  Actually, the
function does not work because "else condition:"
causes a syntax error.

-Chris

From john at fouhy.net  Fri Aug 11 02:02:50 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 11 Aug 2006 12:02:50 +1200
Subject: [Tutor] Rock, Paper, Scissors
In-Reply-To: <20060810233941.76046.qmail@web51607.mail.yahoo.com>
References: <20060810233941.76046.qmail@web51607.mail.yahoo.com>
Message-ID: <5e58f2e40608101702n699ce81l390a0599a363918@mail.gmail.com>

Hi Chris,

On 11/08/06, Christopher Spears <cspears2002 at yahoo.com> wrote:
>        def plays(self):
>                self.choice = raw_input("Pick (R)ock, (P)aper, or
> (S)cissors! ")
>                if self.choice == 'r':
>                        self.choice = 'rocks'
>                elif self.choice == 'p':
>                        self.choice = 'paper'
>                elif self.choice == 's':
>                        self.choice = 'scissors'
>                else:
>                        print "Invalid response"

A couple of comments here ---

Firstly, to me, 'self.choice' is the thing you want to save, which is
distinct from the user's input.  So, I would call the result of
raw_input something else.  eg:

    fromUser = raw_input("Pick (R)ock, (P)aper, or
(S)cissors! ")
    if fromUser == 'r':
        self.choice = 'rocks'
    # etc

Secondly, if the user enters 'R' (as you request), your program will
say "Invalid response", because 'R' != 'r'.  You can get around this
by saying:

    if fromUser.lower() == 'r':

Thirdly, a dictionary would make this much simpler.  Something like:

    translate = { 'r':'rock', 's':'scissors', 'p':'paper' }
    try:
        self.choice = translate[fromUser.lower()]
    except KeyError:
        print 'Invalid response.'
        # what else are you going to do?  what does self.choice become?

> def compare_objects(human, computer):
>        print "Human picked ", human.choice
>        print "Computer picked", computer.choice
>        if human.choice == computer.choice:
>                print "Draw!"
>        elif human.choice == 'rocks' and computer.choice ==
> 'paper':
>                print "Computer wins!"
>                computer.points = computer.points + 1
[...]

You can use a similar dictionary-based approach here.  You could use a
dictionary to make a data structure that expresses what beats what,
and then reduce your code to:

    if human.choice == computer.choice:
        print 'Draw!'
    elif # human beats computer
        print 'Human wins!'
    else:
        print 'Computer wins!'

HTH :-)

-- 
John.

From alan.gauld at freenet.co.uk  Fri Aug 11 12:13:26 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 11 Aug 2006 11:13:26 +0100
Subject: [Tutor] Rock, Paper, Scissors
References: <20060810233941.76046.qmail@web51607.mail.yahoo.com>
Message-ID: <000a01c6bd2e$c9ab9b90$0201a8c0@XPpro>

> My main concern is the compare_objects function.  Is
> there any easier way to write it?  Actually, the
> function does not work because "else condition:"
> causes a syntax error.

I'd do that with a two dimernsional table.
The table would be indexed by the computers choice and 
the human choice and the outcome stored as a value.

Thus it becomes

outcome = results[computer.choice][human.choice]
if outcome == 0: print "Computer Wins"
elif outcome == 1: print "Human wins"
else: print 'Draw!'

Another interesting variation is to create a single 
Player class and make human and computer instances.
Pass in the function for setting choice as a 
parameter to init...  That way your code 
consists of a Player class, two selection functions
and the lookup/display code that could sit in main()
This isn't any "better", as such, just different...

HTH,

Alan G.

From peppers at gmail.com  Fri Aug 11 16:26:09 2006
From: peppers at gmail.com (Terry Peppers)
Date: Fri, 11 Aug 2006 09:26:09 -0500
Subject: [Tutor] Python Block
Message-ID: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com>

I'm really blocked right now, and I don't want to post this to the
main Python list since I think the answer is probably right in front
of my face. I'm clearly just too close to see it.

I'm able to do frequency counts of items in a list by doing the following:

>>> list = ["5100", "5100", "5100", "5200", "5200"]
>>> count = {}
>>> for l in list:
...     count[l] = count.get(l, 0) + 1
...
>>> count
{'5200': 2, '5100': 3}
>>>

Hooray, right?! However, my real problem is dealing with another
dimension of data. So suppose I can access the following data:

"5100", "foo"
"5100", "-"
"5100", "-"
"5100", "-"
"5200", "foo"
"5200", -

That's a total of 6  line records that I want to output like this:

5100        -         3
5100       foo      1
5200       -          1
5200       foo      1

I want to count the frequency of the second column of data that I can
access. I can't seem to get any traction as how to figure this out.
Should I put the data in a list of dictionaries? A dictionary of
lists? How do I call the data if there are all kinds of duplicate
keys? When the data's in some data structure how do I iterate over it
to get frequency of column B?

Really confused. Can someone help?

From wierob at gmx.de  Fri Aug 11 18:28:58 2006
From: wierob at gmx.de (Robert Wierschke)
Date: Fri, 11 Aug 2006 18:28:58 +0200
Subject: [Tutor] Rock, Paper, Scissors
Message-ID: <44DCB04A.2020202@gmx.de>

the else part can't have a condition!!!

From rabidpoobear at gmail.com  Fri Aug 11 18:53:12 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 11 Aug 2006 11:53:12 -0500
Subject: [Tutor] Rock, Paper, Scissors
In-Reply-To: <44DCB04A.2020202@gmx.de>
References: <44DCB04A.2020202@gmx.de>
Message-ID: <44DCB5F8.4080303@gmail.com>

Robert Wierschke wrote:
> the else part can't have a condition!!!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   
Are you referring to Alan's post?
You should have included the original text in your reply so we would 
know what you're talking about.
If  you _are_ talking about Alan's example:
#---

outcome = results[computer.choice][human.choice]
if outcome == 0: print "Computer Wins"
elif outcome == 1: print "Human wins"
else: print 'Draw!'
#---
his else doesn't have a condition.
it's just that he only needed to do one thing in the else clause
and it looks neater to put it on one line.
else: print 'Draw!'
is equivalent to
else:
	print 'Draw!'


From wescpy at gmail.com  Fri Aug 11 19:42:32 2006
From: wescpy at gmail.com (wesley chun)
Date: Fri, 11 Aug 2006 10:42:32 -0700
Subject: [Tutor] Rock, Paper, Scissors
In-Reply-To: <001b01c6bb0c$37df2390$0201a8c0@XPpro>
References: <20060808054246.54903.qmail@web51606.mail.yahoo.com>
	<001b01c6bb0c$37df2390$0201a8c0@XPpro>
Message-ID: <78b3a9580608111042j255857c9j120963c69e089a94@mail.gmail.com>

> This looks like a fun project to work on.  From
> reading the description, I feel this would be pretty
> straight forward game to program.  However, I have no
> idea how the computer would decide if it wanted a
> rock, paper, or a pair of scissors.  Any hints?


christopher,

this is indeed a *great* exercise... i've been using it since i can't
remember when... i had it as an exercise in BASIC and Pascal when i
was in high school, then turned it into an exercise for my C and
Python courses.  naturally it's also in Core Python.

others have said it and given code already, but this problem breaks
down into 3 discrete steps:

1. give values to R, P or S, i.e., an int, char, or some constant
2. have the user choose one via its constant
3. have the computer choose another -- you will need to randomly pick
one of the 3 constants
4. logic to determine who the "winner" is of if it is a draw

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

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

From wescpy at gmail.com  Fri Aug 11 19:47:37 2006
From: wescpy at gmail.com (wesley chun)
Date: Fri, 11 Aug 2006 10:47:37 -0700
Subject: [Tutor] Python Block
In-Reply-To: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com>
References: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com>
Message-ID: <78b3a9580608111047u15201a79x7bc5f334be9262e7@mail.gmail.com>

On 8/11/06, Terry Peppers <peppers at gmail.com> wrote:
> I'm really blocked right now, and I don't want to post this to the
> main Python list since I think the answer is probably right in front
> of my face. I'm clearly just too close to see it.
>
> "5100", "foo"
> "5100", "-"
> "5100", "-"
> "5100", "-"
> "5200", "foo"
> "5200", -
>
> That's a total of 6  line records that I want to output like this:
>
> 5100        -         3
> 5100       foo      1
> 5200       -          1
> 5200       foo      1
>
> I want to count the frequency of the second column of data that I can
> access. I can't seem to get any traction as how to figure this out.
> Should I put the data in a list of dictionaries? A dictionary of
> lists? How do I call the data if there are all kinds of duplicate
> keys? When the data's in some data structure how do I iterate over it
> to get frequency of column B?


without hacking any code... i can see two possibilities you can try:

1) easiest.  use a tuple of pairs as your key, i.e. (5100, 'foo'),
(5100, '-'), etc.  it's only confusing because you're seeing "5100" in
both keys

2) more complex.  you suggested a list of dicts or a dict of lists,
but it looks like a dict of dicts would be a better fit., i.e. {5100:
{'foo': 1, '-': 3}, etc.

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

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

From cspears2002 at yahoo.com  Sat Aug 12 00:39:21 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Fri, 11 Aug 2006 15:39:21 -0700 (PDT)
Subject: [Tutor] rock, paper, scissors
In-Reply-To: <BAY15-F164C875CE212CDDD382789964B0@phx.gbl>
Message-ID: <20060811223921.94136.qmail@web51614.mail.yahoo.com>

--- Tom Wilson <tpwilson at hotmail.co.uk> wrote:

> hi,
> 
> could you please explain to me how your rock paper
> scissors game script 
> works because i am a bit confused.
> 
> thanks
> tom
> 
> 

The game does not work in its current form, which may
be some cause for confusion.  :-)

In designing the program, I took the object oriented
route.  Why?  When I started to design the game, I
imagined two characters (a human and a computer)
playing against each other.  Each character has
similar attributes, i.e. points and a choice, and
behavoir.  They play.  The behavoir is implemented
differently for each character because how a computer
makes a decision is different from how a human makes a
decision.

After the characters decide which object to pick, a
function called compare_objects compares the objects
and uses logic to determine the winner.  After the
winner is picked, points are incremented and play
continues until one character reaches a set number of
points.

The two problem areas are the compare_objects function
and the while loop.  They don't work.  (At least, not
well.)  However, I have gotten several useful tips
from tutors, so I will be making a lot of progress
next week!


-Chris



From ismaelgf at adinet.com.uy  Sat Aug 12 08:05:10 2006
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Sat, 12 Aug 2006 03:05:10 -0300
Subject: [Tutor] Rock, Paper, Scissors
In-Reply-To: <44DCB5F8.4080303@gmail.com>
References: <44DCB04A.2020202@gmx.de> <44DCB5F8.4080303@gmail.com>
Message-ID: <44DD6F96.2050009@adinet.com.uy>

Luke Paireepinart escribi?:
> Robert Wierschke wrote:
>   
>> the else part can't have a condition!!!
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>   
>>     
> Are you referring to Alan's post?
> You should have included the original text in your reply so we would 
> know what you're talking about.
He wasn't. From the original post:

	elif human.choice == 'rocks' and computer.choice ==
'scissors':
		print "Human wins!"
		human.points = human.points + 1
	else human.choice == 'scissors' and computer.choice
== 'rocks':
		print "Computer wins!"
		computer.points = computer.points + 1



Ismael

From rabidpoobear at gmail.com  Sat Aug 12 08:10:23 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sat, 12 Aug 2006 01:10:23 -0500
Subject: [Tutor] Rock, Paper, Scissors
In-Reply-To: <44DD6F96.2050009@adinet.com.uy>
References: <44DCB04A.2020202@gmx.de> <44DCB5F8.4080303@gmail.com>
	<44DD6F96.2050009@adinet.com.uy>
Message-ID: <44DD70CF.9050702@gmail.com>

....
> He wasn't. From the original post:
>
> 	elif human.choice == 'rocks' and computer.choice ==
> 'scissors':
> 		print "Human wins!"
> 		human.points = human.points + 1
> 	else human.choice == 'scissors' and computer.choice
> == 'rocks':
> 		print "Computer wins!"
> 		computer.points = computer.points + 1
>
>
>   
ah.
thanks for clearing this up.

From nimrodx at slingshot.co.nz  Sat Aug 12 14:03:54 2006
From: nimrodx at slingshot.co.nz (nimrodx)
Date: Sat, 12 Aug 2006 22:03:54 +1000
Subject: [Tutor] regular expressions question
Message-ID: <44DDC3AA.8010908@slingshot.co.nz>

Hi All,

I am trying to fish through the history file for the Konquerer web 
browser, and pull out the
web sites visited.

The file's encoding is binary or something

Here is the first section of the file:
'\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l' 


Does that tell you anything?

I have been trying to replace the pesky \x00's with something less 
annoying, but
with no success:
   import re
   pattern = r"\x00"
   re.sub(pattern, '', dat2)

That seems to work at the command line, but this this:

   web = re.compile(
                    r"(?P<addr>[/a-zA-Z0-9\.]+)"
                    )
   res = re.findall(web,dat2)
tends to give me back individual alphanumeric characters, "."'s, and "/"'s,
as if they had each been separated by an unmatched character:
e.g. ['z', 't', 'f', 'i', 'l', 'e', 'h', 'o', 'm', 'e', 'a', 'l', 'p', 
'h', 'a',...]

I was hoping for one web address per element of the list...

Suggestions greatly appreciated!!

Thanks,

Matt

From nimrodx at slingshot.co.nz  Sat Aug 12 14:07:57 2006
From: nimrodx at slingshot.co.nz (nimrodx)
Date: Sat, 12 Aug 2006 22:07:57 +1000
Subject: [Tutor] Message seemed to bounce, so I will try again
Message-ID: <44DDC49D.2010009@slingshot.co.nz>

Hi All,

I am trying to fish through the history file for the Konquerer web 
browser, and pull out the
web sites visited.

The file's encoding is binary or something

Here is the first section of the file:
'\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l' 


Does that tell you anything?

I have been trying to replace the pesky \x00's with something less 
annoying, but
with no success:
  import re
  pattern = r"\x00"
  re.sub(pattern, '', dat2)

That seems to work at the command line, but this this:

  web = re.compile(
                   r"(?P<addr>[/a-zA-Z0-9\.]+)"
                   )
  res = re.findall(web,dat2)
tends to give me back individual alphanumeric characters, "."'s, and "/"'s,
as if they had each been separated by an unmatched character:
e.g. ['z', 't', 'f', 'i', 'l', 'e', 'h', 'o', 'm', 'e', 'a', 'l', 'p', 
'h', 'a',...]

I was hoping for one web address per element of the list...

Suggestions greatly appreciated!!

Thanks,

Matt


From anilmrn at yahoo.com  Sat Aug 12 11:14:31 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sat, 12 Aug 2006 02:14:31 -0700 (PDT)
Subject: [Tutor] how to remove html ags
Message-ID: <20060812091431.74868.qmail@web55905.mail.re3.yahoo.com>

<p><div class="quote">Human nature is not a machin...

for example in the above stirng 

i want to remove <p>
and <div class="quote">

i tried

str = str.replace('(.*)','')

it doesnt work
thanks

 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060812/3f253d02/attachment.html 

From alan.gauld at freenet.co.uk  Sat Aug 12 11:23:38 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 12 Aug 2006 10:23:38 +0100
Subject: [Tutor] Python Block
References: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com>
Message-ID: <001601c6bdf1$02244fe0$0201a8c0@XPpro>

> Hooray, right?! However, my real problem is dealing with another
> dimension of data. So suppose I can access the following data:
> 
> "5100", "foo"
> "5100", "-"
> "5100", "-"
> "5100", "-"
> "5200", "foo"
> "5200", -

Hint: Dictionaries can be keyed by tuples too.
 
>( 5100,  -)  :  3

Does that help?

Alan G.

From alan.gauld at freenet.co.uk  Sat Aug 12 11:33:32 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 12 Aug 2006 10:33:32 +0100
Subject: [Tutor] regular expressions question
References: <44DDC3AA.8010908@slingshot.co.nz>
Message-ID: <002a01c6bdf2$60c69480$0201a8c0@XPpro>

> The file's encoding is binary or something
>
> Here is the first section of the file:
> '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l'
>
> Does that tell you anything?

Recall that on a 32 bit computer each "word" is 4 bytes long
so to get anyting meaningful you often need to consider 4 byte
blocks.

00000002
B8089F00
The next bit is tricky, either 'z' or

(ord('z')A80000

etc.

Now whether those numbers mean anything to you is a moot
point but thats usually the starting point.

> I have been trying to replace the pesky \x00's with something less

But that is almost certainly the wrong approach, you'll never
figure out where the word boundaries are without them!

> Suggestions greatly appreciated!!

Go look on the Konqueror site (at the code if necessary) to find the
format of the data structure in the file and use the struct module
to unpack it.

You might find the section in my tutorial (under Handling Files)
on binary files and using struct useful

HTH

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


From wierob at gmx.de  Sat Aug 12 12:06:56 2006
From: wierob at gmx.de (Robert Wierschke)
Date: Sat, 12 Aug 2006 12:06:56 +0200
Subject: [Tutor] Rock, Paper, Scissors
In-Reply-To: <44DCB5F8.4080303@gmail.com>
References: <44DCB04A.2020202@gmx.de> <44DCB5F8.4080303@gmail.com>
Message-ID: <44DDA840.4050602@gmx.de>

sorry I answerd to

Message: 2
Date: Thu, 10 Aug 2006 16:39:41 -0700 (PDT)
From: Christopher Spears <cspears2002 at yahoo.com>
Subject: [Tutor] Rock, Paper, Scissors


and his else has a condition

>    else human.choice == 'scissors' and computer.choice
>== 'rocks':
>        print "Computer wins!"
>        computer.points = computer.points + 1



Luke Paireepinart schrieb:
> Robert Wierschke wrote:
>> the else part can't have a condition!!!
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>   
> Are you referring to Alan's post?
> You should have included the original text in your reply so we would
> know what you're talking about.
> If  you _are_ talking about Alan's example:
> #---
>
> outcome = results[computer.choice][human.choice]
> if outcome == 0: print "Computer Wins"
> elif outcome == 1: print "Human wins"
> else: print 'Draw!'
> #---
> his else doesn't have a condition.
> it's just that he only needed to do one thing in the else clause
> and it looks neater to put it on one line.
> else: print 'Draw!'
> is equivalent to
> else:
>     print 'Draw!'
>
>


From nimrodx at slingshot.co.nz  Sat Aug 12 16:30:34 2006
From: nimrodx at slingshot.co.nz (nimrodx)
Date: Sun, 13 Aug 2006 00:30:34 +1000
Subject: [Tutor] regular expressions question]
Message-ID: <44DDE60A.60602@slingshot.co.nz>

Hi Alan and other Gurus,

if you look carefully at the string below, you see
that in amongst the "\x" stuff you have the text I want:
z tfile://home/alpha
which I know to be an address on my system, plus a bit of preceeding txt.
Alan Gauld wrote:
>> The file's encoding is binary or something
>>
>> Here is the first section of the file:
>> '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l' 
>>
>>
>> Does that tell you anything?
> But that is almost certainly the wrong approach, you'll never
> figure out where the word boundaries are without them!
So I believe this is the right approach. in fact, If I print the string, 
without any modifications:
I get the following sort of stuff:
?z???tfile:/home/alpha/care/my_details.aspx.html????????%o??0%o??0l

So this is one approach that will work.
I have no idea what sort of encoding it is, but if someone could tell me 
how to get rid of what I assume are hex digits.
In a hex editor it turns out to be readable and sensible url's with 
spaces between each digit, and a bit of crud at the end of url's, just 
as above.

Any suggestions with that additional info?
I've used struct before, it is a very nice module. Could  this be some 
sort of UTF encoding?

I think I was a bit light on info with that first post.
Thanks for your time,

Matt






From bashu at yandex.ru  Sat Aug 12 13:28:18 2006
From: bashu at yandex.ru (Basil Shubin)
Date: Sat, 12 Aug 2006 18:28:18 +0700
Subject: [Tutor] SGMLLib, fetching some weird data
Message-ID: <44DDBB52.5080906@yandex.ru>

Hi friends,

Please, examine attached script. I want fetch some data from online 
resource and almost achieve this, but I can't fetch some weird formatted 
data like this '45? Reverse Calf Press'. I got the following error:

45
  Reverse Calf Press
Reverse Calf Raise
Seated Reverse Calf Press
Traceback (most recent call last):
   File "net_exrx.py", line 226, in ?
     exercisesList = LoadExercisesList(2, 4, 9)
   File "net_exrx.py", line 86, in LoadExercisesList
     return parser.GetExercisesList()
   File "net_exrx.py", line 176, in GetExercisesList
     self.exerList.append([self.desc[i],self.urls[i]])
IndexError: list index out of range

Thanks in advance!
-------------- next part --------------
A non-text attachment was scrubbed...
Name: net_exrx.py
Type: text/x-python
Size: 7295 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060812/93bb7270/attachment.py 

From amonroe at columbus.rr.com  Sat Aug 12 13:54:14 2006
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sat, 12 Aug 2006 07:54:14 -0400
Subject: [Tutor] Python Block
In-Reply-To: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com>
References: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com>
Message-ID: <681067593618.20060812075414@columbus.rr.com>


> 5100        -         3
> 5100       foo      1
> 5200       -          1
> 5200       foo      1

> I want to count the frequency of the second column of data that I can
> access.

It's kind of the long way around, but putting it into a sql database
and doing a groupby query might work.

Alan


From tpwilson at hotmail.co.uk  Fri Aug 11 22:06:22 2006
From: tpwilson at hotmail.co.uk (Tom Wilson)
Date: Fri, 11 Aug 2006 21:06:22 +0100
Subject: [Tutor] Roack, Paper Scissors
Message-ID: <BAY15-F55C6ED3BA895120BEADBC964B0@phx.gbl>

could someone please explain to me how the scripts for the rock, paper, 
scissors game work because i'm not quite sure.

tom

_________________________________________________________________
Windows Live™ Messenger has arrived. Click here to download it for free! 
http://imagine-msn.com/messenger/launch80/?locale=en-gb


From foxandxss at gmail.com  Sat Aug 12 19:00:29 2006
From: foxandxss at gmail.com (Jesus Rodriguez)
Date: Sat, 12 Aug 2006 19:00:29 +0200
Subject: [Tutor] Rock, Paper, Scissors
In-Reply-To: <78b3a9580608111042j255857c9j120963c69e089a94@mail.gmail.com>
References: <20060808054246.54903.qmail@web51606.mail.yahoo.com>
	<001b01c6bb0c$37df2390$0201a8c0@XPpro>
	<78b3a9580608111042j255857c9j120963c69e089a94@mail.gmail.com>
Message-ID: <2a1edb210608121000ube3972fja3f1913ed1e3c836@mail.gmail.com>

Hi, i used a list with R, P, S like:

rps = ["Rock", "Paper", "Scissors"]
random.shuffle(rps)
computerObject = rps[0]

Then, the computer pick a random object and i compare my object with
computer's object.

;)

2006/8/11, wesley chun <wescpy at gmail.com>:
>
> > This looks like a fun project to work on.  From
> > reading the description, I feel this would be pretty
> > straight forward game to program.  However, I have no
> > idea how the computer would decide if it wanted a
> > rock, paper, or a pair of scissors.  Any hints?
>
>
> christopher,
>
> this is indeed a *great* exercise... i've been using it since i can't
> remember when... i had it as an exercise in BASIC and Pascal when i
> was in high school, then turned it into an exercise for my C and
> Python courses.  naturally it's also in Core Python.
>
> others have said it and given code already, but this problem breaks
> down into 3 discrete steps:
>
> 1. give values to R, P or S, i.e., an int, char, or some constant
> 2. have the user choose one via its constant
> 3. have the computer choose another -- you will need to randomly pick
> one of the 3 constants
> 4. logic to determine who the "winner" is of if it is a draw
>
> good luck!
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>     http://corepython.com
>
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060812/dd3294d1/attachment.htm 

From simplebob at gmail.com  Sat Aug 12 23:07:28 2006
From: simplebob at gmail.com (Daniel McQuay)
Date: Sat, 12 Aug 2006 17:07:28 -0400
Subject: [Tutor] how to remove html ags
In-Reply-To: <20060812091431.74868.qmail@web55905.mail.re3.yahoo.com>
References: <20060812091431.74868.qmail@web55905.mail.re3.yahoo.com>
Message-ID: <6d87ecf40608121407p5e3f1546ie40da7dbc915e037@mail.gmail.com>

hey anil,

have you had a look at BeautifulSoup?
http://www.crummy.com/software/BeautifulSoup/

i haven't used it but i have seen it mentioned on the list for parsing html.

On 8/12/06, anil maran <anilmrn at yahoo.com> wrote:
>
> <p><div class="quote">Human nature is not a machin...<http://feeds.feedburner.com/Caterinanet?m=1228>
>
> for example in the above stirng
>
> i want to remove <p>
> and <div class="quote">
>
> i tried
>
> str = str.replace('(.*)','')
>
> it doesnt work
> thanks
>
> ------------------------------
> Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates
> starting at 1?/min.
> <http://us.rd.yahoo.com/mail_us/taglines/postman7/*http://us.rd.yahoo.com/evt=39666/*http://messenger.yahoo.com>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
Daniel McQuay
simplebob at gmail.com
boxster.homelinux.org
prowiseguys.com
H: 814.825.0847
M: 814-341-6233
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060812/0e50bb5b/attachment.html 

From lavendula6654 at yahoo.com  Sun Aug 13 00:09:21 2006
From: lavendula6654 at yahoo.com (Elaine)
Date: Sat, 12 Aug 2006 15:09:21 -0700 (PDT)
Subject: [Tutor] How to teach Python
In-Reply-To: <44C0EF6F.7070907@gmail.com>
Message-ID: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com>

I am going to be teaching "Introduction to Python
Programming" in the Fall at Foothill College in Los
Altos Hills, CA. This is a 5 quarter unit class for
students who already know one programming language.

I have been teaching programming for 20 years now,
including Java and C++ as of late. As I prepare this
class, I have some questions that I I am hoping you
can shed some light on.

1) Programming Style 

         while 1:
              x = next()
              if not x: break

I have never allowed students to use break or continue
in any 
programming class I have taught. I think of this type
of code as belonging with the dreaded GOTO.

I find that students who are having difficulty writing

complex conditions in a loop use multiple if's with
break's 
inside the loop instead. Also, it is MUCH easier to
read a 
loop if the condition for continuing in the loop is
right up 
at the top of the loop where it belongs.

I have always thought of break and continue as hacks
that 
are not compatible with structured programming
techniques. 
The only exception is using break in a switch in C,
C++ and 
Java.

However, all Python books seem to contain sample
programs like this one. Do you think that code like
this is desirable?

2) Since this is an introductory class, I am tempted
to leave out "optional" topics like argument matching
modes, walk, map, filter, reduce, apply. Do you think
these are required for any Python programmer?

3) I need to teach a GUI in this class. I would like
something that is easy, standard, and multi-platform.
I am considering Tkinter and Jython. Any opnions on
this?

Thanks for any answers you might have.

-Elaine Haight



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

From kermit at polaris.net  Sun Aug 13 01:40:58 2006
From: kermit at polaris.net (Kermit Rose)
Date: Sat, 12 Aug 2006 19:40:58 -0400 (Eastern Daylight Time)
Subject: [Tutor] function value
Message-ID: <44DE670A.000005.02128@YOUR-4105E587B6>

 
A function in my factor package 
return zeros instead of the correct value.
 
    It did this for several times, and then returned the correct value.
 
    I inserted print statements in the function and in the calling routine
    which document this behavior.
 
    The calling routine is function function  fermat.
 
    The function being called is function strongfac.
 
    To see the test results , run the function testrange
    with parameters
    testrange(10**14+37,10**14+37).
 
    Since it takes quite a lot of work to make a copy that survives the
email
    removal of leading blanks
    I attach the package of function routines here.
 
 
Results as run on my machine:
 
Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license()" for more information.

 
 
IDLE 1.1.2      
>>> import factor34
>>> from factor34 import testrange
>>> testrange(10**14+37,10**14+37)
 Begin calculating constants to be used in factoring.
 Finished calculating constants to be used in factoring.
 
 Search for a factor of  100000000000037
 
 Could not find factors by strong probable prime test using witnesses <
10000.
 
 Try to find factors by using power of  2  mod z as a witness.
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  0  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  1  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  2  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  3  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  4  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  5  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  6  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  7  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  8  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  9  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  10  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  11  x =  0  y =  0  face =  [0, 0, 0]
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  12  x =  0  y =  0  face =  [0, 0, 0]
 
 In strongfac 
 Found1: x =  53799857
 Found1: y =  1858741
 face =  [53799857L, 1858741L, 0]
 Found1: factor by strong probable prime test, using witnes  15306543515214 
.
 Found1: factors are  53799857 1858741
 Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  13  x =  0  y =  0  face =  [0, 0, 0]
 
 In strongfac 
 Found1: x =  53799857
 Found1: y =  1858741
 face =  [53799857L, 1858741L, 0]
 Found1: factor by strong probable prime test, using witnes  12123044576953 
.
 Found1: factors are  53799857 1858741
 Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  14  x =  0  y =  0  face =  [0, 0, 0]
 
 In strongfac 
 Found1: x =  53799857
 Found1: y =  1858741
 face =  [53799857L, 1858741L, 0]
 Found1: factor by strong probable prime test, using witnes  45391315949900 
.
 Found1: factors are  53799857 1858741
 Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  15  x =  0  y =  0  face =  [0, 0, 0]
 
 In strongfac 
 Found1: x =  53799857
 Found1: y =  1858741
 face =  [53799857L, 1858741L, 0]
 Found1: factor by strong probable prime test, using witnes  59571344259390 
.
 Found1: factors are  53799857 1858741
 Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  16  x =  0  y =  0  face =  [0, 0, 0]
 
 In strongfac 
 Found1: x =  53799857
 Found1: y =  1858741
 face =  [53799857L, 1858741L, 0]
 Found1: factor by strong probable prime test, using witnes  78029752396948 
.
 Found1: factors are  53799857 1858741
 Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  17  x =  0  y =  0  face =  [0, 0, 0]
 
 In strongfac 
 Found1: x =  53799857
 Found1: y =  1858741
 face =  [53799857L, 1858741L, 0]
 Found1: factor by strong probable prime test, using witnes  35863146075772 
.
 Found1: factors are  53799857 1858741
 Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  18  x =  0  y =  0  face =  [0, 0, 0]
 
 In strongfac 
 Found1: x =  53799857
 Found1: y =  1858741
 face =  [53799857L, 1858741L, 0]
 Found1: factor by strong probable prime test, using witnes  19712913203085 
.
 Found1: factors are  53799857 1858741
 Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  19  x =  0  y =  0  face =  [0, 0, 0]
 
 In strongfac 
 Found1: x =  53799857
 Found1: y =  1858741
 face =  [53799857L, 1858741L, 0]
 Found1: factor by strong probable prime test, using witnes  14607414373499 
.
 Found1: factors are  53799857 1858741
 Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  20  x =  0  y =  0  face =  [0, 0, 0]
 
 In strongfac 
 Found1: x =  53799857
 Found1: y =  1858741
 face =  [53799857L, 1858741L, 0]
 Found1: factor by strong probable prime test, using witnes  57761947468766 
.
 Found1: factors are  53799857 1858741
 Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  21  x =  0  y =  0  face =  [0, 0, 0]
 
 In strongfac 
 Found1: x =  53799857
 Found1: y =  1858741
 face =  [53799857L, 1858741L, 0]
 Found1: factor by strong probable prime test, using witnes  75604347243674 
.
 Found1: factors are  53799857 1858741
 Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 Retrieved from strongfac, face =  [0, 0, 0]
 In fermat: k =  22  x =  0  y =  0  face =  [0, 0, 0]
 
 In strongfac 
 Found1: x =  53799857
 Found1: y =  1858741
 face =  [53799857L, 1858741L, 0]
 Found1: factor by strong probable prime test, using witnes  3561873332543  

 Found1: factors are  53799857 1858741
 Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 
 In strongfac 
 Found1: x =  1858741
 Found1: y =  53799857
 face =  [1858741L, 53799857L, 0]
 Found1: factor by strong probable prime test, using witnes  96058894729069 
.
 Found1: factors are  1858741 53799857
 Found1: returning  [1858741L, 53799857L, 0]  to fermat routine.
 Retrieved from strongfac, face =  [1858741L, 53799857L, 0]
 In fermat: k =  23  x =  1858741  y =  53799857  face =  [1858741L,
53799857L, 0]
 index of torial is  23
 z =  100000000000037  x =  1858741  y =  53799857  difficulty =  0
>>> 
 
 
 
    Kermit Rose   <  kermit at polaris.net  >
 
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: not available
Url: http://mail.python.org/pipermail/tutor/attachments/20060812/70aca486/attachment-0001.asc 

From python at venix.com  Sun Aug 13 01:56:04 2006
From: python at venix.com (Python)
Date: Sat, 12 Aug 2006 19:56:04 -0400
Subject: [Tutor] How to teach Python
In-Reply-To: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com>
References: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com>
Message-ID: <1155426964.5685.101.camel@www.venix.com>

On Sat, 2006-08-12 at 15:09 -0700, Elaine wrote:
> I am going to be teaching "Introduction to Python
> Programming" in the Fall at Foothill College in Los
> Altos Hills, CA. This is a 5 quarter unit class for
> students who already know one programming language.
> 
> I have been teaching programming for 20 years now,
> including Java and C++ as of late. As I prepare this
> class, I have some questions that I I am hoping you
> can shed some light on.
> 
> 1) Programming Style 
> 
>          while 1:
>               x = next()
>               if not x: break
> 
> I have never allowed students to use break or continue
> in any 
> programming class I have taught. I think of this type
> of code as belonging with the dreaded GOTO.
> 
> I find that students who are having difficulty writing
> 
> complex conditions in a loop use multiple if's with
> break's 
> inside the loop instead. Also, it is MUCH easier to
> read a 
> loop if the condition for continuing in the loop is
> right up 
> at the top of the loop where it belongs.
> 
> I have always thought of break and continue as hacks
> that 
> are not compatible with structured programming
> techniques. 
> The only exception is using break in a switch in C,
> C++ and 
> Java.
> 
> However, all Python books seem to contain sample
> programs like this one. Do you think that code like
> this is desirable?

YES.

In C you can code
	while ((c = getchar()) != EOF)
	<loop body>
which combines the assignment and the conditional

The equivalent Python code is something like:
	c = getchar()
	while c != EOF:
	<loop body>
	c = getchar()

Because the assignment is a separate statement and not an expression, it
cannot be combined with the condition.  So the Python consensus seems to
be that you are better of with one assignment and embed the condition
with a break at the proper spot within the loop.  The loop is simply
	while True:	# with newer Pythons
		c = getchar(1)
		if c == EOF: break
		<loop body>

In translating from other languages, note that many while loops can
become for loops in Python.  The while loop above came from K&R page 17,
	(The C Programming Language, Kernighan and Ritchie)
counting lines in a file.  A more natural Python translation would use
	nl = 0
	for line in input:
		nl += 1
	print nl

Certainly break and continue can be abused.  I would normally expect all
break and continue testing to be in one section of the while loop so
that it looks like

while True:
	<get next whatever we are looping on>
	<should we skip it: continue>
	<are we done yet: break>
	<loop body>

I'm glad to see Python getting taught in schools.  When my daughter's
college decided to stop teaching C++ as the first programming language
(the year she took the course), I urged them to seriously consider
Python, but they went with Java.

> 2) Since this is an introductory class, I am tempted
> to leave out "optional" topics like argument matching
> modes, walk, map, filter, reduce, apply. Do you think
> these are required for any Python programmer?

I think the argument matching is too important to skip.  For cases like
HTTP POST data, passing a dictionary around is pretty convenient when
you can pass it using the ** notation.  It allows you to code:

def celsius(fahrenheit, **kwds):
	return (fahrenheit - 32) * 5 / 9.0

postdata['celsius'] = celsius( **postdata)

So functions can specify just the dictionary keys they care about.  My
little example imagines an HTML form with a variety of variables that
include temperature conversions.

Also zip(*args) is the transpose function.  This is too handy to omit,
but requires covering the single * mode of matching arguments.

> 
> 3) I need to teach a GUI in this class. I would like
> something that is easy, standard, and multi-platform.
> I am considering Tkinter and Jython. Any opnions on
> this?
(not from me.)
> 
> Thanks for any answers you might have.
> 
> -Elaine Haight
> 
> 
> 
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around 
> http://mail.yahoo.com 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp


From bgailer at alum.rpi.edu  Sun Aug 13 03:38:41 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sat, 12 Aug 2006 18:38:41 -0700
Subject: [Tutor] How to teach Python
In-Reply-To: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com>
References: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com>
Message-ID: <44DE82A1.3000903@alum.rpi.edu>

Elaine wrote:
> I am going to be teaching "Introduction to Python Programming" in the Fall at Foothill College in Los Altos Hills, CA. 
Great. Welcome to the Python Teachers Association. I'm your "neighbor" 
to the north, above Berkeley.
> This is a 5 quarter unit class for students who already know one programming language.
>   
I presume you mean "at least one".
> I have been teaching programming for 20 years now, including Java and C++ as of late.
>   
I did it for 10 years. Assembler, APL, BASIC, FORTRAN, PL/I,. Pascal, 
REXX, ....
>  As I prepare this class, I have some questions that I I am hoping you can shed some light on.
>
> 1) Programming Style 
>
>          while 1:
>               x = next()
>               if not x: break
>
> I have never allowed students to use break or continue in any programming class I have taught. I think of this type of code as belonging with the dreaded GOTO.
>   
Consider that all "structured" programming statements are some form of 
GOTO. The question is not which are and which are not but rather the 
effect on readability and maintainability. The alternative to your code 
fragment is:

  x = True 
  while x:
    x = next()

IMHO the former is easier to read, understand, maintain. It gets even 
worse when the terminating condition occurs in the middle of the loop 
code. Then we are stuck with:

  limit = 45
  x = limit  
  while x >= limit:
    x = next()
    if x < limit:
      do more stuff with x

or

  while 1:
    x = next()
    if x >= 45:
      break
    do more stuff with x

I'd rather have the 2nd.



> I find that students who are having difficulty writing complex conditions in a loop use multiple if's with break's inside the loop instead. Also, it is MUCH easier to read a loop if the condition for continuing in the loop is right up at the top of the loop where it belongs.
>   
In some cases that IS where it belongs. In many others that is 
debatable. See my example above. A nice example from 
http://en.wikipedia.org/wiki/Control_flow#Early_exit_from_loops:

   for n in set_of_numbers:
       if isprime(n):
           print "Set contains a prime number"
           break
   else:
       print "Set did not contain any prime numbers"


> I have always thought of break and continue as hacks that are not compatible with structured programming techniques. The only exception is using break in a switch in C, C++ and Java.
>
> However, all Python books seem to contain sample programs like this one. Do you think that code like this is desirable?
>   
Consider also that a feature of Python is the generator, in which a 
function will suspend execution to return (yield) a result, then resume 
following the yield statement. Extremely useful, and hard to defend 
using a limited view of structured programming.
> 2) Since this is an introductory class, I am tempted to leave out "optional" topics like argument matching modes, walk, map, filter, reduce, apply. Do you think these are required for any Python programmer?
>   
Since many of there will disappear in Python 3 it might be OK to omit 
them. OTOH for those of us who come from languages like APL, these 
constructs are dear to our hearts.

Also it is worth noting that filter and apply can be rewritten as list 
comprehensions, so they can be omitted.
> 3) I need to teach a GUI in this class. I would like something that is easy, standard, and multi-platform. I am considering Tkinter and Jython. Any opnions on this?
>   
Jython is not a GUI.
> Thanks for any answers you might have.
>   
Thanks for asking. And good luck with the class. And just for grins see 
http://www.fortran.com/come_from.html for FORTRAN's COME FROM statement.

-- 
Bob Gailer
510-978-4454


From dyoo at hkn.eecs.berkeley.edu  Sun Aug 13 06:59:33 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 12 Aug 2006 21:59:33 -0700 (PDT)
Subject: [Tutor] How to teach Python
In-Reply-To: <44DE82A1.3000903@alum.rpi.edu>
References: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com>
	<44DE82A1.3000903@alum.rpi.edu>
Message-ID: <Pine.LNX.4.64.0608122151240.10709@hkn.eecs.berkeley.edu>

>> 2) Since this is an introductory class, I am tempted to leave out 
>> "optional" topics like argument matching modes, walk, map, filter, 
>> reduce, apply. Do you think these are required for any Python 
>> programmer?
>>
> Since many of there will disappear in Python 3 it might be OK to omit 
> them. OTOH for those of us who come from languages like APL, these 
> constructs are dear to our hearts.

Hi Elaine,

More generally: the "function is as first-class value" is a fundamental 
concept.  I'm not sure when that concept should be introduced, but it 
definitely belongs in an introductory programming course.  If one looks 
at code like this:

     if input == 'a': doA()
     elif input == 'b': doB()
     ...

if we know that functions are avlues, we can reconsider it as:

     dispatchTable = { 'a' : doA,
                       'b' : doB,
                       ... }
     dispatchTable[input]()


Other textbooks have covered this ground; you may want to look at them for 
inspriation.  Here's my favorite one now (it's not Python, but it's good 
stuff.):

     http://www.htdp.org/

From gunny01 at gmail.com  Sun Aug 13 07:18:57 2006
From: gunny01 at gmail.com (Gunny -)
Date: Sun, 13 Aug 2006 14:48:57 +0930
Subject: [Tutor] Making a CLI Text editor in Python
Message-ID: <9bd0fd3d0608122218n1a650d34ma3da4aed76e702e6@mail.gmail.com>

Hi,

I've been playing around with Python for a while now, and I'm looking for
where next to take my skills. I'm thinking of writing a simple text editor
(in the style of Nano), but I'm not sure where to start. Some help or a
point to a tutorial would be great

Cheers

Tom.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060813/11c5de8a/attachment.html 

From anilmrn at yahoo.com  Sun Aug 13 09:56:55 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sun, 13 Aug 2006 00:56:55 -0700 (PDT)
Subject: [Tutor] suggestions for read unread items datastructure
Message-ID: <20060813075655.49062.qmail@web55915.mail.re3.yahoo.com>


suggestions for read unread items datastructure     [input]   [input]   [input]   [input]              

keep a list of read and unread items

hi guys
i m building an rss reader and i want you suggestions for datastructure
for keeping read and unread list for each use
i m assuming it will be very sparse
thanks

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

From alan.gauld at freenet.co.uk  Sun Aug 13 10:18:10 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 13 Aug 2006 09:18:10 +0100
Subject: [Tutor] How to teach Python
References: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com>
Message-ID: <000c01c6beb1$03fa6c30$0201a8c0@XPpro>

Hi Elaine,

There is a separate mailing list for people who teach Python 
as opposed to people learning Python. They might have a 
more pertinent view on this. However, for what its worth 
here are my views...

> students who already know one programming language.

The language they know might make a big difference.
For example if they know Lisp or Smalltalk then the
aspects of Python that will be familiar are very diffferent 
than if they know C++/Java.

> 1) Programming Style 
> 
>         while 1:
>              x = next()
>              if not x: break

Personally I don;t like this style either, its not intuitive 
and harder to read, but it is now the standard Python 
idiom in many cases. The reason for this is that you 
cannot use assignment in the test in Python, as you
can with C/C++ etc so you would need to repeat the 
assignment:

x = func()
while x:
    doit()
    x = func()

Some folks don't like the double assignment and so prefer

while 1
     x = func()
     if not x: break
     doit()

Personally I prefer the first version...

> I have never allowed students to use break or continue
> in any programming class I have taught. I think of this type
> of code as belonging with the dreaded GOTO.

GOTO is no longer consider quite as evil as it used to be... :-)
It just has to be used with discretion.

> complex conditions in a loop use multiple if's with
> break's 

I agree, and this can be a significant barrier to the 
understanding and use of boolean expressions.
Its quite common to see that on this mailing list, 
although I admit we very rarely pick it up and comment.

> inside the loop instead. Also, it is MUCH easier to
> read a loop if the condition for continuing in the loop is
> right up at the top of the loop where it belongs.

Again I agree.
 
> I have always thought of break and continue as hacks
> that  are not compatible with structured programming
> techniques. 

In a pure sense you are right because strictly speaking 
structured programming requires a single exit point in 
a function or block. But break/continue are not the only 
culprits here, multiple return statements have the same 
effect. In practice multiple returns and break/continue 
can improve the readibility of code significantly as well 
as the performance. (And this is also true of GOTO which 
is why academics are giving GOTO a cautious rebirth)


> The only exception is using break in a switch in C,
> C++ and  Java.

And that's purely because the switch statement, like 
so much else, is a badly designed construct in both 
languages. The default position should be to exit the 
case condition at the end of the block, not fall through 
to the next block!.

> However, all Python books seem to contain sample
> programs like this one. Do you think that code like
> this is desirable?

No, but it is standard Python idiom so for the sake of 
students underdstanding other people's Python code 
you probably need to teach it - although you might 
leave it to near the end, after showing the alternatives!

OTOH I don't discuss break/continue in my tutor until 
into the advanced topics... And didn't use them at all
in the original vesion (c 1998) or in the book.

> 2) Since this is an introductory class, I am tempted
> to leave out "optional" topics like argument matching
> modes, walk, map, filter, reduce, apply. Do you think
> these are required for any Python programmer?

The functional programming aspects can be left out, 
argument matching, if you mean what I think, is quite 
important in a dymanically typed language. I'd keep that in.

If you teach list comprehensions you will make the 
map/filter/reduce set almost irrelevant anyway.

> 3) I need to teach a GUI in this class. I would like
> something that is easy, standard, and multi-platform.
> I am considering Tkinter and Jython. Any opnions on
> this?

If they already know Java then teach Jython.
Otherwise Teach Tkinter because 
1) its the python standard
2) its best documented
3) its pretty easy
4) it has a limited widget set (but explore Tix too) which 
is easy to extend
5) its based on Tk which is also the standard GUI for 
Tcl and Perl - and there are versions of it for Lisp and C.

HTH,

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

From johna at johnaherne.co.uk  Sun Aug 13 10:27:46 2006
From: johna at johnaherne.co.uk (John Aherne)
Date: Sun, 13 Aug 2006 09:27:46 +0100
Subject: [Tutor] self (again)
Message-ID: <44DEE282.5080904@johnaherne.co.uk>

I have been following the thread on self because for the past month I 
have been driven potty trying to be sure that I understand the 
ramifications of how self works.

I have tried to create some code that tries to prove how self, 
variables, assignment and namespace gel together. I can't convince 
myself that I have it right.

I think it works as follows. I just need to know what is right.

Class variables are 'global' for the class and all instances of the class.

Using self makes the assignment 'local' to the instance. This is used to 
create variables that will retain the assigned value for the duration of 
the instance. This variable is 'global' for the instance. It can be 
accessed by all the functions in the class/instance without being passed 
as a parameter from function to function.

Self is used if you want to create a class where you store data for a 
'long' period of time. Not like local variables that only have duration 
for the execution of the function.

Within the def functions inside the class, assignments inside the 
function are local.

If the def function inside a class takes a set of parameters that are 
passed in from outside e.g.
class one:
     def func1(parm1,parm2,parm3):

These parameters are passed by reference. So they refer to values held 
elsewhere.
If I use the names inside the function what problem will I give myself. 
Are they local, global.
e.g. if parm1=='somevalue': How long can I trust the value in the passed 
parameter - parm1

What namespace are they in.

I run all this under modpython on windows, where one python interpreter 
runs all the instances so I have multiple copies of the code running in 
the same interpreter. What is likely to happen to these values being 
passed by reference if several people log in at once and run the code.

Hope I have explained myself so people can understand what I mean.

Looking forward to the light of understanding.

Regards

John Aherne





From john.corry at ntlworld.com  Sun Aug 13 11:56:32 2006
From: john.corry at ntlworld.com (John CORRY)
Date: Sun, 13 Aug 2006 10:56:32 +0100
Subject: [Tutor] key_press_event
Message-ID: <000001c6bebe$c5cedcd0$4f3ea8c0@JOHNC>

Hi,

I'm using Python 2.4, pygtk and Glade2.

I have a few text entries.  I am trying to put validation on the text
entry boxes.  I am trying to catch the key_press_event, check the key
that has been pressed and either allow it or put back the old text.  The
code is below with the output after it.

class Test:
    def __init__(self):
        self.wTree = gtk.glade.XML ("test.glade", "window1")
        dic={"on_window1_delete_event" : self.quit10, }
        self.wTree.signal_autoconnect(dic)
        
        cancel = self.wTree.get_widget("button2")
        cancel.connect("clicked", self.quit, )
        text1 = self.wTree.get_widget("entry1")
        text2 = self.wTree.get_widget("entry2")
        text2.connect("key_press_event",self.callback3)
        login = self.wTree.get_widget("button1")
        login.connect("clicked", self.callback2, text1,text2)
    def callback3(self,data,widget):
        
        input = data.get_text()
        print input
        data.set_text("test")
       
        
    def callback2(self,data,text1,text2):
        print 'hello'
    def quit10(self,obj,data):
        gtk.main_quit()
        sys.exit(1)
    def quit(self,obj):
        gtk.main_quit()
        sys.exit(1)
if __name__ == '__main__':
    Test()
    try:
        gtk.threads_init()
    except:
            print "No threading was enabled when you compiled pyGTK!"
            import sys
            sys.exit(1)
    gtk.threads_enter()
    gtk.main()
    gtk.threads_leave()


The box starts of with 123 in it.  If I hit the 'a' key on the key board
I get the following result.

123 is printed and 'atest' appears in the text entry box.

Is there a way to catch the key_press (in this case the 'a') and check
to see if it is a number.  If it is not a number, ignore it.  If it is a
number accept it.  

Why does the 'a' appear in 'atest'.  It is like the code works first,
sets the text to 'test' and then the key press works and inserts the
'a'.  Do I need to disconnect the key press signal?

Thanks,

John. 



From wescpy at gmail.com  Sun Aug 13 12:19:56 2006
From: wescpy at gmail.com (wesley chun)
Date: Sun, 13 Aug 2006 03:19:56 -0700
Subject: [Tutor] How to teach Python
In-Reply-To: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com>
References: <44C0EF6F.7070907@gmail.com>
	<20060812220921.46742.qmail@web31709.mail.mud.yahoo.com>
Message-ID: <78b3a9580608130319h5460dd71ta28e32a0b52c4c2b@mail.gmail.com>

hi elaine,

welcome to Tutor.  this list is really for those learning
Python and/or programming, so i'm going to assume that your
question is directed to mainly tutors, but perhaps tutees
in reference to their experience in learning Python and how
it was/is taught to them.

if you want to address teachers and other educational
individuals, you should probably post to the EDU-SIG
mailing list  -- i'd recommend cross-posting there if you wish:

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


there have been so many good responses so far that i can
just say that you will see "as others have said" quite
often in my reply here.


> I am going to be teaching "Introduction to Python
> Programming" in the Fall at Foothill College in Los
> Altos Hills, CA.

that's great!  i am also a Python teacher professionally
and happen to live just 5 minutes away from the campus.
if you ever need a substitute and don't wish to cancel
class for any some reason, drop me a line.


> I have been teaching programming for 20 years now,
> including Java and C++ as of late.

i have been teaching since 1983... BASIC, C, and Python
are the programming languages i have taught over the years.


> 1) Programming Style
>          while 1:
>               x = next()
>               if not x: break
>
> I have never allowed students to use break or continue
> in any programming class I have taught. I think of this
> type of code as belonging with the dreaded GOTO.
>
> I have always thought of break and continue as hacks that
> are not compatible with structured programming techniques.
> The only exception is using break in a switch in C, C++ and
> Java.
>
> However, all Python books seem to contain sample
> programs like this one. Do you think that code like
> this is desirable?

as others have mentioned already, because assignments are
not expressions in Python, it is quite a common idiom and
should be covered and implemented in this manner to keep
the code cleaner and more consistent.  remember that
"readability counts."  its are in all the books because
it is one of those basic idioms that ppl *have* to use
to get things done.

also as others have said, GOTO does not have the stigma
that it once had and that there is nothing wrong in
principle with break and continue when used with loops,
which is what they were designed to do.  you pretty much
have to be a very experienced programmer in order to know
when and where are the right places for that beast.

with that said, it would be a good idea to review the Zen
to truly understand the philosophy of Python.  it is one
thing teaching and learning Python, but it is another
step when you are able to understand it and program in a
"Pythonic" way.  (if away from the internet or a book,
you can access then Zen using 'import this' or 'python
-m this' from the shell.)


> 2) Since this is an introductory class, I am tempted
> to leave out "optional" topics like argument matching
> modes, walk, map, filter, reduce, apply. Do you think
> these are required for any Python programmer?

list comprehensions (and generator expressions) have obsoleted
map() and filter() because in general, their performance is
better, but that is not always the case.  apply() was
deprecated by the new function invocation mechanism using *
and ** back in Python 1.6.

reduce() will stick around.  i'm not sure what "walk" is, and
argument matching is important.  in fact, you need to cover
standard/formal/required argus, default args, keyword args,
and variable args (* tuples and ** dictionaries).


> 3) I need to teach a GUI in this class. I would like
> something that is easy, standard, and multi-platform.
> I am considering Tkinter and Jython. Any opnions on
> this?

Tkinter was chosen as the default for Python way back in the
early days because that was easy to understand and teach and
was available on the big 3 platforms (Unix, Win, Mac).  i
teach this in my courses (and also in "Core Python," the
textbook i wrote for college-level courses as well as for
working professionals), but also try to cover more advanced
and related widget sets like Pmw and Tix.  if you want to
teach the most basic concepts, even leaving off event-driven
programming, take a look at EasyGUI.

since then, however, it is no longer the only GUI toolkit.
wxWindows (and its adapter wxPython) has grown in userbase
quite a lot in the last few years -- it is also cross-plat-
form.  one of its greatst features is that it uses a system's
native widget set.  in other words, GUIs written on Win32
look like Windoze apps, and the same for Mac and *ix.

there are some nice "intro" libraries like PythonCard.  for
building GUIs in wxPython, one of the most painless ways is
using Boa Constructor.  you can drag-n-drop widgets onto a
canvas.  Boa writes the boilerplate code, and you only have
to worry about supplying the callbacks.

fwiw, i teach both an "Introduction to Programming using
Python" course as well as an (intensive) "Introduction to
Python" programming course.  the first is meant for those
with no programming experience whatsoever while the second
matches your prerequisite of knowledge of at least one other
high-level language is required. if you're curious as to
the topics i cover in either course, here are their course
descriptions, repsectively:

http://roadkill.com/~wesc/cyberweb/ippdsc.html
http://roadkill.com/~wesc/cyberweb/pp1dsc.html

it is also not by coincidence that the syllabus follows the
text and exercises found in "Core Python" very closely. :-)

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

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

From john.corry at ntlworld.com  Sun Aug 13 12:47:05 2006
From: john.corry at ntlworld.com (John CORRY)
Date: Sun, 13 Aug 2006 11:47:05 +0100
Subject: [Tutor] [pygtk] key_press_event
In-Reply-To: <20060813102743.GA11920@casa.e-den.it>
Message-ID: <000201c6bec5$d5f89270$4f3ea8c0@JOHNC>

Sandro,

That's exactly what I need.  

Thanks,

John.

>     def callback3(self,data,widget):
>         
>         input = data.get_text()
>         print input
>         data.set_text("test")


If you don't return True, default callback will be called that insert
the 'a'.

I have something like this:

    def digits_check_input_cb(self, widget, event):
        """prevents the possibility of inputting wrong chars"""
        ## fixme: missing comma, and cut&paste
        key = gtk.gdk.keyval_name (event.keyval)

 
ONLYDIGITS="([0-9.,]|BackSpace|Left|Right|F1|period|Tab|Up|Down)"
        if not re.match (ONLYDIGITS, key):
            return True

Not sure whether this is the best way thought...

sandro
*;-)

-- 
Sandro Dentella  *:-)
http://www.tksql.org                    TkSQL Home page - My GPL work



From pythontut at pusspaws.net  Sun Aug 13 13:33:00 2006
From: pythontut at pusspaws.net (dave s)
Date: Sun, 13 Aug 2006 11:33:00 +0000
Subject: [Tutor] Style query
Message-ID: <200608131133.00864.pythontut@pusspaws.net>

As my programs become more complex I am aware of the need to adopt a 
consistent style. To differentiate between classes, instances & objects I use 
capital letters for example:

A class uses 'MyClass'
A class instance 'myInstance'
A def uses 'myDef'
An object 'myobject' or 'my_object' etc 

Can any of you more experienced programmers outline your style or critique my 
way of doing this ? Tell me if you have a different system - I am trying to 
get myself into good habits :)

Is there a Python style guide anywhere ?

Cheers

Dave


PS

I have started using packages, so much easier and more flexable than long 
PYTHONPATH declarations and am now proramming with QT :).

From rfquerin at gmail.com  Sun Aug 13 14:02:10 2006
From: rfquerin at gmail.com (Richard Querin)
Date: Sun, 13 Aug 2006 08:02:10 -0400
Subject: [Tutor] Style query
In-Reply-To: <200608131133.00864.pythontut@pusspaws.net>
References: <200608131133.00864.pythontut@pusspaws.net>
Message-ID: <7d81675b0608130502j2cbad2fap1b224726de99f643@mail.gmail.com>

I believe you can find it here:

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

Authored by Guido Van Rossum himself.


Cheers,

Richard


On 8/13/06, dave s <pythontut at pusspaws.net> wrote:
>
> As my programs become more complex I am aware of the need to adopt a
> consistent style. To differentiate between classes, instances & objects I
> use
> capital letters for example:
>
> A class uses 'MyClass'
> A class instance 'myInstance'
> A def uses 'myDef'
> An object 'myobject' or 'my_object' etc
>
> Can any of you more experienced programmers outline your style or critique
> my
> way of doing this ? Tell me if you have a different system - I am trying
> to
> get myself into good habits :)
>
> Is there a Python style guide anywhere ?
>
> Cheers
>
> Dave
>
>
> PS
>
> I have started using packages, so much easier and more flexable than long
> PYTHONPATH declarations and am now proramming with QT :).
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060813/cb338018/attachment.html 

From pythontut at pusspaws.net  Sun Aug 13 14:13:19 2006
From: pythontut at pusspaws.net (dave s)
Date: Sun, 13 Aug 2006 12:13:19 +0000
Subject: [Tutor] Style query
In-Reply-To: <7d81675b0608130502j2cbad2fap1b224726de99f643@mail.gmail.com>
References: <200608131133.00864.pythontut@pusspaws.net>
	<7d81675b0608130502j2cbad2fap1b224726de99f643@mail.gmail.com>
Message-ID: <200608131213.21950.pythontut@pusspaws.net>

On Sunday 13 August 2006 12:02, you wrote:
> I believe you can find it here:
>
> http://www.python.org/doc/essays/styleguide.html
>
> Authored by Guido Van Rossum himself.
>

Thanks :)

Dave


>
> Cheers,
>
> Richard
>
> On 8/13/06, dave s <pythontut at pusspaws.net> wrote:
> > As my programs become more complex I am aware of the need to adopt a
> > consistent style. To differentiate between classes, instances & objects I
> > use
> > capital letters for example:
> >
> > A class uses 'MyClass'
> > A class instance 'myInstance'
> > A def uses 'myDef'
> > An object 'myobject' or 'my_object' etc
> >
> > Can any of you more experienced programmers outline your style or
> > critique my
> > way of doing this ? Tell me if you have a different system - I am trying
> > to
> > get myself into good habits :)
> >
> > Is there a Python style guide anywhere ?
> >
> > Cheers
> >
> > Dave
> >
> >
> > PS
> >
> > I have started using packages, so much easier and more flexable than long
> > PYTHONPATH declarations and am now proramming with QT :).
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor

From bgailer at alum.rpi.edu  Sun Aug 13 18:50:08 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sun, 13 Aug 2006 09:50:08 -0700
Subject: [Tutor] suggestions for read unread items datastructure
In-Reply-To: <20060813075655.49062.qmail@web55915.mail.re3.yahoo.com>
References: <20060813075655.49062.qmail@web55915.mail.re3.yahoo.com>
Message-ID: <44DF5840.7080204@alum.rpi.edu>

anil maran wrote:
>
> 	suggestions for read unread items datastructure
>
>
> keep a list of read and unread items
>
> hi guys
> i m building an rss reader and i want you suggestions for datastructure
> for keeping read and unread list for each use
> i m assuming it will be very sparse
Just a guess but I think the lack of response is due to (at least for 
me) not knowing enough about your situation to give a useful response. 
Please tell us more.

-- 
Bob Gailer
510-978-4454


From simplebob at gmail.com  Sun Aug 13 20:22:06 2006
From: simplebob at gmail.com (Daniel McQuay)
Date: Sun, 13 Aug 2006 14:22:06 -0400
Subject: [Tutor] suggestions for read unread items datastructure
In-Reply-To: <44DF5840.7080204@alum.rpi.edu>
References: <20060813075655.49062.qmail@web55915.mail.re3.yahoo.com>
	<44DF5840.7080204@alum.rpi.edu>
Message-ID: <6d87ecf40608131122i29bdcadew16d48d03f3264382@mail.gmail.com>

i concur, anil try looking at how you ask a question.
http://catb.org/~esr/faqs/smart-questions.html#before

On 8/13/06, Bob Gailer <bgailer at alum.rpi.edu> wrote:
>
> anil maran wrote:
> >
> >       suggestions for read unread items datastructure
> >
> >
> > keep a list of read and unread items
> >
> > hi guys
> > i m building an rss reader and i want you suggestions for datastructure
> > for keeping read and unread list for each use
> > i m assuming it will be very sparse
> Just a guess but I think the lack of response is due to (at least for
> me) not knowing enough about your situation to give a useful response.
> Please tell us more.
>
> --
> Bob Gailer
> 510-978-4454
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Daniel McQuay
simplebob at gmail.com
boxster.homelinux.org
prowiseguys.com
H: 814.825.0847
M: 814-341-6233
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060813/51e1a794/attachment.html 

From anilmrn at yahoo.com  Sun Aug 13 21:21:31 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sun, 13 Aug 2006 12:21:31 -0700 (PDT)
Subject: [Tutor] suggestions for read unread items datastructure
In-Reply-To: <44DF5840.7080204@alum.rpi.edu>
Message-ID: <20060813192131.98005.qmail@web55912.mail.re3.yahoo.com>

there is a blog
and it associated feed entries
the blog posts
when someone clicks it i need to maintain read status for it
and when it is unclicked i need the unread status
this needs to be maintianed for a huge number of usrs
thanks

Bob Gailer <bgailer at alum.rpi.edu> wrote: anil maran wrote:
>
>  suggestions for read unread items datastructure
>
>
> keep a list of read and unread items
>
> hi guys
> i m building an rss reader and i want you suggestions for datastructure
> for keeping read and unread list for each use
> i m assuming it will be very sparse
Just a guess but I think the lack of response is due to (at least for 
me) not knowing enough about your situation to give a useful response. 
Please tell us more.

-- 
Bob Gailer
510-978-4454



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

From dyoo at hkn.eecs.berkeley.edu  Sun Aug 13 22:18:36 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 13 Aug 2006 13:18:36 -0700 (PDT)
Subject: [Tutor] suggestions for read unread items datastructure
In-Reply-To: <20060813192131.98005.qmail@web55912.mail.re3.yahoo.com>
References: <20060813192131.98005.qmail@web55912.mail.re3.yahoo.com>
Message-ID: <Pine.LNX.4.64.0608131305350.22172@hkn.eecs.berkeley.edu>



On Sun, 13 Aug 2006, anil maran wrote:

> when someone clicks it i need to maintain read status for it

Hi Anil,

You've giving some "use case" information, which is useful.  Can you also 
give us some definitions?  Are you saying that an rss entry is some data 
with an associated 'read' status?  What else does an rss entry have? 
What do people do with it?

I'm mimicking total ignorance here, but this is not far from the truth. 
*grin* I really don't know what an RSS reader is supposed to handle, and 
since it sounds like you're writing one from scratch, you should also 
explicitely state what things you want out of it.



In your earlier question, you asked what an appropriate data structure 
will be for storing RSS entries.  It sounds that you're dealing with two 
distinct data types:

     * A singular 'RssEntry' that contains information on a single RSS
       item.

     * An 'RssLibrary' collection that has a bunch of 'RssEntries'.

Is this accurate, or are you thinking of something else?  What are the 
operations you want to do with your data types?



> this needs to be maintianed for a huge number of usrs

Let's try to forget efficiency for the moment; I'm not even sure people on 
the list are even clear about what you are trying to represent yet. 
Let's get the concepts solid first before talking about scaling to large 
groups.

From alan.gauld at freenet.co.uk  Mon Aug 14 01:24:09 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 14 Aug 2006 00:24:09 +0100
Subject: [Tutor] suggestions for read unread items datastructure
References: <20060813192131.98005.qmail@web55912.mail.re3.yahoo.com>
Message-ID: <00c201c6bf2f$9447f630$0201a8c0@XPpro>

Caveat - I know nothing about RSS, it's one of those web 
technologies that I just can't get excited about, sorry...

However...

> there is a blog
> and it associated feed entries
> the blog posts
> when someone clicks it i need to maintain read status for it
> and when it is unclicked i need the unread status
> this needs to be maintianed for a huge number of usrs

Whenever you need to maintain data for "a huge number of users"
its time to question whether it's your job to maintain the data. 
Maybe the users should each maintain their own data? That's 
the idea behind cookies in a web browsing context - does 
anything similar work for RSS?

Alan G.

From alan.gauld at freenet.co.uk  Mon Aug 14 01:44:46 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 14 Aug 2006 00:44:46 +0100
Subject: [Tutor] self (again)
References: <44DEE282.5080904@johnaherne.co.uk>
Message-ID: <00c801c6bf32$7581aae0$0201a8c0@XPpro>

> I think it works as follows. I just need to know what is right.
>
> Class variables are 'global' for the class and all instances of the 
> class.

Correct. Classes are containers and they contain the class
variables and method definitions shared by all instances of
the class (and its subclasses).

> Using self makes the assignment 'local' to the instance.

Sort of, but self is just a reference to an instance of a class.
There is no magic involved (or very little), when you call a
method on an instance you simply execute the function
stored in the class object but pass in a reference to the
called instance as the first argument.

> create variables that will retain the assigned value for the 
> duration of the instance.

Correct, the instance is also a container that holds a reference
to the defining class and all the instance variables.

> This variable is 'global' for the instance.

I'd prefer to say local to the instance. Its not shared outside
the instance and can only be accessed in methods via the
self reference

> accessed by all the functions in the class/instance without being 
> passed as a parameter from function to function.

No, it can only be accessed by the methods via the self reference
that is passed implicitly in each method call.

> Self is used if you want to create a class where you store data for 
> a 'long' period of time. Not like local variables that only have 
> duration for the execution of the function.

No, self is purely about allowing the methods stored in a
class object to access the instance variables of the specific
instance that invoked the method at any given point in time.

There are many ways to store data over a long period that
do not use self (global variables, lists, dictionaries, tuples,
files, databases). Even class attributes can do that,
regardless of whether any instances are created.

> Within the def functions inside the class, assignments inside the 
> function are local.

As they are in any other functuion, again nothing magic is
happening here.

> If the def function inside a class takes a set of parameters that 
> are passed in from outside e.g.
> class one:
>     def func1(parm1,parm2,parm3):
>
> These parameters are passed by reference. So they refer to values 
> held elsewhere.

Again just like any other function, yes.

> If I use the names inside the function what problem will I give 
> myself.

None, thats what they are there for. They are your mechanism
for comunicating between the world outside the function and the
world (or namespace) inside.

> Are they local, global.

They are local. The name of the parameter bears norelation to what
that value is called (or referenced by) outsidfe the function.

> e.g. if parm1=='somevalue': How long can I trust the value in the 
> passed parameter - parm1

Until you change it or exit the function.
Example:

def f(a,b):
    if a > b: a = b
    return a+b

x=3
f(x,4)  -> 7
print x   -> 3
f(x,3)  -> 6
print x   -> 3
f(x,2)  -> 4
print x   -> 3

So even in the last case x remains equal to 3 but inside
the function the value of a was changed to 2. This is standard
function behaviour and there is nothing different about methods
in a class.

> What namespace are they in.

The parameters are in the local namespace of the method.

> I run all this under modpython on windows, where one python 
> interpreter runs all the instances so I have multiple copies of the 
> code running in the same interpreter. What is likely to happen to 
> these values being passed by reference if several people log in at 
> once and run the code.

I know nothing about mod_python but assuming it uses threading
then you need to avoid changing global variables or class variables
without using locks or semaphores. But instances created in a
thread should remain independant from each other - a good reason
for using OOP for multi threaded code!

> Hope I have explained myself so people can understand what I mean.

ditto!

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


From kermit at polaris.net  Mon Aug 14 02:37:43 2006
From: kermit at polaris.net (Kermit Rose)
Date: Sun, 13 Aug 2006 20:37:43 -0400 (Eastern Daylight Time)
Subject: [Tutor] Global variables
References: <Pine.LNX.4.64.0608091028210.18371@hkn.eecs.berkeley.edu>
Message-ID: <44DFC5D7.00000D.02912@YOUR-4105E587B6>

 
 
From: Danny Yoo 
Date: 08/09/06 16:23:35 
To: Kermit Rose 
Cc: tutor at python.org 
 
 
If I can figure out how to make my main function subroutine declare global
variables
then I won't need to pass parameters most parameters to the other
subroutines,
 
and will bypass the problem I'm having that sometimes the function strongfac
SOMETIMES does not return the value it has in the subroutine, back to the
calling routine.
 
 
Kermit  <  kermit at polaris.net   >
 
 
 
 
 
 


From dianahawks at optusnet.com.au  Mon Aug 14 03:57:53 2006
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Mon, 14 Aug 2006 11:57:53 +1000
Subject: [Tutor] Python on network problems
Message-ID: <200608140157.k7E1vrWP013862@mail16.syd.optusnet.com.au>

An embedded and charset-unspecified text was scrubbed...
Name: not available
Url: http://mail.python.org/pipermail/tutor/attachments/20060814/5244fe1a/attachment.pot 

From rabidpoobear at gmail.com  Mon Aug 14 04:28:37 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 13 Aug 2006 21:28:37 -0500
Subject: [Tutor] Global variables
In-Reply-To: <44DFC5D7.00000D.02912@YOUR-4105E587B6>
References: <Pine.LNX.4.64.0608091028210.18371@hkn.eecs.berkeley.edu>
	<44DFC5D7.00000D.02912@YOUR-4105E587B6>
Message-ID: <44DFDFD5.2080208@gmail.com>

Kermit Rose wrote:
>  
>  
> From: Danny Yoo 
> Date: 08/09/06 16:23:35 
> To: Kermit Rose 
> Cc: tutor at python.org 
>  
>  
> If I can figure out how to make my main function subroutine declare global
> variables
> then I won't need to pass parameters most parameters to the other
> subroutines,
>  
> and will bypass the problem I'm having that sometimes the function strongfac
> SOMETIMES does not return the value it has in the subroutine, back to the
> calling routine.
>   
are you asking a question?

From rabidpoobear at gmail.com  Mon Aug 14 04:37:22 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 13 Aug 2006 21:37:22 -0500
Subject: [Tutor] Python on network problems
In-Reply-To: <200608140157.k7E1vrWP013862@mail16.syd.optusnet.com.au>
References: <200608140157.k7E1vrWP013862@mail16.syd.optusnet.com.au>
Message-ID: <44DFE1E2.6000309@gmail.com>

Diana Hawksworth wrote:
> Dear List,
>
> I have Python installed on 1 of 4 labs at my High School. The lab is connected to a whole school network.  Students login through the network - but Python is active in this lab only.
>   
You have 4 labs.
Python is installed on all the computers in a single lab.
All of the labs are networked together.
Students log into an authentication server and not to the individual 
computer.

Are they given 'virtual' drives?  some type of network-based storage?
Are they using Windows? What version?
What do you mean 'Python is _active_'?
> Sometimes I have a student who simply cannot access Python, even though he has been working on it for a number of months now.  Usually a change in username will solve the problem - but I would like to know what is causing this to happen.
>   
They can't access the python install on the individual computer on which 
they're logged, or they can't access a python install that's on a 
different computer on the network?  A change in their network login 
fixes the problem?
> The second problem is much more severe. Seems for the past three weeks now, the entire system will crash.  It happens when we are working on Python - so the assumption is that the program is to blame. I cannot see that it is - but it certainly is upsetting when it happens. Has anyone had a similar accurrence with Python and networks? If so - what have you done about it.  If not - then any clues about what could be happening so that I can get the system administrator off my back - and get the system working again!!
>
> Thanks for any suggestions.
>   
Is it like this:

Lab1:
    Computer1 - has python
    Computer2 - has python
Lab2:
    Computer3 - no python
Lab3:
    Computer4 - no python
Lab4:
    Computer5 - no python

A user logs onto the network from Computer5 in Lab4.
Do you expect him to be able to run a python script?
What interpreter do you expect him to use?  One that's installed on a 
computer in Lab1?

Say a user logs onto Computer1.
they can run python programs on their computer.
Do you expect them to be able to run python programs that are stored on 
Computer2, using the
interpreter that's installed on Computer1?


I'm not too clear on how you have this set up, what it's supposed to do,
and why the network is involved at all.
It seems like the kids should be able to run python scripts on any 
computer in Lab1
without fiddling with the network whatsoever, so I suspect that there's some
additional information that I'm not getting.
Can you clarify?

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


From anilmrn at yahoo.com  Mon Aug 14 07:59:54 2006
From: anilmrn at yahoo.com (anil maran)
Date: Sun, 13 Aug 2006 22:59:54 -0700 (PDT)
Subject: [Tutor] suggestions for read unread items datastructure
In-Reply-To: <00c201c6bf2f$9447f630$0201a8c0@XPpro>
Message-ID: <20060814055954.23253.qmail@web55914.mail.re3.yahoo.com>

i m sure the users need to maintain their own data,
but as a provider we need to store their information
right, sessions and cookies work only during their
stay in the site, after they exit, im sure they would
like to come back to the same info, wont u

so i was wondering what is the best way to maintain
the list of read/unread items in a python
datastructure, 

--- Alan Gauld <alan.gauld at freenet.co.uk> wrote:

> Caveat - I know nothing about RSS, it's one of those
> web 
> technologies that I just can't get excited about,
> sorry...
> 
> However...
> 
> > there is a blog
> > and it associated feed entries
> > the blog posts
> > when someone clicks it i need to maintain read
> status for it
> > and when it is unclicked i need the unread status
> > this needs to be maintianed for a huge number of
> usrs
> 
> Whenever you need to maintain data for "a huge
> number of users"
> its time to question whether it's your job to
> maintain the data. 
> Maybe the users should each maintain their own data?
> That's 
> the idea behind cookies in a web browsing context -
> does 
> anything similar work for RSS?
> 
> Alan G.
> 


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

From rdm at rcblue.com  Mon Aug 14 08:30:37 2006
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 13 Aug 2006 23:30:37 -0700
Subject: [Tutor] Having trouble getting mind around decimal module
Message-ID: <7.0.1.0.2.20060813231658.06d43ff8@rcblue.com>

I'm having trouble getting my mind around the decimal module. From 
the tutorial (<http://docs.python.org/lib/decimal-tutorial.html>) I 
can see how to get 1/7 to, say, 32 places:

 >>> from decimal import Decimal
 >>> getcontext().prec = 32
 >>> Decimal(1) / Decimal(7)
Decimal("0.14285714285714285714285714285714")

But I can't figure out how to compute to 32 places things like the 
square root of 2, or the arc tangent of .41. Could someone please show me?

Thanks,

Dick Moores
rdm at rcblue.com


From dianahawks at optusnet.com.au  Mon Aug 14 08:55:43 2006
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Mon, 14 Aug 2006 16:55:43 +1000
Subject: [Tutor] Python on network problems
References: <200608140157.k7E1vrWP013862@mail16.syd.optusnet.com.au>
	<44E01809.9070200@gmail.com>
Message-ID: <000c01c6bf6e$a9c781d0$2e716c3a@SNNECCM>

Thanks Tom.  I installed the latest version on Friday - but today the system 
went down again. I am inclined to think it is not a Python problem at all. 
Just need someone who also has it installed on a network to know if they 
have had any problems!!
Diana

----- Original Message ----- 
From: "Tom Schinckel" <gunny01 at gmail.com>
To: <dianahawks at optusnet.com.au>
Sent: Monday, August 14, 2006 4:28 PM
Subject: Re: [Tutor] Python on network problems


> Diana Hawksworth wrote:
>> Dear List,
>>
>> I have Python installed on 1 of 4 labs at my High School. The lab is 
>> connected to a whole school network.  Students login through the 
>> network - but Python is active in this lab only.
>>
>> Sometimes I have a student who simply cannot access Python, even though 
>> he has been working on it for a number of months now.  Usually a change 
>> in username will solve the problem - but I would like to know what is 
>> causing this to happen.
>>
>> The second problem is much more severe. Seems for the past three weeks 
>> now, the entire system will crash.  It happens when we are working on 
>> Python - so the assumption is that the program is to blame. I cannot see 
>> that it is - but it certainly is upsetting when it happens. Has anyone 
>> had a similar accurrence with Python and networks? If so - what have you 
>> done about it.  If not - then any clues about what could be happening so 
>> that I can get the system administrator off my back - and get the system 
>> working again!!
>>
>> Thanks for any suggestions.
>>
>> Diana
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
> It sounds a tad out of my depth, but when I first installed Python, IDLE 
> crashed, all the time.
>
> Try the age old software fix: reinstall.
>
> Cheers
>
> Tom
> 



From rabidpoobear at gmail.com  Mon Aug 14 09:49:50 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 14 Aug 2006 02:49:50 -0500
Subject: [Tutor] Having trouble getting mind around decimal module
In-Reply-To: <7.0.1.0.2.20060813231658.06d43ff8@rcblue.com>
References: <7.0.1.0.2.20060813231658.06d43ff8@rcblue.com>
Message-ID: <44E02B1E.2070103@gmail.com>

Dick Moores wrote:
> I'm having trouble getting my mind around the decimal module. From 
> the tutorial (<http://docs.python.org/lib/decimal-tutorial.html>) I 
> can see how to get 1/7 to, say, 32 places:
>
>  >>> from decimal import Decimal
>  >>> getcontext().prec = 32
>  >>> Decimal(1) / Decimal(7)
> Decimal("0.14285714285714285714285714285714")
>
> But I can't figure out how to compute to 32 places things like the 
> square root of 2, or the arc tangent of .41. Could someone please show me?
>
>   
I think square root calculations, and other math operations, by the 
built-in math.py package
only work on floats since they wrap math.c
So you'd have to find a pure-python implementation that supported 
Decimal objects I guess,
or write your own.
> Thanks,
>
> Dick Moores
> rdm at rcblue.com
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From alan.gauld at freenet.co.uk  Mon Aug 14 09:52:42 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 14 Aug 2006 08:52:42 +0100
Subject: [Tutor] Having trouble getting mind around decimal module
References: <7.0.1.0.2.20060813231658.06d43ff8@rcblue.com>
Message-ID: <002501c6bf76$9fc805d0$0201a8c0@XPpro>

> >>> from decimal import Decimal
> >>> getcontext().prec = 32
> >>> Decimal(1) / Decimal(7)
> Decimal("0.14285714285714285714285714285714")
>
> But I can't figure out how to compute to 32 places things like the 
> square root of 2, or the arc tangent of .41. Could someone please 
> show me?

The first is easy:

>>> from decimal import getcontext
>>> getcontext().prec = 32
>>> Decimal(2).sqrt()
Decimal("1.4142135623730950488016887242097")

actan(0.41) is trickier... because you need to use the math module
>>> Decimal(str(math.atan(0.41)))
0.38909723105527838

And that limits the precision. If you were working with lower value
precision - say 16 digits - then it would be OK.

>>> getcontext().prec=12
>>> Decimal(str(math.atan(0.41)))
Decimal("0.389097231055")
>>>

HTH,

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


From rabidpoobear at gmail.com  Mon Aug 14 09:56:27 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 14 Aug 2006 02:56:27 -0500
Subject: [Tutor] suggestions for read unread items datastructure
In-Reply-To: <20060814055954.23253.qmail@web55914.mail.re3.yahoo.com>
References: <20060814055954.23253.qmail@web55914.mail.re3.yahoo.com>
Message-ID: <44E02CAB.2040507@gmail.com>

anil maran wrote:
> i m sure the users need to maintain their own data,
> but as a provider we need to store their information
> right, sessions and cookies work only during their
> stay in the site, after they exit, im sure they would
> like to come back to the same info, wont u
>
> so i was wondering what is the best way to maintain
> the list of read/unread items in a python
> datastructure, 
>   
It's not that we don't want to help you, it's that we don't understand 
what you want to do.
Consider this:
Are you trying to make a client-side program for this?
    If so, why do you care about storing multiple user data?
Are you making a server that mirrors other RSS feeds for your users?
 
Are you making a client-side program that communicates with a single server
that has everyone's RSS feeds on it?

Why do you think you need to do things this way?
Why are you concerned about the data structure used to store this when 
there's
other things to be concerned about (RSS feed parsing, etc, etc.)
This should be one of the last things you worry about.

Also, Alan wasn't suggesting you use cookies.
He was stating that websites allow the client to maintain information 
about their own activities,
rather than the server trying to manage all the users.
He means that maybe you shouldn't be concerned about which RSS feeds 
your clients have been to
and let the clients take care of it themselves.

Sort of how my mailserver sends me all my mail, but my E-mail client 
takes care of marking
individual messages 'read/unread' and sorting it into folders.  There's 
no reason for the server
to need to know about any of this stuff.  Does your server really need 
to know about which
RSS feeds the clients have viewed?
> --- Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
>   
>> Caveat - I know nothing about RSS, it's one of those
>> web 
>> technologies that I just can't get excited about,
>> sorry...
>>
>> However...
>>
>>     
>>> there is a blog
>>> and it associated feed entries
>>> the blog posts
>>> when someone clicks it i need to maintain read
>>>       
>> status for it
>>     
>>> and when it is unclicked i need the unread status
>>> this needs to be maintianed for a huge number of
>>>       
>> usrs
>>
>> Whenever you need to maintain data for "a huge
>> number of users"
>> its time to question whether it's your job to
>> maintain the data. 
>> Maybe the users should each maintain their own data?
>> That's 
>> the idea behind cookies in a web browsing context -
>> does 
>> anything similar work for RSS?
>>
>> Alan G.
>>
>>     
>
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around 
> http://mail.yahoo.com 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From alan.gauld at freenet.co.uk  Mon Aug 14 09:56:36 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 14 Aug 2006 08:56:36 +0100
Subject: [Tutor] Python on network problems
References: <200608140157.k7E1vrWP013862@mail16.syd.optusnet.com.au><44E01809.9070200@gmail.com>
	<000c01c6bf6e$a9c781d0$2e716c3a@SNNECCM>
Message-ID: <002901c6bf77$2b8de210$0201a8c0@XPpro>

Diana,

It is almost certainly not a Python problem but related to how
you have the network set up. As Luke was trying to point out,
we  mifght be able to help out but your description of the
network setup wasn't clear.

We need more precise information about things like:
what OS you are using?
Are you using Domains/NIS/NDS etc?
Do you have shared drives, VNC, windows terminal server?
How do you define a 'lab'?
What do you mean by python being 'active'?
And what exactly happens when a failure occurs?

None of these things are standardised in anmy way.

Alan G



----- Original Message ----- 
From: "Diana Hawksworth" <dianahawks at optusnet.com.au>
To: "Tom Schinckel" <gunny01 at gmail.com>; <tutor at python.org>
Sent: Monday, August 14, 2006 7:55 AM
Subject: Re: [Tutor] Python on network problems


> Thanks Tom.  I installed the latest version on Friday - but today 
> the system went down again. I am inclined to think it is not a 
> Python problem at all. Just need someone who also has it installed 
> on a network to know if they have had any problems!!
> Diana
>
> ----- Original Message ----- 
> From: "Tom Schinckel" <gunny01 at gmail.com>
> To: <dianahawks at optusnet.com.au>
> Sent: Monday, August 14, 2006 4:28 PM
> Subject: Re: [Tutor] Python on network problems
>
>
>> Diana Hawksworth wrote:
>>> Dear List,
>>>
>>> I have Python installed on 1 of 4 labs at my High School. The lab 
>>> is connected to a whole school network.  Students login through 
>>> the network - but Python is active in this lab only.
>>>
>>> Sometimes I have a student who simply cannot access Python, even 
>>> though he has been working on it for a number of months now. 
>>> Usually a change in username will solve the problem - but I would 
>>> like to know what is causing this to happen.
>>>
>>> The second problem is much more severe. Seems for the past three 
>>> weeks now, the entire system will crash.  It happens when we are 
>>> working on Python - so the assumption is that the program is to 
>>> blame. I cannot see that it is - but it certainly is upsetting 
>>> when it happens. Has anyone had a similar accurrence with Python 
>>> and networks? If so - what have you done about it.  If not - then 
>>> any clues about what could be happening so that I can get the 
>>> system administrator off my back - and get the system working 
>>> again!!
>>>
>>> Thanks for any suggestions.
>>>
>>> Diana
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>> It sounds a tad out of my depth, but when I first installed Python, 
>> IDLE crashed, all the time.
>>
>> Try the age old software fix: reinstall.
>>
>> Cheers
>>
>> Tom
>>
>
>
>
> 


From kent37 at tds.net  Mon Aug 14 13:52:44 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 14 Aug 2006 07:52:44 -0400
Subject: [Tutor] i18n Encoding/Decoding issues
In-Reply-To: <BAY5-F47A6D444C943E857BA744864A0@phx.gbl>
References: <BAY5-F47A6D444C943E857BA744864A0@phx.gbl>
Message-ID: <44E0640C.4060904@tds.net>

Jorge De Castro wrote:
> Hi all,
>
> It seems I can't get rid of my continuous issues i18n with Python :(
>   
You're not alone :-)
> I've been through:
> http://docs.python.org/lib/module-email.Header.html
> and
> http://www.reportlab.com/i18n/python_unicode_tutorial.html
> to no avail.
>   
Try these:
http://www.joelonsoftware.com/articles/Unicode.html
http://jorendorff.com/articles/unicode/index.html
> Basically, I'm receiving and processing mail that comes with content (from 
> an utf-8 accepting form) from many locales (France, Germany, etc)
>
> def splitMessage() does what the name indicates, and send message is the 
> code below.
>
> def sendMessage(text):
>     to, From, subject, body = splitMessage(text)
>     msg = MIMEText(decodeChars(body), 'plain', 'UTF-8')
>     msg['From'] = From
>     msg['To'] = to
>     msg['Subject'] = Header(decodeChars(subject), 'UTF-8')
>
> def decodeChars(str=""):
>     if not str: return None
>     for characterCode in _characterCodes.keys():
>         str = str.replace(characterCode, _characterCodes[characterCode])
>     return str
>
> Now as you have noticed, this only works, ie, I get an email sent with the 
> i18n characters displayed correctly, after I pretty much wrote my own 
> 'urldecode' map
>
> _characterCodes ={  "%80" : "&#65533;", "%82" : "&#65533;", "%83" : 
> "&#65533;", "%84" : "&#65533;", \
>                     "%85" : "&#65533;", "%86" : "&#65533;",	"%87" : 
> "&#65533;", "%88" : "&#65533;", \
>                     "%89" : "&#65533;", "%8A" : "&#65533;", "%8B" : 
> "&#65533;", "%8C" : "&#65533;", \
>                     "%8E" : "&#65533;", "%91" : "&#65533;", "%92" : 
> "&#65533;", "%93" : "&#65533;", \
>                     "%94" : "&#65533;", "%95" : "&#65533;", "%96" : 
> "&#65533;", "%97" : "&#65533;", \
> ...
>
> Which feels like an horrible kludge.
>   
This _characterCodes map replaces chars is the range 80-9F with a 
Unicode "undefined" marker, so I don't understand how using it gives you 
a correct result.
> Note that using urlilib.unquote doesn't do it -I get an error saying that it 
> is unable to . Replacing my decodeChars
>
> msg = MIMEText(urllib.unquote(body), 'plain', 'UTF-8')
>
> Returns content with i18n characters mangled.
>   
 From the selection of characters you have chosen to replace, my guess 
is that your source data is urlencoded Cp1252, not urlencoded UTF-8. So 
when you unquote it and then call it UTF-8, which is what the above code 
does, you get incorrect display. What happens if you change UTF-8 to 
Cp1252 in the call to MIMEText?
> Using unicode(body, 'latin-1').encode('utf-8') doesn't work either. Besides, 
> am I the only one to feel that if I want to encode something in UTF-8 it 
> doesn't feel intuitive to have to convert to latin-1 first and then encode?
>   
It doesn't work because the urlencoded text is ascii, not latin-1. I 
suspect that
  unicode(urllib.unquote(body), 'Cp12521).decode('UTF-8')
would give you what you want.
> Any ideas? I am dry on other option and really don't want to keep my kludge 
> (unless I absolutely have to)
>   
Post some of your actual data, it will be obvious whether it is encoded 
from Cp1252 or UTF-8.

Keep trying, it's worth it to actually understand what is going on. 
Trying to solve encoding problems when you don't understand the basic 
issues is unlikely to give a good solution.

Kent


From kent37 at tds.net  Mon Aug 14 14:00:53 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 14 Aug 2006 08:00:53 -0400
Subject: [Tutor] how to remove html ags
In-Reply-To: <20060812091431.74868.qmail@web55905.mail.re3.yahoo.com>
References: <20060812091431.74868.qmail@web55905.mail.re3.yahoo.com>
Message-ID: <44E065F5.3090209@tds.net>

anil maran wrote:
> <p><div class="quote">Human nature is not a machin... 
> <http://feeds.feedburner.com/Caterinanet?m=1228>
>
> for example in the above stirng
>
> i want to remove <p>
> and <div class="quote">
Try one of these:
http://www.oluyede.org/blog/2006/02/13/html-stripper/
http://www.aminus.org/rbre/python/cleanhtml.py
>
> i tried
>
> str = str.replace('(.*)','')
>
> it doesnt work
because it looks for a literal "(.*)" in the string and replaces it with 
an empty string. Since "(.*)" doesn't appear, nothing is replaced.

Kent
> thanks
>
> ------------------------------------------------------------------------
> Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great 
> rates starting at 1?/min. 
> <http://us.rd.yahoo.com/mail_us/taglines/postman7/*http://us.rd.yahoo.com/evt=39666/*http://messenger.yahoo.com> 
>
>
>  <http://us.rd.yahoo.com/mail_us/taglines/postman7/*http://us.rd.yahoo.com/evt=39666/*http://messenger.yahoo.com>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>  <http://us.rd.yahoo.com/mail_us/taglines/postman7/*http://us.rd.yahoo.com/evt=39666/*http://messenger.yahoo.com>



From kent37 at tds.net  Mon Aug 14 14:11:15 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 14 Aug 2006 08:11:15 -0400
Subject: [Tutor] SGMLLib, fetching some weird data
In-Reply-To: <44DDBB52.5080906@yandex.ru>
References: <44DDBB52.5080906@yandex.ru>
Message-ID: <44E06863.4040201@tds.net>

Basil Shubin wrote:
> Hi friends,
>
> Please, examine attached script. I want fetch some data from online 
> resource and almost achieve this, but I can't fetch some weird formatted 
> data like this '45? Reverse Calf Press'. I got the following error:
>
> 45
>   Reverse Calf Press
> Reverse Calf Raise
> Seated Reverse Calf Press
> Traceback (most recent call last):
>    File "net_exrx.py", line 226, in ?
>      exercisesList = LoadExercisesList(2, 4, 9)
>    File "net_exrx.py", line 86, in LoadExercisesList
>      return parser.GetExercisesList()
>    File "net_exrx.py", line 176, in GetExercisesList
>      self.exerList.append([self.desc[i],self.urls[i]])
> IndexError: list index out of range
>   
Apparently self.desc has more entries than self.urls. This would happen 
if handle_data() is called more than once for an <a> tag. If you put 
some print statements in your program you can probably figure out why 
this is happening.

Kent


From matthew.williams at cancer.org.uk  Mon Aug 14 16:10:19 2006
From: matthew.williams at cancer.org.uk (Matt Williams)
Date: Mon, 14 Aug 2006 15:10:19 +0100
Subject: [Tutor] Regex
Message-ID: <44E0844B.7080307@cancer.org.uk>

Dear All,

I know this has come up loads of times before, but I'm stuck with what 
should be a simple Regex problem. I'm trying to pull all the definitions 
  from a latex document. these are marked

\begin{defn}
<TEXT>
\end{defn}

so I thought I'd write something like this:

filename = '/home/acl_home/PhD/CurrentPhD/extensions1_14.8.6.tex'

infile = open(filename,'r')

def_start = "\\begin\{defn\}"
def_end = "\end{defn}"

def_start_reg = re.compile(def_start)

l = 0
while l < 500:
     line = infile.readline()
     #print l, line
     res = re.search(def_start_reg,line)
     print l, res
     l = l+1

but it doesn't return any matches (BTW, I know there's a defn tag in 
that section). I thought it was my regex matching, but I checked it with 
an online checker, and also with a small bit of text:


def_start = "\\begin\{defn\}"

def_start_reg = re.compile(def_start)

text = """atom that is grounded. These formulae are useful not only for the
work on valuation but are also used in later chapters.

\begin{defn}
A Patient-ground formula is a formula which contains a grounding of
$Patient(x)$. The other atoms in the formula may be either ground
or non-ground.
\end{defn}
Having defined our patient ground formulae, we can now use formulae
of this form to define our patient values."""

res = re.search(def_start_reg, text)
print res



and this returns a MatchObject. I'm not sure why there should be any 
difference between the two - but I'm sure it's very simple.

Thanks for any tips,

Matt

From rdm at rcblue.com  Mon Aug 14 16:35:44 2006
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 14 Aug 2006 07:35:44 -0700
Subject: [Tutor] How to un-import modules?
Message-ID: <7.0.1.0.2.20060814072726.05946c20@rcblue.com>

Actually, my question is, after using IDLE to do some importing of 
modules and initializing of variables, how to return it to it's 
initial condition without closing and reopening it.

So, for example after I've done
 >>> import math, psyco
 >>> a = 4**23

How can I wipe those out without closing IDLE?
(I used to know how, but I've forgotten.)

Thanks,

Dick Moores
rdm at rcblue.com


From kermit at polaris.net  Mon Aug 14 16:47:06 2006
From: kermit at polaris.net (Kermit Rose)
Date: Mon, 14 Aug 2006 10:47:06 -0400 (Eastern Daylight Time)
Subject: [Tutor] Global variables
References: <44DFDFD5.2080208@gmail.com>
Message-ID: <44E08CEA.000001.02432@YOUR-4105E587B6>

 
 
From: Luke Paireepinart 
Date: 08/13/06 22:28:50 
To: Kermit Rose 
Cc: Danny Yoo; tutor at python.org 
Subject: Re: [Tutor] Global variables 
 
Kermit Rose wrote: 
> 
> 
> From: Danny Yoo 
> Date: 08/09/06 16:23:35 
> To: Kermit Rose 
> Cc: tutor at python.org 
> 
> 
> If I can figure out how to make my main function subroutine declare global

> variables 
> then I won't need to pass parameters most parameters to the other 
> subroutines, 
> 
> and will bypass the problem I'm having that sometimes the function
strongfac 
> SOMETIMES does not return the value it has in the subroutine, back to the 
> calling routine. 
> 
 
From: Luke Paireepinart 
 
are you asking a question?
 
 
Kermit Rose wrote: 
 
 
Yes.   How can I make a package of functions declare global variables for
passing information between
the functions in the package?
 
 
 
 
 
 
 
 
 


From arcege at gmail.com  Mon Aug 14 17:46:08 2006
From: arcege at gmail.com (Michael P. Reilly)
Date: Mon, 14 Aug 2006 11:46:08 -0400
Subject: [Tutor] How to un-import modules?
In-Reply-To: <7.0.1.0.2.20060814072726.05946c20@rcblue.com>
References: <7.0.1.0.2.20060814072726.05946c20@rcblue.com>
Message-ID: <7e5ba9220608140846s47feffb7x8569ee5bfe6be5c6@mail.gmail.com>

On 8/14/06, Dick Moores <rdm at rcblue.com> wrote:
>
> Actually, my question is, after using IDLE to do some importing of
> modules and initializing of variables, how to return it to it's
> initial condition without closing and reopening it.
>
> So, for example after I've done
> >>> import math, psyco
> >>> a = 4**23
>
> How can I wipe those out without closing IDLE?
> (I used to know how, but I've forgotten.)


Hi Dick,
  Usually this entails removing from the "module registry and removing
references to it in the code.  If you have a _really_ well used module (like
one with config parameters imported into every module), then you'll have an
additional step of removing it from every module.  Also, if you have use
"from psyco import ...", then you will not be able to free up the module and
the reference to the module easily (is it from that module, or imported from
a third module? see "if paranoid: code below).

The function below deletes a module by name from the Python interpreter, the
"paranoid" parameter is a list of variable names to remove from every other
module (supposedly being deleted with the module).  Be VERY careful with the
paranoid param; it could cause problems for your interpreter if your
functions and classes are named the same in different modules.  One common
occurrance of this is "error" for exceptions.  A lot of libraries have one
"catch-all" exception called "error" in the module.  If you also named your
exception "error" and decided to include that in the paranoid list... there
go a lot of other exception objects.

def delete_module(modname, paranoid=None):
    from sys import modules
    try:
        thismod = modules[modname]
    except KeyError:
        raise ValueError(modname)
    these_symbols = dir(thismod)
    if paranoid:
        try:
            paranoid[:]  # sequence support
        except:
            raise ValueError('must supply a finite list for paranoid')
        else:
            these_symbols = paranoid[:]
    del modules[modname]
    for mod in modules.values():
        try:
            delattr(mod, modname)
        except AttributeError:
            pass
        if paranoid:
            for symbol in these_symbols:
                if symbol[:2] == '__':  # ignore special symbols
                    continue
                try:
                    delattr(mod, symbol)
                except AttributeError:
                    pass

Then you should be able to use this like:

delete_module('psyco')
  or
delete_module('psyco', ['Psycho', 'KillerError'])  # only delete these
symbols from every other module (for "from psyco import Psycho, KillerError"
statements)

  -Arcege

-- 
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060814/4709e976/attachment.html 

From anilmrn at yahoo.com  Mon Aug 14 22:27:05 2006
From: anilmrn at yahoo.com (anil maran)
Date: Mon, 14 Aug 2006 13:27:05 -0700 (PDT)
Subject: [Tutor] how to remove html ags
In-Reply-To: <44E065F5.3090209@tds.net>
Message-ID: <20060814202705.55898.qmail@web55905.mail.re3.yahoo.com>

how to do regular expressions
and remove waht is in and also the brackets
<>

Kent Johnson <kent37 at tds.net> wrote: anil maran wrote:
> 
Human nature is not a machin... 
> 
>
> for example in the above stirng
>
> i want to remove 
> and 

Try one of these:
http://www.oluyede.org/blog/2006/02/13/html-stripper/
http://www.aminus.org/rbre/python/cleanhtml.py
>
> i tried
>
> str = str.replace('(.*)','')
>
> it doesnt work
because it looks for a literal "(.*)" in the string and replaces it with 
an empty string. Since "(.*)" doesn't appear, nothing is replaced.

Kent
> thanks
>
> ------------------------------------------------------------------------
> Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great 
> rates starting at 1?/min. 
>  
>
>
>  
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>  


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




 		
---------------------------------
Do you Yahoo!?
 Get on board. You're invited to try the new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060814/f9b9b230/attachment-0001.htm 

From rabidpoobear at gmail.com  Mon Aug 14 23:17:09 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 14 Aug 2006 16:17:09 -0500
Subject: [Tutor] Global variables
In-Reply-To: <44E08CEA.000001.02432@YOUR-4105E587B6>
References: <44DFDFD5.2080208@gmail.com>
	<44E08CEA.000001.02432@YOUR-4105E587B6>
Message-ID: <44E0E855.1070007@gmail.com>


> From: Luke Paireepinart 
>  
> are you asking a question?
>  
>  
> Kermit Rose wrote: 
>  
>  
> Yes.   How can I make a package of functions declare global variables for
> passing information between
> the functions in the package?
>  
>   
a 'package' meaning a module?
If you think you need global variables you're probably going about the 
problem the wrong way.
What are you trying to do?

From rabidpoobear at gmail.com  Mon Aug 14 23:19:44 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 14 Aug 2006 16:19:44 -0500
Subject: [Tutor] How to un-import modules?
In-Reply-To: <7e5ba9220608140846s47feffb7x8569ee5bfe6be5c6@mail.gmail.com>
References: <7.0.1.0.2.20060814072726.05946c20@rcblue.com>
	<7e5ba9220608140846s47feffb7x8569ee5bfe6be5c6@mail.gmail.com>
Message-ID: <44E0E8F0.3070909@gmail.com>

Michael P. Reilly wrote:
> On 8/14/06, *Dick Moores* <rdm at rcblue.com <mailto:rdm at rcblue.com>> wrote:
>
>     Actually, my question is, after using IDLE to do some importing of
>     modules and initializing of variables, how to return it to it's
>     initial condition without closing and reopening it.
>
>     So, for example after I've done
>     >>> import math, psyco
>     >>> a = 4**23
>
>     How can I wipe those out without closing IDLE?
>     (I used to know how, but I've forgotten.)
>
while you're in the IDLE shell view, hit Ctrl+F6.  it restarts the 
interpreter.


From rabidpoobear at gmail.com  Mon Aug 14 23:25:03 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 14 Aug 2006 16:25:03 -0500
Subject: [Tutor] how to remove html ags
In-Reply-To: <20060814202705.55898.qmail@web55905.mail.re3.yahoo.com>
References: <20060814202705.55898.qmail@web55905.mail.re3.yahoo.com>
Message-ID: <44E0EA2F.2050701@gmail.com>

anil maran wrote:
> how to do regular expressions
> and remove waht is in and also the brackets
> <>
I'm not answering any more of your questions until you read 
http://www.catb.org/~esr/faqs/smart-questions.html
The information you want you could find in any regexp tutorial.
If you have a problem learning regular expressions and you need 
clarification about something, ask us.
This list is here to help you learn and understand the Python language, 
not to generate code for you.
:-).
-Luke

From anilmrn at yahoo.com  Tue Aug 15 00:08:27 2006
From: anilmrn at yahoo.com (anil maran)
Date: Mon, 14 Aug 2006 15:08:27 -0700 (PDT)
Subject: [Tutor] how to remove html ags
In-Reply-To: <44E0EA2F.2050701@gmail.com>
Message-ID: <20060814220827.52188.qmail@web55904.mail.re3.yahoo.com>

hi luke
i tried to do this for 2 weeks using the regexps
i couldnt find it
and hence i was asking you guys
thanks
anil

Luke Paireepinart <rabidpoobear at gmail.com> wrote: anil maran wrote:
> how to do regular expressions
> and remove waht is in and also the brackets
> <>

 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1&cent;/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060814/cc72c305/attachment.html 

From john at fouhy.net  Tue Aug 15 00:15:05 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 15 Aug 2006 10:15:05 +1200
Subject: [Tutor] how to remove html ags
In-Reply-To: <20060814220827.52188.qmail@web55904.mail.re3.yahoo.com>
References: <44E0EA2F.2050701@gmail.com>
	<20060814220827.52188.qmail@web55904.mail.re3.yahoo.com>
Message-ID: <5e58f2e40608141515l1a67b7d6t85c20a0327e41206@mail.gmail.com>

On 15/08/06, anil maran <anilmrn at yahoo.com> wrote:
> hi luke
> i tried to do this for 2 weeks using the regexps
> i couldnt find it
> and hence i was asking you guys
> thanks
> anil

What have you tried?  What problems were you having?

-- 
John.

From alan.gauld at freenet.co.uk  Tue Aug 15 00:32:33 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 14 Aug 2006 23:32:33 +0100
Subject: [Tutor] Regex
References: <44E0844B.7080307@cancer.org.uk>
Message-ID: <001101c6bff1$897bbfd0$0201a8c0@XPpro>

> so I thought I'd write something like this:
> 
> filename = '/home/acl_home/PhD/CurrentPhD/extensions1_14.8.6.tex'
> 
> infile = open(filename,'r')
> 
> def_start = "\\begin\{defn\}"
> def_end = "\end{defn}"
> 
> def_start_reg = re.compile(def_start)
> 
> l = 0
> while l < 500:
>     line = infile.readline()
>     #print l, line
>     res = re.search(def_start_reg,line)
>     print l, res
>     l = l+1

Use a for loop instead of the while loop.
And use the methods of the compiled regex object:

for n,line in enumerate(open(filename)):
    res = def_start_reg.search(line)
    print n,res

Does that work?

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


From alan.gauld at freenet.co.uk  Tue Aug 15 00:40:28 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 14 Aug 2006 23:40:28 +0100
Subject: [Tutor] How to un-import modules?
References: <7.0.1.0.2.20060814072726.05946c20@rcblue.com>
	<7e5ba9220608140846s47feffb7x8569ee5bfe6be5c6@mail.gmail.com>
Message-ID: <002b01c6bff2$ac42af00$0201a8c0@XPpro>

>> Actually, my question is, after using IDLE to do some importing of
>> modules and initializing of variables, how to return it to it's
>> initial condition without closing and reopening it.

Doesn't Shell->Restart shell do this?

Alan G.


From alan.gauld at freenet.co.uk  Tue Aug 15 00:39:15 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 14 Aug 2006 23:39:15 +0100
Subject: [Tutor] Global variables
References: <44DFDFD5.2080208@gmail.com>
	<44E08CEA.000001.02432@YOUR-4105E587B6>
Message-ID: <001701c6bff2$79646010$0201a8c0@XPpro>

>> If I can figure out how to make my main function subroutine declare 
>> global
>> variables then I won't need to pass parameters most parameters to 
>> the other
>> subroutines,

That may be true but you will make your code much less reusable
and much more error propne in the process. There are good reasons
why global variables are considered evil...

>> and will bypass the problem I'm having that sometimes the function
> strongfac SOMETIMES does not return the value it has in the 
> subroutine,
> back to the calling routine.

I'm not sure how you work that out. If the function uis getting bad 
data
it will still return it regardless of whether you use golobals or 
return values.

> Yes.   How can I make a package of functions declare global 
> variables for
> passing information between the functions in the package?

just use the global keyword:

###############
x,y = 42,27

def f():
   global x,y
   x = 66
   y = 42
   print x+y

print x,y
f()
print x,y
############

But its very bad practice and

##############
x,y = 42,27
def f(x,y):
    x = 66
    y = 42
    print x+y
    return x,y

print x,y
x,y = f(x,y)
print x,y
##########

is much better.

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


From kermit at polaris.net  Tue Aug 15 00:51:43 2006
From: kermit at polaris.net (Kermit Rose)
Date: Mon, 14 Aug 2006 18:51:43 -0400 (Eastern Daylight Time)
Subject: [Tutor] Global variables
References: <44E0E855.1070007@gmail.com>
Message-ID: <44E0FE7F.00000D.02432@YOUR-4105E587B6>

 
From: Luke Paireepinart 
Date: 08/14/06 17:17:13 
To: Kermit Rose 
Cc: Danny Yoo; tutor at python.org 
Subject: Re: [Tutor] Global variables 
 
 
> From: Luke Paireepinart 
> 
> are you asking a question? 
> 
> 
> Kermit Rose wrote: 
> 
> 
> Yes. How can I make a package of functions declare global variables for 
> passing information between 
> the functions in the package? 
> 
> 
a 'package' meaning a module? 
 
****
 
Yes.  I mean a module.
 
 
>>>>>
 
If you think you need global variables you're probably going about the 
problem the wrong way. 
What are you trying to do? 
 
*****
 
In my module I have several functions which work together to factor integers

 
One function, called testrange is the  main calling routine.
 
It generates Tables and and passes their values to the main factoring
subroutine, named 
fermat.
 
Fermat calls a routine named strongfac.
 
There seems to be some type of bug in Python because
 
I observe that 
strongfac, depending on the number being factored,
will sometimes return  0 instead of the  factors it found.
 
I believe that if I can get my main function, testrange,
to declare a global variable to hold the caculated factor list,
then I can bypass the apparent bug in Python that actualizes only
for  a few particular  numbers to be factored.
 
Also, if I can get testrange to create global variables, then I can shorten
the parameter list of many of the
functions in the module.
 
 
Kermit   <  kermit at polaris.net  >
 
 
 


From kermit at polaris.net  Tue Aug 15 01:33:16 2006
From: kermit at polaris.net (Kermit Rose)
Date: Mon, 14 Aug 2006 19:33:16 -0400 (Eastern Daylight Time)
Subject: [Tutor] Global variables
References: <001701c6bff2$79646010$0201a8c0@XPpro>
Message-ID: <44E1083C.000015.02432@YOUR-4105E587B6>

 
 
From: Alan Gauld 
Date: 08/14/06 18:42:41 
To: Kermit Rose; Luke Paireepinart 
Cc: tutor at python.org; Danny Yoo 
Subject: Re: [Tutor] Global variables 
 
 
That may be true but you will make your code much less reusable 
and much more error propne in the process. There are good reasons 
why global variables are considered evil... 
 
 
*****
 
I know that global variable usage can be abused.
 
But in fact I use the same variable names  in the subroutine parameter list
as in the calling routine for every function in the module.
 
So I believe that in this case global variables would be useful and not
likely to
increase errors due to confusion of global and local variables.
 
I would never have a local variable with the same name as the global
variable.
 
But in this case, it's only because of an apparent bug in Python that want
to 
bypass that I'm considering the use of global variables.
 
 
My routine strongfac calculates a value for fac in the subroutine, and the
calling routine picks up a different vaalue.
 
An illustration.
 
In strong fac:
 
fac = [1,2,3]
print fac
return fac
 
in fermat:
 
fac = strongfac(z)
print fac
 
prints [0,0,0]
 
And most of the time it does not misbehave like this.
 
It is only occasionally, and consistently with certain numbers to be
factored.
 
 
Kermit   <  kermit at polaris.net >
 
 
 
 


From john at fouhy.net  Tue Aug 15 01:50:47 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 15 Aug 2006 11:50:47 +1200
Subject: [Tutor] Global variables
In-Reply-To: <44E1083C.000015.02432@YOUR-4105E587B6>
References: <001701c6bff2$79646010$0201a8c0@XPpro>
	<44E1083C.000015.02432@YOUR-4105E587B6>
Message-ID: <5e58f2e40608141650m2a0347d5j581a0847daa806e5@mail.gmail.com>

On 15/08/06, Kermit Rose <kermit at polaris.net> wrote:
> My routine strongfac calculates a value for fac in the subroutine, and the
> calling routine picks up a different vaalue.
>
> An illustration.
>
> In strong fac:
>
> fac = [1,2,3]
> print fac
> return fac
>
> in fermat:
>
> fac = strongfac(z)
> print fac
>
> prints [0,0,0]
>
> And most of the time it does not misbehave like this.

Can you post actual code to illustrate the problem?  Don't post your
entire module; just show us the functions involved, the input that
causes the problem, and what output you expect to get.

-- 
John.

From rabidpoobear at gmail.com  Tue Aug 15 02:18:34 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 14 Aug 2006 19:18:34 -0500
Subject: [Tutor] Global variables
In-Reply-To: <44E1083C.000015.02432@YOUR-4105E587B6>
References: <001701c6bff2$79646010$0201a8c0@XPpro>
	<44E1083C.000015.02432@YOUR-4105E587B6>
Message-ID: <44E112DA.3090502@gmail.com>

Kermit Rose wrote:
>  
>  
> From: Alan Gauld 
> Date: 08/14/06 18:42:41 
> To: Kermit Rose; Luke Paireepinart 
> Cc: tutor at python.org; Danny Yoo 
> Subject: Re: [Tutor] Global variables 
>  
>  
> That may be true but you will make your code much less reusable 
> and much more error propne in the process. There are good reasons 
> why global variables are considered evil... 
>  
>  
> *****
>  
> I know that global variable usage can be abused.
>  
> But in fact I use the same variable names  in the subroutine parameter list
> as in the calling routine for every function in the module.
>  
> So I believe that in this case global variables would be useful and not
> likely to
> increase errors due to confusion of global and local variables.
>  
> I would never have a local variable with the same name as the global
> variable.
>  
>   
It sounds like you should make a Factoring class and have whichever
variables are similar for all functions be variables specific to the 
class instance
(I forgot the word for this)

Something like:

#----
Class Factoring(object):
    def __init__(self):
       self.var1 = ['a','b','c']
       self.var2 = 5
       self.var3 = (0)

    def method1(self):
       print self.var1,self.var2
    def method2(self):
       print self.var2,self.var3

fac = Factoring()
fac.method1()
fac.method2()

#-----
the output would be
['a','b','c']5
5(0)

Thus you prevent global namespace pollution.
> But in this case, it's only because of an apparent bug in Python that want
> to 
> bypass that I'm considering the use of global variables.
>   
You probably shouldn't claim there's a bug in Python unless you're sure 
(I.E. have a snippet of code
that reproduces the bug that you'll share with us)
>  
>  
> My routine strongfac calculates a value for fac in the subroutine, and the
> calling routine picks up a different vaalue.
>   
do you think you could use more conventional terminology like 'function' 
and such?
I don't understand what you mean by the subroutine of the routine.
def routine():
    def subroutine():
       print 'hi'
    subroutine()

Is that what you mean?
or by 'subroutine' do you mean 'loop inside of function'?

By your terminology, if there's a routine that calls strongfac, doesn't 
that mean
strongfac is a subroutine?  which would mean that the value for fac is 
calculated in the subroutine of the subroutine of the calling routine?

>  
> An illustration.
>  
> In strong fac:
>  
> fac = [1,2,3]
> print fac
> return fac
>  
> in fermat:
>  
> fac = strongfac(z)
> print fac
>  
> prints [0,0,0]
>   
what is 'z'?  a random parameter?
can you give us a cut-down version of your code that just reproduces this
erratic behavior you're having a problem with?

>  
> And most of the time it does not misbehave like this.
>   
if random.randint(0,5) < 3:
    malfunction()
>  
> It is only occasionally, and consistently with certain numbers to be
> factored.
>   
so with certain numbers it always occurs, with other numbers it 
sometimes occurs?
>  
>  
> Kermit   <  kermit at polaris.net >
>  
>   
Luke

From bgailer at alum.rpi.edu  Tue Aug 15 02:24:06 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon, 14 Aug 2006 17:24:06 -0700
Subject: [Tutor] Global variables
Message-ID: <44E11426.2060700@alum.rpi.edu>

A while back you attached factor34.py. Is that the program you are 
having trouble with?
And you said it misbehaves "consistently with certain numbers to be 
factored."
What are these numbers?

-- 
Bob Gailer
510-978-4454


From dianahawks at optusnet.com.au  Tue Aug 15 03:19:35 2006
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Tue, 15 Aug 2006 11:19:35 +1000
Subject: [Tutor] Python on network problems
Message-ID: <200608150119.k7F1JZ9O022639@mail31.syd.optusnet.com.au>

An embedded and charset-unspecified text was scrubbed...
Name: not available
Url: http://mail.python.org/pipermail/tutor/attachments/20060815/56d4318a/attachment.asc 

From jim at well.com  Tue Aug 15 04:11:31 2006
From: jim at well.com (jim stockford)
Date: Mon, 14 Aug 2006 19:11:31 -0700
Subject: [Tutor] What does import really do?
Message-ID: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com>


For example,
import os
import sys

    My take is that one uses the import keyword in a
program.
    The Python interpreter reads the program and
generates machine code.
    The import keyword directs the Python interpreter
to find some library (which is not necessarily named,
certainly not necessarily named in the import
statement), get some portion of machine code from
the library, bind that machine code in current
program's process space, and integrate the names
of the imported machine code with the program's
namespace (probably keeping the namespace of
the imported code as a separate name domain).

    I'm just guessing, of course. Can anyone explain
what is really going on under the hood? I'll be
grateful for a description of the behavior.

newbie


From reed at intersiege.com  Tue Aug 15 04:44:11 2006
From: reed at intersiege.com (Reed L. O'Brien)
Date: Mon, 14 Aug 2006 22:44:11 -0400
Subject: [Tutor] processing multi entry logs
Message-ID: <0A65F8F9-3545-46C4-BD93-64DF92383351@intersiege.com>

I have a log file. Essentially the file has 2 important entries for  
each process id. One when the process starts with an id and a another  
piece of data. the second is when the process finishes, with the  
result also with the process id. I need to get data from both to make  
a sensible representation of the data. The file can be very large, in  
excess of 400MB. And the process id entries can be any random  
distance apart.

I am hoping for input regarding the best way to do it.

I can't think of an efficient way to store the data from the first  
entry.

Keep processing line by line and check against the partially recorded  
ids?


Maintain seperate lists and merge them at the end?


Ideas and input appreciated?

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

From rabidpoobear at gmail.com  Tue Aug 15 04:52:19 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 14 Aug 2006 21:52:19 -0500
Subject: [Tutor] What does import really do?
In-Reply-To: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com>
References: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com>
Message-ID: <44E136E3.1020307@gmail.com>

jim stockford wrote:
Hi Jim.
> For example,
> import os
> import sys
>
>     My take is that one uses the import keyword in a
> program.
>     The Python interpreter reads the program and
> generates machine code.
>     The import keyword directs the Python interpreter
> to find some library (which is not necessarily named,
> certainly not necessarily named in the import
> statement), get some portion of machine code from
> the library, bind that machine code in current
> program's process space, and integrate the names
> of the imported machine code with the program's
> namespace (probably keeping the namespace of
> the imported code as a separate name domain).
>   
I don't know when code is converted to machine code, but here's how I think
import works.
you say 'find some library ... not necessarily named in the import 
statement.'
I don't know what you mean by this.
If the user says 'import os'
first python checks for
'os.pyc' in the current working directory.
if it doesn't find this, it looks if 'os.py' is there.
If not, then it checks the PYTHONPATH (I believe)
for 'os.pyc' and 'os.py' files.

When the user says 'import x' the name of the
actual filename will be x.pyc or x.py
for example:

#---- config.py in C:/exprog
a = 'hi'
b = 'hello'
#----

#---- main.py in C:/exprog
import config
print config.a
print config.b
#----

when I run main.py for the first time, it looks for
'config.pyc' because of the 'import config' line.
It doesn't find it, so it compiles 'config.py' into 'config.pyc'
and then imports it.  Note that it's not in the global namespace
unless I say 'from config import *'
instead, you have to reference values stored in the 'config' module
using the 'config. ' syntax.

if I were to delete config.py and config.pyc, it would look in
C:/python24/Lib/site-packages/ for a 'config.py' and 'config.pyc'
because that's where my python is installed.

At least that's how I think import works :)
>     I'm just guessing, of course. Can anyone explain
> what is really going on under the hood? I'll be
> grateful for a description of the behavior.
>
> newbie
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From rabidpoobear at gmail.com  Tue Aug 15 05:02:37 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 14 Aug 2006 22:02:37 -0500
Subject: [Tutor] processing multi entry logs
In-Reply-To: <0A65F8F9-3545-46C4-BD93-64DF92383351@intersiege.com>
References: <0A65F8F9-3545-46C4-BD93-64DF92383351@intersiege.com>
Message-ID: <44E1394D.4000702@gmail.com>

Reed L. O'Brien wrote:
> I have a log file. Essentially the file has 2 important entries for 
> each process id. One when the process starts with an id and a another 
> piece of data. the second is when the process finishes, with the 
> result also with the process id. I need to get data from both to make 
> a sensible representation of the data. The file can be very large, in 
> excess of 400MB. And the process id entries can be any random distance 
> apart.
>
Are you in control of the format of the log file?  Is it possible that, 
in the future, you could instead log everything in an SQL table or 
something of the sort
to make it easier to get at the data you want?
I understand that now you have a log that you need to parse, but if 
every time you need something from the log you have to parse 400MB of text
it might take a little longer than you'd like.

> I am hoping for input regarding the best way to do it.
>
> I can't think of an efficient way to store the data from the first entry. 
>
> Keep processing line by line and check against the partially recorded ids?
>
>
> Maintain seperate lists and merge them at the end?

You could do something like (in semi-python)
tasks = {}
for item in logfile.readlines():
    if item is start_data:
       tasks[process_id] = [start_data-process_id]
    elif item is end_data:
       tasks[process_id].append(end_data-process_id)

This should work because you said the process_id is common to both the 
startdata and enddata.
The only problem is determining if the entry is start or end data.

Now you have a dictionary where the keywords are the processids and the 
data is
a two-element list.
Does that do what you need?
HTH,
-Luke

From jim at well.com  Tue Aug 15 05:11:28 2006
From: jim at well.com (jim stockford)
Date: Mon, 14 Aug 2006 20:11:28 -0700
Subject: [Tutor] What does import really do?
In-Reply-To: <44E136E3.1020307@gmail.com>
References: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com>
	<44E136E3.1020307@gmail.com>
Message-ID: <BE5585AA-2C0B-11DB-B3EC-000A95EA5592@well.com>


many thanks.
    wrt import and what's named, in the case of
the PIL library, the import statement can be
import Image # not import PIL
    my presumption is that the PIL whatever-it-is
contains a set of whatever-they-are, one of
which is named Image.
    I like to use proper terminology, by way of
explaining my avoidance above. Might help
to know I very much liked working in assembler
and infer possible assembler correspondences
when I wonder about code behavior.
    Your rundown of search order is helpful.
more thanks.
jim


On Aug 14, 2006, at 7:52 PM, Luke Paireepinart wrote:

> jim stockford wrote:
> Hi Jim.
>> For example,
>> import os
>> import sys
>>
>>     My take is that one uses the import keyword in a
>> program.
>>     The Python interpreter reads the program and
>> generates machine code.
>>     The import keyword directs the Python interpreter
>> to find some library (which is not necessarily named,
>> certainly not necessarily named in the import
>> statement), get some portion of machine code from
>> the library, bind that machine code in current
>> program's process space, and integrate the names
>> of the imported machine code with the program's
>> namespace (probably keeping the namespace of
>> the imported code as a separate name domain).
>>
> I don't know when code is converted to machine code, but here's how I 
> think
> import works.
> you say 'find some library ... not necessarily named in the import 
> statement.'
> I don't know what you mean by this.
> If the user says 'import os'
> first python checks for
> 'os.pyc' in the current working directory.
> if it doesn't find this, it looks if 'os.py' is there.
> If not, then it checks the PYTHONPATH (I believe)
> for 'os.pyc' and 'os.py' files.
>
> When the user says 'import x' the name of the
> actual filename will be x.pyc or x.py
> for example:
>
> #---- config.py in C:/exprog
> a = 'hi'
> b = 'hello'
> #----
>
> #---- main.py in C:/exprog
> import config
> print config.a
> print config.b
> #----
>
> when I run main.py for the first time, it looks for
> 'config.pyc' because of the 'import config' line.
> It doesn't find it, so it compiles 'config.py' into 'config.pyc'
> and then imports it.  Note that it's not in the global namespace
> unless I say 'from config import *'
> instead, you have to reference values stored in the 'config' module
> using the 'config. ' syntax.
>
> if I were to delete config.py and config.pyc, it would look in
> C:/python24/Lib/site-packages/ for a 'config.py' and 'config.pyc'
> because that's where my python is installed.
>
> At least that's how I think import works :)
>>     I'm just guessing, of course. Can anyone explain
>> what is really going on under the hood? I'll be
>> grateful for a description of the behavior.
>>
>> newbie
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>


From cspears2002 at yahoo.com  Tue Aug 15 08:42:37 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Mon, 14 Aug 2006 23:42:37 -0700 (PDT)
Subject: [Tutor] more rps
Message-ID: <20060815064237.80516.qmail@web51614.mail.yahoo.com>

Here is the latest version of my Rock, Paper, Scissors
game:

#!/usr/bin/python

import random
random.seed()

class Human:
	def __init__(self):
		self.points = 0
		self.choice = " "
		
	def plays(self):
		fromUser = raw_input("Pick (R)ock, (P)aper, or
(S)cissors! ")
		translate = {'r':'rock', 's':'scissors',
'p':'paper'} 
		try:
			self.choice = translate[fromUser.lower()]
		except KeyError:
			print 'Invalid Response'
	
class Computer:
	def __init__(self):
		self.points = 0
		self.choice = " "
	
	def plays(self):
		comp_choice = random.randint(0,2)
		if comp_choice == 0:
			self.choice = 'rock'
		elif comp_choice == 1:
			self.choice = 'paper'
		else:
			self.choice = 'scissors'
			
def compare_objects(human, computer):
	print "Human picked ", human.choice
	print "Computer picked", computer.choice
	results = { 'rock' : {'rock' : 'draw', 'paper': 0,
'scissors': 1},
		'paper' : {'rock' : 1, 'paper': 'draw', 'scissors':
0},
		'scissors' : {'rock' : 0, 'paper' : 1, 'scissors' :
'draw'}
		}
		
	outcome = results[human.choice][computer.choice]
	if outcome == 0:
		print "Computer Wins!"
		computer.points = computer.points + 1
	elif outcome == 1:
		print "Human Wins!"
		human.points = human.points + 1
	else:
		print "Draw!"
		

if __name__ == "__main__":
	print "Welcome to Rock, Paper, Scissors!"
	final_points = raw_input("Play to how many points? ")
	human = Human()
	computer = Computer()
	while (human.points < final_points or computer.points
< final_points):
		human.plays()
		computer.plays()
		compare_objects(human, computer)
		print "Score:\tHuman: ",human.points,"\tComputer:
",computer.points
	print "Game Over!"
	
	
I actually figured out how to build the 2x2 matrix. 
I'm quite proud of this.  Like all of my good ideas,
the answer came to me in the shower. :-)

Unfortunately, my while loop doesn't seem to be
working.  I've played around with it with no success. 
Hints, anyone?


From rdm at rcblue.com  Tue Aug 15 08:58:58 2006
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 14 Aug 2006 23:58:58 -0700
Subject: [Tutor] How to un-import modules?
In-Reply-To: <44E0E8F0.3070909@gmail.com>
References: <7.0.1.0.2.20060814072726.05946c20@rcblue.com>
	<7e5ba9220608140846s47feffb7x8569ee5bfe6be5c6@mail.gmail.com>
	<44E0E8F0.3070909@gmail.com>
Message-ID: <7.0.1.0.2.20060814235628.05a68540@rcblue.com>

At 02:19 PM 8/14/2006, you wrote:
>Michael P. Reilly wrote:
>>On 8/14/06, *Dick Moores* <rdm at rcblue.com <mailto:rdm at rcblue.com>> wrote:
>>
>>     Actually, my question is, after using IDLE to do some importing of
>>     modules and initializing of variables, how to return it to it's
>>     initial condition without closing and reopening it.
>>
>>     So, for example after I've done
>>     >>> import math, psyco
>>     >>> a = 4**23
>>
>>     How can I wipe those out without closing IDLE?
>>     (I used to know how, but I've forgotten.)
>while you're in the IDLE shell view, hit Ctrl+F6.  it restarts the 
>interpreter.

Yes! That's it. Or Shell->Restart. I should have poked around in IDLE 
and found this myself.

Thanks!

Dick Moores
rdm at rcblue.com




From kraus at hagen-partner.de  Tue Aug 15 09:01:57 2006
From: kraus at hagen-partner.de (Wolfram Kraus)
Date: Tue, 15 Aug 2006 09:01:57 +0200
Subject: [Tutor] more rps
In-Reply-To: <20060815064237.80516.qmail@web51614.mail.yahoo.com>
References: <20060815064237.80516.qmail@web51614.mail.yahoo.com>
Message-ID: <ebrrh5$jt1$1@sea.gmane.org>

On 15.08.2006 08:42, Christopher Spears wrote:
> Here is the latest version of my Rock, Paper, Scissors
> game:
> 
> #!/usr/bin/python
> 
> import random
> random.seed()
> 
> class Human:
> 	def __init__(self):
> 		self.points = 0
> 		self.choice = " "
> 		
> 	def plays(self):
> 		fromUser = raw_input("Pick (R)ock, (P)aper, or
> (S)cissors! ")
> 		translate = {'r':'rock', 's':'scissors',
> 'p':'paper'} 
> 		try:
> 			self.choice = translate[fromUser.lower()]
> 		except KeyError:
> 			print 'Invalid Response'
> 	
> class Computer:
> 	def __init__(self):
> 		self.points = 0
> 		self.choice = " "
> 	
> 	def plays(self):
> 		comp_choice = random.randint(0,2)
> 		if comp_choice == 0:
> 			self.choice = 'rock'
> 		elif comp_choice == 1:
> 			self.choice = 'paper'
> 		else:
> 			self.choice = 'scissors'
> 			
> def compare_objects(human, computer):
> 	print "Human picked ", human.choice
> 	print "Computer picked", computer.choice
> 	results = { 'rock' : {'rock' : 'draw', 'paper': 0,
> 'scissors': 1},
> 		'paper' : {'rock' : 1, 'paper': 'draw', 'scissors':
> 0},
> 		'scissors' : {'rock' : 0, 'paper' : 1, 'scissors' :
> 'draw'}
> 		}
> 		
> 	outcome = results[human.choice][computer.choice]
> 	if outcome == 0:
> 		print "Computer Wins!"
> 		computer.points = computer.points + 1
> 	elif outcome == 1:
> 		print "Human Wins!"
> 		human.points = human.points + 1
> 	else:
> 		print "Draw!"
> 		
> 
> if __name__ == "__main__":
> 	print "Welcome to Rock, Paper, Scissors!"
> 	final_points = raw_input("Play to how many points? ")
> 	human = Human()
> 	computer = Computer()
> 	while (human.points < final_points or computer.points
> < final_points):
> 		human.plays()
> 		computer.plays()
> 		compare_objects(human, computer)
> 		print "Score:\tHuman: ",human.points,"\tComputer:
> ",computer.points
> 	print "Game Over!"
> 	
> 	
> I actually figured out how to build the 2x2 matrix. 
> I'm quite proud of this.  Like all of my good ideas,
> the answer came to me in the shower. :-)
> 
> Unfortunately, my while loop doesn't seem to be
> working.  I've played around with it with no success. 
> Hints, anyone?
> 

Look at the type of human.points and final_points:

>>> final_points = raw_input("Play to how many points? ")
Play to how many points? 10
>>> type(final_points)
<type 'str'>
>>> 1 < final_points
True
>>> 100 < final_points
True
>>> 1000 < final_points
True

HTH,
Wolfram


From alan.gauld at freenet.co.uk  Tue Aug 15 09:37:05 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 15 Aug 2006 08:37:05 +0100
Subject: [Tutor] Global variables
References: <001701c6bff2$79646010$0201a8c0@XPpro>
	<44E1083C.000015.02432@YOUR-4105E587B6>
Message-ID: <000301c6c03d$9b8cc5b0$0201a8c0@XPpro>

> That may be true but you will make your code much less reusable
> and much more error propne in the process. There are good reasons
> why global variables are considered evil...
>
> But in fact I use the same variable names  in the subroutine 
> parameter list
> as in the calling routine for every function in the module.

The names have very little to do with it, the danger of global 
variable
use is the reliance on side-effects and the tight coupling that you
introduce between the calling module and the called module.
Changes to the state of the calling module in an unpredictable
manner lead to subtle bugs which are extremely hard to see and fix.

> increase errors due to confusion of global and local variables.

Confusion of names is of very little import, that really isn't the 
issue.

> I would never have a local variable with the same name as the global
> variable.

Again thats not a problem.

> But in this case, it's only because of an apparent bug in Python 
> that want
> to bypass that I'm considering the use of global variables.

I'd be very very doubtful that its a bug in Python.
Python is very well tested and while occasionally bugs do surface,
the type of bug you are describing is extremely unl;ikely to have
remained hidden. It is far more likely to be an error in the code
or in the data.

> My routine strongfac calculates a value for fac in the subroutine, 
> and the
> calling routine picks up a different vaalue.
>
> An illustration.
>
> In strong fac:
>
> fac = [1,2,3]
> print fac
> return fac
>
> in fermat:
>
> fac = strongfac(z)
> print fac
>
> prints [0,0,0]
>
> And most of the time it does not misbehave like this.
>
> It is only occasionally, and consistently with certain numbers to be
> factored.

All of which points to an error in the code not in Python.
The way Python is written it is virtually never going to result in
that kind of error dependant on data values. That might happen
is if the values are very close to zero and a type conversion
occurs, but otherwise I'm very dubious about a Python bug
of that type.

Alan G. 


From alan.gauld at freenet.co.uk  Tue Aug 15 09:46:02 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 15 Aug 2006 08:46:02 +0100
Subject: [Tutor] Python on network problems
References: <200608150119.k7F1JZ9O022639@mail31.syd.optusnet.com.au>
Message-ID: <000701c6c03e$dbac5f10$0201a8c0@XPpro>

Thanks Diana,

> We are running Windows XP.  The students log in to a
> network server that allows them access to their user
> accounts as well as various group folders.
> We have 4 rooms full of computers - but Python is installed
> on each workstation in this room only .... It is not on the network
> and no other computer rooms have access to it.

That's much clearer.

> Two failures have occurred.
>
> The first has been intermittent and to individual students
> only at rare times.  A student will attempt to start IDLE
> - and nothing will happen.

That could be a local machine/user setup issue.
Given the various issues with IDLE and firewalls I might
look at the firewall settings on the Python PCs and make
sure IDLE is happy with them.

> The 2nd is more pervasive, and that is, whenever I have
> the class working with Python - the entire school network
> becomes inoperable,

That is bizarre. And very unlikely to be Python since
they are running it frpom their local machine!

The only slight possibility is if any of the students are
writing code that accesses a networked folder, to open
a file say, and is causing some high volume network traffic.
Can you check if any of the students are using network
paths for file access in their code? Even this shouldn't
crash the network, but it can occasionally give rise to
problems - although I've never seen it from Python...


> Now I am inclined to think it is not a Python problem at all.

Me too, but coincidences shouldn't be dismissed lightly.

> What I would like to know is if anyone else has had
> a similar problem

Not with python.

Alan G. 


From alan.gauld at freenet.co.uk  Tue Aug 15 09:58:08 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 15 Aug 2006 08:58:08 +0100
Subject: [Tutor] processing multi entry logs
References: <0A65F8F9-3545-46C4-BD93-64DF92383351@intersiege.com>
Message-ID: <005101c6c040$8c7efbd0$0201a8c0@XPpro>


>I have a log file. Essentially the file has 2 important entries for
> each process id. One when the process starts with an id and a 
> another
> piece of data. the second is when the process finishes, with the
> result also with the process id.

> I can't think of an efficient way to store the data from the first
> entry.

This sounds like a job for a dictionary based on process Id.
You can store a tuple of start/stop times and key it by pid.

In pseudo code:

for line in logfile:
    pid,event,time = parseData(line)
    if event == start
        processes[pid] = [time,0]
    elif event == stop:
        processes[pid][1] = time

That throws all other events away and leaves you a dictionary
holding start and stop times per process id.

> Keep processing line by line and check against the partially 
> recorded
> ids?

Thats what I've done yes.

HTH,

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


From alan.gauld at freenet.co.uk  Tue Aug 15 18:49:07 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 15 Aug 2006 17:49:07 +0100
Subject: [Tutor] more rps
References: <20060815064237.80516.qmail@web51614.mail.yahoo.com>
Message-ID: <001f01c6c08a$b9feef30$0201a8c0@XPpro>

Let me start by saying that your code is pretty 
much OK as is. Indeed even using clssses for an 
RPS game is probably overkill to some extent.

What follows should be seen more as some ideas 
for experimentation and building towards a more 
flexible/expandable architecture for future 
projects. Its really about introducing some 
alternative approaches and increasing consistency.
It is definitely not "better" - and indeed could 
definitely be improved in several ways.

> class Human:
>   def __init__(self):
>     self.points = 0
>     self.choice = " "
> 
>   def plays(self):
>     fromUser = raw_input("Pick (R)ock, (P)aper, or
>               (S)cissors! ")
>     translate = {'r':'rock', 's':'scissors',
>               'p':'paper'} 
>     try:
>        self.choice = translate[fromUser.lower()]
>     except KeyError:
>        print 'Invalid Response'
> 
> class Computer:
>    def __init__(self):
>      self.points = 0
>      self.choice = " "
> 
>   def plays(self):
>     comp_choice = random.randint(0,2)
>     if comp_choice == 0:
>        self.choice = 'rock'
>     elif comp_choice == 1:
>        self.choice = 'paper'
>     else:
>       self.choice = 'scissors'

While its of little real advantage for this program 
I'd be tempted to introduce a Player superclass to avoid 
code duplication. The protocol of both classes 
here is the same and they both pass the "is-a" 
test for inheritance - ie. they are both Players.

class Player:
   def __init__(self):
     self.points = 0
     self.choice = " "

   def getChoice(self): pass   # implemented in subclass

   def plays(self):
     choice = self.getChoice()
     if choice == 0:
        self.choice = 'rock'
     elif choice == 1:
        self.choice = 'paper'
     else:
       self.choice = 'scissors'

Notice I put the plays function in the Player class.
By unifying the representation of choice we can use 
that function for both and just implement a 
relatively simple getChoice method in each subclass 
and we are done... (In fact we could simplify still 
further by storing the choice in its numeric form 
and using a class level dictionary to translate 
that to a string for printing - although in fact 
you never print what the choices were - maybe you 
should?)


class Human(Player):
   def getChoice(self):
      choice = raw_input('Choice - rps: ').lower()
      if choice in 'rps':
         return {'r':0,'p':1,'s':2}[choice]
      else: raise ValueError

class Computer(Player):
  def getChoice(self):
      return randrange(0,3)


> 
> def compare_objects(human, computer):
>   print "Human picked ", human.choice
>   print "Computer picked", computer.choice
>   results = { 'rock' : {'rock' : 'draw', 'paper': 0,
>                  'scissors': 1},
>                  'paper' : {'rock' : 1, 'paper': 'draw', 'scissors':
>                   0},
>                  'scissors' : {'rock' : 0, 'paper' : 1, 'scissors' :
>                  'draw'}
>              }
> 
>   outcome = results[human.choice][computer.choice]
>   if outcome == 0:
>     print "Computer Wins!"
>     computer.points = computer.points + 1
>   elif outcome == 1:
>     print "Human Wins!"
>     human.points = human.points + 1
>   else:
>     print "Draw!"

By using the number format of storage and the 
dictionary in the class you can simplify that
as in show below using lists.

> I actually figured out how to build the 2x2 matrix. 
> I'm quite proud of this.  

A nested dictionary is one way. Another is to use numbers 
to represent the choices and outcomes and create a nested 
list structure nested list

rps = {0:'Rock',1:'Paper',2:'Scissors'}
draw,loss,win = 0,1,2
outcomes = [ [0,1,2], [2,0,1], [1,2,0] ]

computer = randrange(0,3)
human = randrange(0,3)
result = outcomes[computer][human] 
if result == draw: print 'Draw'
elif result == loss: print 'Computer lost with', rps[computer]
elif result == win: print 'Computer won with', rps[computer]

The dictionary is more verbose but does have more readable
code.

I hope somebody finds at least some of that interesting! :-)
I guess what I'm really trying to show is how 
choosing different data structures makes a big 
difference to how the code looks.

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060815/d33a8c99/attachment.html 

From sfhaley at gmail.com  Tue Aug 15 19:07:11 2006
From: sfhaley at gmail.com (Steve Haley)
Date: Tue, 15 Aug 2006 13:07:11 -0400
Subject: [Tutor] The In Operator
In-Reply-To: <44C897DD.7040606@tds.net>
References: <f445d9050607262019v2ee66096wed45e6658354e6db@mail.gmail.com>
	<44C897DD.7040606@tds.net>
Message-ID: <f445d9050608151007q571e5b4cn50dfbd7f41dd6c09@mail.gmail.com>

Hi all,

I didn't forget about this - I got involved with some other things, was away
for a little while, etc.  Thanks for the help.  I have tried statements that
version 2.1 understands and the "in operator" (so to speak in ver. 21) works
fine.  As far as downloading a more recent version, I looked briefly at some
of the exchanges on the ESRI site and decided it looked a little tricky at
best.  I think I might wait for ArcView 9.2 and see what it ships with.

Thanks again,
Steve


On 7/27/06, Kent Johnson <kent37 at tds.net> wrote:
>
> Steve Haley wrote:
> > Finally, my version of 2.1 came bundled with other software (ESRI
> > ArcView).  Is anyone out there an ESRI user who can tell me if I can I
> > go ahead and download a newer version without messing up my ArcView
> > installation?
> Google is your friend:
> http://forums.esri.com/Thread.asp?c=93&f=1729&t=157014&mc=43
>
> http://support.esri.com/index.cfm?fa=knowledgebase.techarticles.articleShow&d=26872
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060815/cb44f590/attachment.htm 

From Barry.Carroll at psc.com  Tue Aug 15 20:21:00 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Tue, 15 Aug 2006 11:21:00 -0700
Subject: [Tutor] Python on network problems
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3702@eugsrv400.psc.pscnet.com>

Hello, Diana,

I have had a little experience with networking problems.  Here's my take
on your situation.  

Regards,
 

> Date: Tue, 15 Aug 2006 11:19:35 +1000
> From: Diana Hawksworth <dianahawks at optusnet.com.au>
> Subject: Re: [Tutor] Python on network problems
> To: Alan Gauld <alan.gauld at freenet.co.uk>
> Cc: tutor at python.org
> Message-ID: <200608150119.k7F1JZ9O022639 at mail31.syd.optusnet.com.au>
> Content-Type: text/plain
> 
<<snip>>
> 
> We are running Windows XP.  The students log in to a network server
that
> allows them access to their user accounts as well as various group
> folders.  We have 4 rooms full of computers - but Python is installed
on
> each workstation in this room only ie, it is "active" in this room
only.
> It is not on the network and no other computer rooms have access to
it.
> The students in this room save their Python files to a networked
"user"
> account - as they do with all their other files.
> 

>From your description, I gather that a single computer provides
authentication service and file service to the entire network.  Is this
correct?  If so, that machine is a single point of failure in your
network.  If it hangs for any reason, the entire network "goes away".  

> Two failures have occurred.
> 
> The first has been intermittent and to individual students only at
rare
> times.  A student will attempt to start IDLE - and nothing will
happen.
> Sometimes, changing that student's log in user name will solve the
> problem, and he then has access to Python again.
> 

I don't haven't used IDLE that much, so Alan's ideas are more reliable
than mine here:

>> That could be a local machine/user setup issue.
>> Given the various issues with IDLE and firewalls I might
>> look at the firewall settings on the Python PCs and make
>> sure IDLE is happy with them.

> The 2nd is more pervasive, and that is, whenever I have the class
working
> with Python - the entire school network becomes inoperable, and the
system
> administrator needs to reboot it again. Because we have been working
on
> Python each time this has happened, Python is being blamed for the
system
> failure. Inoperable - no one is able to open any files in any program,
> save any work they have been working on, open files - or even log in
if
> they haven't already. The whole system is " frozen", from the office
to
> every other computer in the school.

> Now I am inclined to think it is not a Python problem at all.  Python
is
> locally and individually installed on computers in this room only.  It
has
> no network access at all  - apart from files being saved in networked
user
> accounts.
> 

>> The only slight possibility is if any of the students are
>> writing code that accesses a networked folder, to open
>> a file say, and is causing some high volume network traffic. 

I think Alan is right here, too, and here's why. (Python internals
gurus, please correct any bad assumptions in the following.)  Lab #4 is
full of users running Python programs.  The interpreter is running on
each local machine, but the program (and data) files are all stored on
the lone network file server.  Since Python programs are executed by the
interpreter, they access file storage more heavily that compiled
programs do.  So, every time any of the (15, 20, 25?) computers in the
Python lab needs a file, or needs to save a file, it sends a request to
that one computer.  The potential bottleneck is obvious.  

I think the network server's capacity is being exceeded in some way.
When this happens, instead of degrading service gracefully (e.g.
rejecting a request and instructing the client to try again later) the
server is getting lost somehow and hanging, causing the failure modes
you describe.  

Here are some areas for your network administrator to investigate:

   * maximum number of concurrent disk access requests, 
   * maximum number of open files,
   * file server disk usage,
   * file server disk fragmentation,
   * server processor utilization, 
   * network bandwidth utilization,
   * other limits imposed by the networking software or the 
     server's hardware.

> What I would like to know is if anyone else has had a similar problem
-
> and it has been proven that Python is the cause?  If so - how was the
> problem solved?
> 

The best solution (IMHO) is also the most expensive: add a redundant
server to your network.  This would eliminate the single point of
failure weakness and reduce the load per server.  Also, is one server
should hang or fail for any other reason, the duplicate server can keep
the network running while the failed machine is rebooted, repaired, etc.


If possible, I would recommend using a Unix clone as your server's OS
instead of Windows.  Even Linux, which is available free of charge,
provides a more stable platform for a network server than does Windows.
This is relatively easy, especially if your network is based on TCP/IP.
Many Windows intranets use Unix/Linux servers.  The biggest obstacle, in
many cases, is the learning curve required of the network administrator.


> Be grateful for any advice - and hope I have made the situation
clearer
> now.
> 
> Diana
> 

HTH

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

-Quarry worker's creed



From rabidpoobear at gmail.com  Tue Aug 15 20:58:03 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 15 Aug 2006 13:58:03 -0500
Subject: [Tutor] more rps
In-Reply-To: <001f01c6c08a$b9feef30$0201a8c0@XPpro>
References: <20060815064237.80516.qmail@web51614.mail.yahoo.com>
	<001f01c6c08a$b9feef30$0201a8c0@XPpro>
Message-ID: <44E2193B.8010001@gmail.com>

[snip]
> > class Computer:
> >    def __init__(self):
> >      self.points = 0
> >      self.choice = " "
> >
> >   def plays(self):
> >     comp_choice = random.randint(0,2)
> >     if comp_choice == 0:
> >        self.choice = 'rock'
> >     elif comp_choice == 1:
> >        self.choice = 'paper'
> >     else:
> >       self.choice = 'scissors'

this could be shortened to 'comp_choice = 
random.choice(['rock','paper','scissors'])'

From alan.gauld at freenet.co.uk  Tue Aug 15 22:03:23 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 15 Aug 2006 21:03:23 +0100
Subject: [Tutor] Python on network problems
References: <2BBAEE949D384D40A2B851287ADB6A432C3702@eugsrv400.psc.pscnet.com>
Message-ID: <001c01c6c0a5$dd692470$0201a8c0@XPpro>

> If possible, I would recommend using a Unix clone as your 
> server's OS instead of Windows.  Even Linux, 

Speaking personally I can't complain about Windows 
as a server since windows 2000. NT was horrible but 
Win2K seems to do a fair job.

BUT it does need to be set up correctly and running 
XP Home doesn't count! It is terrible as a server.
However given the number of machines in your network 
I'd expect the basics to bbe catered for. The borttleneck 
issue that Barry alludes to is one I hadn't even considered 
but its valid. If the students are all writing code for a similar 
example and that cpde imports lots of modules which are 
stored on shared disk on a single server then it could 
throttle the network. Similarly if they are all accessing 
a single database or web server stored on the main 
server - that'd be a pretty bad network setup however!

> the learning curve required of the network administrator.

And thats pretty massive. Many Windows admins can't 
work without the GUI tools and Linux really needs 
command line skills to get the best out of it. Even editing 
a text file is intimidating for some of these guys!

Alan G.

From bgailer at alum.rpi.edu  Tue Aug 15 22:43:46 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 15 Aug 2006 13:43:46 -0700
Subject: [Tutor] more rps
In-Reply-To: <001f01c6c08a$b9feef30$0201a8c0@XPpro>
References: <20060815064237.80516.qmail@web51614.mail.yahoo.com>
	<001f01c6c08a$b9feef30$0201a8c0@XPpro>
Message-ID: <44E23202.1070108@alum.rpi.edu>

FWIF Here's my "minimalist" version:
# rock paper scissors
import random
media = ('rock', 'paper', 'scissors')
outcome = ('tie', 'human', 'computer')
winner = ((0,2,1), (1,0,2), (1,2,0))
print 'Human      Computer   Winner'
while 1:
  h = "rpsvq".find(raw_input('Rock Paper Scissors Verify Quit').lower())
  if h == -1:  print "Don't recognize " + x
  elif h == 4: break
  elif h == 3: # print table of all combinations to verify the winner matrix
    for r in [(media[h], media[c], outcome[winner[h][c]]) for h in 
range(3) for c in range(3)]:
      print '%10s%10s%10s' % r
  else:
    c = random.randint(0,2)
    print '%10s%10s%10s' % (media[h], media[c], outcome[winner[h][c]])

-- 
Bob Gailer
510-978-4454


From dianahawks at optusnet.com.au  Wed Aug 16 00:41:17 2006
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Wed, 16 Aug 2006 08:41:17 +1000
Subject: [Tutor] Python on network problems
Message-ID: <200608152241.k7FMfHdR020748@mail02.syd.optusnet.com.au>

An embedded and charset-unspecified text was scrubbed...
Name: not available
Url: http://mail.python.org/pipermail/tutor/attachments/20060816/b16de59e/attachment.asc 

From anilmrn at yahoo.com  Wed Aug 16 01:57:45 2006
From: anilmrn at yahoo.com (anil maran)
Date: Tue, 15 Aug 2006 16:57:45 -0700 (PDT)
Subject: [Tutor] getting and storing favicon.ico
Message-ID: <20060815235745.74333.qmail@web55907.mail.re3.yahoo.com>

/favicon.ico

i want to get the favicon.ico from the URL when a blog is added to the aggregator

and then display the image,
this is the usage scenario

Please let me know how to do this in python

i m willing to use os.spawnv() and call convert if need be
thanks a lot
 			
---------------------------------
Do you Yahoo!?
 Everyone is raving about the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060815/af46d2d6/attachment.html 

From kent37 at tds.net  Wed Aug 16 03:32:19 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 15 Aug 2006 21:32:19 -0400
Subject: [Tutor] What does import really do?
In-Reply-To: <BE5585AA-2C0B-11DB-B3EC-000A95EA5592@well.com>
References: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com>	<44E136E3.1020307@gmail.com>
	<BE5585AA-2C0B-11DB-B3EC-000A95EA5592@well.com>
Message-ID: <44E275A3.9040208@tds.net>

jim stockford wrote:
> many thanks.
>     wrt import and what's named, in the case of
> the PIL library, the import statement can be
> import Image # not import PIL
>   
That is because the directory Lib/site-packages/PIL is in sys.path, so 
any PIL module can be imported directly without the PIL prefix. (The PIL 
dir is added to sys.path by the file Lib/site-customize/PIL.pth.)

>     my presumption is that the PIL whatever-it-is
> contains a set of whatever-they-are, one of
> which is named Image.
>   
In the above usage I would say PIL is a directory containing a 
collection of modules. But PIL is also a package, since you can say
  from PIL import Image

Kent


From jeffpeery at yahoo.com  Wed Aug 16 07:31:22 2006
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Tue, 15 Aug 2006 22:31:22 -0700 (PDT)
Subject: [Tutor] threading
Message-ID: <20060816053122.36571.qmail@web30503.mail.mud.yahoo.com>

hello, how do I stop a thread? do I need to kill it or can I simply call a stop function... kinda like the start function? I read a bit on google and it sounded like using a kill isn't recommended for some reason... so how is this thing stopped? thanks!

Jeff

 		
---------------------------------
Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060815/d686a449/attachment.html 

From john at fouhy.net  Wed Aug 16 07:45:13 2006
From: john at fouhy.net (John Fouhy)
Date: Wed, 16 Aug 2006 17:45:13 +1200
Subject: [Tutor] threading
In-Reply-To: <20060816053122.36571.qmail@web30503.mail.mud.yahoo.com>
References: <20060816053122.36571.qmail@web30503.mail.mud.yahoo.com>
Message-ID: <5e58f2e40608152245h4e3863e0r1c357072a8f5a011@mail.gmail.com>

On 16/08/06, Jeff Peery <jeffpeery at yahoo.com> wrote:
> hello, how do I stop a thread? do I need to kill it or can I simply call a
> stop function... kinda like the start function? I read a bit on google and
> it sounded like using a kill isn't recommended for some reason... so how is
> this thing stopped? thanks!

The only good way for a thread to stop is for its run() method to exit.

It kinda depends what your thread is doing, and what technique you are
using to keep it alive, but one possibility is to do something like:

class Worker(threading.Thread):
    def run(self):
        self.running = True
        while(self.running):
            # do stuff

    def stop(self):
        self.running = False

In this case, the you call .stop() on your Worker object, and the
thread will exit when it next gets to the top of the while loop.

-- 
John.

From jeffpeery at yahoo.com  Wed Aug 16 07:52:16 2006
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Tue, 15 Aug 2006 22:52:16 -0700 (PDT)
Subject: [Tutor] threading
In-Reply-To: <5e58f2e40608152245h4e3863e0r1c357072a8f5a011@mail.gmail.com>
Message-ID: <20060816055216.65970.qmail@web30502.mail.mud.yahoo.com>

hmmmm, ok, well that is what I am currently doing but something is causing it to continue... guess I have some digging around to do. thanks for the help!

Jeff

John Fouhy <john at fouhy.net> wrote: On 16/08/06, Jeff Peery  wrote:
> hello, how do I stop a thread? do I need to kill it or can I simply call a
> stop function... kinda like the start function? I read a bit on google and
> it sounded like using a kill isn't recommended for some reason... so how is
> this thing stopped? thanks!

The only good way for a thread to stop is for its run() method to exit.

It kinda depends what your thread is doing, and what technique you are
using to keep it alive, but one possibility is to do something like:

class Worker(threading.Thread):
    def run(self):
        self.running = True
        while(self.running):
            # do stuff

    def stop(self):
        self.running = False

In this case, the you call .stop() on your Worker object, and the
thread will exit when it next gets to the top of the while loop.

-- 
John.


 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060815/5bd417e0/attachment-0001.htm 

From dyoo at hkn.eecs.berkeley.edu  Wed Aug 16 07:56:31 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 15 Aug 2006 22:56:31 -0700 (PDT)
Subject: [Tutor] threading
In-Reply-To: <5e58f2e40608152245h4e3863e0r1c357072a8f5a011@mail.gmail.com>
References: <20060816053122.36571.qmail@web30503.mail.mud.yahoo.com>
	<5e58f2e40608152245h4e3863e0r1c357072a8f5a011@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0608152251160.3143@hkn.eecs.berkeley.edu>



> It kinda depends what your thread is doing, and what technique you are 
> using to keep it alive, but one possibility is to do something like:
>
> class Worker(threading.Thread):
>    def run(self):
>        self.running = True
>        while(self.running):
>            # do stuff
>
>    def stop(self):
>        self.running = False
>
> In this case, the you call .stop() on your Worker object, and the thread 
> will exit when it next gets to the top of the while loop.


Hi Jeff,

Another variation of this is in here:

     http://mail.python.org/pipermail/tutor/2006-January/044557.html

Some of the method names in that old message are badly named, but I hope 
its ideas are clear.

From emilia12 at mail.bg  Wed Aug 16 08:37:27 2006
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Wed, 16 Aug 2006 09:37:27 +0300
Subject: [Tutor] about threads
In-Reply-To: <mailman.34578.1155667574.27774.tutor@python.org>
References: <mailman.34578.1155667574.27774.tutor@python.org>
Message-ID: <1155710247.b9eec2c3f7c1a@mail.bg>

Hi all,

my question is probably about the threads... I have two IPs
and i want to run web.py server for each IP in the same
time from one script file. I can run them in two command
boxes (and this works) but i want to do this from one ;-)
Maybe i can do this with 'threads' but how ? is there some
example ??

regards
e.

-----------------------------

Êàê äà ïîëó÷èòå 10% îòñòúïêà îò öåíèòå
çà îðèãèíàëíè êîíñóìàòèâè è ïðèíòåðè íà HP
http://digiteq.com/


From rabidpoobear at gmail.com  Wed Aug 16 08:52:41 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 16 Aug 2006 01:52:41 -0500
Subject: [Tutor] about threads
In-Reply-To: <1155710247.b9eec2c3f7c1a@mail.bg>
References: <mailman.34578.1155667574.27774.tutor@python.org>
	<1155710247.b9eec2c3f7c1a@mail.bg>
Message-ID: <44E2C0B9.8060003@gmail.com>

emilia12 at mail.bg wrote:
> Hi all,
>   
Hi!
> my question is probably about the threads... I have two IPs
> and i want to run web.py server for each IP in the same
> time from one script file. I can run them in two command
> boxes (and this works) but i want to do this from one ;-)
>
>   
if you run two instances of the python interpreter (like you're doing 
when you start two command windows,)
they're executing in different threads, it's just that the threads are 
OS level instead of application level.
Windows automatically switches between the two instances of the 
interpreter and gives them both time to do something.
This is why you can run an E-mail application at the same time as your 
web browser.
I suspect that OS-level threading in this way would be more efficient in 
regard to speed, but
it'd use more RAM because two interpreter instances would be loaded into 
memory at the same time.
I don't know what web.py is.
Is it something you wrote?
You'll have to write multi-threaded code if you want it to run multiple 
threads :)
(Unless, of course, Web.py supports threads?)
What's your experience with Python?
Do you need help with threads in general? threads in Python?
 >Maybe i can do this with 'threads' but how ? is there some
 >example ??
There are plenty of examples of threaded code that you could find by 
googling around,
or do you mean 'is there some example [of multi-threading the web.py 
program]??'
If the latter case, I guess you could find that by googling as well, if 
it exists.

> regards
> e.
>   

Cheers,
-Luke

From ismaelgf at adinet.com.uy  Wed Aug 16 09:30:15 2006
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Wed, 16 Aug 2006 04:30:15 -0300
Subject: [Tutor] about threads
In-Reply-To: <44E2C0B9.8060003@gmail.com>
References: <mailman.34578.1155667574.27774.tutor@python.org>	<1155710247.b9eec2c3f7c1a@mail.bg>
	<44E2C0B9.8060003@gmail.com>
Message-ID: <44E2C987.7070704@adinet.com.uy>

Luke Paireepinart escribi?:
> if you run two instances of the python interpreter (like you're doing 
> when you start two command windows,)
> they're executing in different threads, it's just that the threads are 
> OS level instead of application level.

Bear in mind that python threads have the GIL "Global interpreter lock". 
If you've got two processors, one interpreter, and two python threads 
there, at most you'll be able to use one processor. The GIL means that 
only one instruction at a time can be executed. Depending on what you're 
doing and the load you've got, this may or may not be important.


Ismael

From alan.gauld at freenet.co.uk  Wed Aug 16 11:04:06 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 16 Aug 2006 10:04:06 +0100
Subject: [Tutor] getting and storing favicon.ico
References: <20060815235745.74333.qmail@web55907.mail.re3.yahoo.com>
Message-ID: <002001c6c112$ee0624f0$0201a8c0@XPpro>

Anil,

Can you please ask more useful questions?
You have already been pointed to the url which describes
how to ask good questions. Please read it!

> /favicon.ico
>
> i want to get the favicon.ico from the URL when a blog is added to 
> the aggregator

I have no idea what this means.

> and then display the image,
> this is the usage scenario

Display the image where? On the blog? On a client GUI?
In a browser?

Don't make us guess, we cannot see your code, we cannot
see your system. We only have a vague idea of what you are
trying to do based on these fragmentary postings. We try to
help but you are making it nearly impossible to give any
sensible guidance.

What code have you tried to read this icon file?

> Please let me know how to do this in python
>
> i m willing to use os.spawnv() and call convert if need be

I have no idea why you think either would be necessaary.

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


From janos.juhasz at VELUX.com  Wed Aug 16 11:09:26 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Wed, 16 Aug 2006 11:09:26 +0200
Subject: [Tutor] Build a simple ftp server in python
In-Reply-To: <mailman.33836.1155161799.27774.tutor@python.org>
Message-ID: <OF6E716D84.1F1CF49B-ONC12571CC.0031DFF9-C12571CC.00324C38@velux.com>

Hi All,

I am just plannig to make a small ftp server that would serv not a 
filesystem, but some kind of objects, like stocks or assets.
In that case I can use my favorite commander to delete, copy, move objects 
from one place to another.

Have you got any idea which module to use ?

Yours sincerely, 
______________________________
J?nos Juh?sz 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060816/d5bc0165/attachment.htm 

From kent37 at tds.net  Wed Aug 16 13:22:07 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Aug 2006 07:22:07 -0400
Subject: [Tutor] about threads
In-Reply-To: <1155710247.b9eec2c3f7c1a@mail.bg>
References: <mailman.34578.1155667574.27774.tutor@python.org>
	<1155710247.b9eec2c3f7c1a@mail.bg>
Message-ID: <44E2FFDF.1000606@tds.net>

emilia12 at mail.bg wrote:
> Hi all,
>
> my question is probably about the threads... I have two IPs
> and i want to run web.py server for each IP in the same
> time from one script file. I can run them in two command
> boxes (and this works) but i want to do this from one ;-)
> Maybe i can do this with 'threads' but how ? is there some
> example ??

What are the commands you use to run the two copies of web.py?

Introductory material on threading is pretty scarce, try these:
http://mail.python.org/pipermail/tutor/2005-October/041866.html
http://linuxgazette.net/107/pai.html

Kent


From dyoo at hkn.eecs.berkeley.edu  Wed Aug 16 17:33:36 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 16 Aug 2006 08:33:36 -0700 (PDT)
Subject: [Tutor] getting and storing favicon.ico
In-Reply-To: <002001c6c112$ee0624f0$0201a8c0@XPpro>
References: <20060815235745.74333.qmail@web55907.mail.re3.yahoo.com>
	<002001c6c112$ee0624f0$0201a8c0@XPpro>
Message-ID: <Pine.LNX.4.64.0608160831060.31317@hkn.eecs.berkeley.edu>


>> i want to get the favicon.ico from the URL when a blog is added to
>> the aggregator
>
> I have no idea what this means.

Anil is referring to an icon image file that's often associated with web 
sites:

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

The Python Imaging Library (PIL) should be able to open .ICO files.  See:

     http://www.pythonware.com/products/pil/

From emilia12 at mail.bg  Wed Aug 16 17:56:08 2006
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Wed, 16 Aug 2006 18:56:08 +0300
Subject: [Tutor] threads and webpy
In-Reply-To: <mailman.41.1155722411.1676.tutor@python.org>
References: <mailman.41.1155722411.1676.tutor@python.org>
Message-ID: <1155743768.c8b5c03c24d33@mail.bg>

> Hi!
Hi !

> I don't know what web.py is.
> Is it something you wrote?
no, this is a simple webserver, (http://webpy.org/)
> You'll have to write multi-threaded code if you want it
> to run multiple
> threads :)
> (Unless, of course, Web.py supports threads?)

i will ask the authors about this ...

> What's your experience with Python?
> Do you need help with threads in general? threads in
> Python?
yes, but python related part of threads
>  >Maybe i can do this with 'threads' but how ? is there
> some
>  >example ??
> There are plenty of examples of threaded code that you
> could find by
> googling around,
> or do you mean 'is there some example [of multi-threading
> the web.py
> program]??'
> If the latter case, I guess you could find that by
> googling as well, if
> it exists.
yes - i will ask the webpy authors

but i expected to fond out a way to start two (or more)
scripts (web.py) in different threads from one puthon's
scrypt. OR two pythons interpretators to execute the above
scrypt ?

cheers
e.


-----------------------------

??????. ???? ? ?????? ?? 4 ??????.


From rabidpoobear at gmail.com  Wed Aug 16 18:28:02 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 16 Aug 2006 11:28:02 -0500
Subject: [Tutor] threads and webpy
In-Reply-To: <1155743768.c8b5c03c24d33@mail.bg>
References: <mailman.41.1155722411.1676.tutor@python.org>
	<1155743768.c8b5c03c24d33@mail.bg>
Message-ID: <44E34792.4030406@gmail.com>


> yes - i will ask the webpy authors
>
> but i expected to fond out a way to start two (or more)
> scripts (web.py) in different threads from one puthon's
> scrypt. OR two pythons interpretators to execute the above
> scrypt ?
>   
Python is a programming language. It's not a question about whether it's 
possible;
rather, it's who will do it.  If all you really want to do is start 2 
web.py scripts
from one python script you'd do something like this:
# ---- (non-working code)
import subprocess
subprocess.Popen('python web.py')
subprocess.Popen('python web.py')
#-----
This may or may not work.  You may only be able to subprocess actual 
executable files.
This is probably not what you want to do, though.
You'll probably have to learn how to program in Python to do this.
 ... ... ... ... ... ...

I just looked at web.py.
It's not a webserver.  It's a toolkit you use to write your own webserver.
Why are you under the impression that it's a webserver?
Did you just google for 'web server in Python' and find this?
If you're using some code that you've written (or found) to handle web 
requests
using the 'web.py' module, then show us your code and we'll tell you
how to make it into a class that listens on a single IP and how to
start two listen() methods of the class using threads, or maybe even
handling multiple IPs using a single class instance.
But just knowing that you are using 'web.py' isn't very helpful.
What actual code are you using to run the webserver?
(Or maybe web.py contains a simple webserver in the module when it's run 
as main?)
HTH,
-Luke

> cheers
> e.
>
>
> -----------------------------
>
> ??????. ???? ? ?????? ?? 4 ??????.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From alan.gauld at freenet.co.uk  Wed Aug 16 19:03:05 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 16 Aug 2006 18:03:05 +0100
Subject: [Tutor] getting and storing favicon.ico
References: <20060815235745.74333.qmail@web55907.mail.re3.yahoo.com>
	<002001c6c112$ee0624f0$0201a8c0@XPpro>
	<Pine.LNX.4.64.0608160831060.31317@hkn.eecs.berkeley.edu>
Message-ID: <000501c6c155$d7d96f50$0201a8c0@XPpro>

>>> i want to get the favicon.ico from the URL when a blog is added to
>>> the aggregator
>>
>> I have no idea what this means.
>
> Anil is referring to an icon image file that's often associated with 
> web sites:
>
>     http://en.wikipedia.org/wiki/Favicon

Sure, that much I understood, but which url, and what is the 
aggregator?
Is this one he is creating? Is his code part of the server or a client 
monitoring
a blog site? Is he trying to detect events on a server site he uses, 
or
one he manages? or one he is writing?

Despite his many posts I still don't really understand what exactly
anil is trying to do and which parts of it are in Python, which are
server side, which are client side and if any of it is server admin
related.

Nor do I understand what specifically Anil has tried himself and
where he is getting stuck and what exactly he wants us to help
with.

Alan G.


From carroll at tjc.com  Wed Aug 16 20:43:35 2006
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 16 Aug 2006 11:43:35 -0700 (PDT)
Subject: [Tutor] threading
In-Reply-To: <20060816053122.36571.qmail@web30503.mail.mud.yahoo.com>
Message-ID: <Pine.LNX.4.44.0608161133050.2413-100000@violet.rahul.net>

On Tue, 15 Aug 2006, Jeff Peery wrote:

> hello, how do I stop a thread? 

In all the threaded apps I have so far, I've worked with Queues to give 
them work.  So my technique has been to put a special-purpose element on 
the Queue, which is recognized by the thread, which exits.

I usually have multiple threads accessing the Queue (or what's the 
point?), so before exiting, the ending thread requeues the "stop" element 
back onto the Queue it took it from, so that other executing threads can 
pick it up and process it the same way.


From kermit at polaris.net  Thu Aug 17 05:42:08 2006
From: kermit at polaris.net (Kermit Rose)
Date: Wed, 16 Aug 2006 23:42:08 -0400 (Eastern Daylight Time)
Subject: [Tutor] Actual code that illustrates problem
Message-ID: <44E3E590.000005.00920@YOUR-4105E587B6>

  
Message: 11
Date: Tue, 15 Aug 2006 11:50:47 +1200
From: "John Fouhy" <john at fouhy.net>
Subject: Re: [Tutor] Global variables
Cc: tutor at python.org
 
 
Can you post actual code to illustrate the problem?  Don't post your
entire module; just show us the functions involved, the input that
causes the problem, and what output you expect to get.
 
--
John.
 
 
*******
 
Here is the output that illustratrates the problem.  After the output I'll
list the code for the called function,
strongfac,
 
and the calling function,  fermat.
 
IDLE 1.1.2
>>> import factor34
>>> from factor34 import testrange
>>> testrange(10**14+37,10**14+37)
  Begin calculating constants to be used in factoring.
  Finished calculating constants to be used in factoring.
 
  Search for a factor of  100000000000037
 
  Could not find factors by strong probable prime test using witnesses <
10000.
 
  Try to find factors by using power of  2  mod z as a witness.
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  0  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  1  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  2  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  3  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  4  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  5  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  6  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  7  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  8  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  9  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  10  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  11  x =  0  y =  0  face =  [0, 0, 0]
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  12  x =  0  y =  0  face =  [0, 0, 0]
 
  In strongfac
  Found1: x =  53799857
  Found1: y =  1858741
  face =  [53799857L, 1858741L, 0]
  Found1: factor by strong probable prime test, using witnes  15306543515214
.
  Found1: factors are  53799857 1858741
  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  13  x =  0  y =  0  face =  [0, 0, 0]
 
  In strongfac
  Found1: x =  53799857
  Found1: y =  1858741
  face =  [53799857L, 1858741L, 0]
  Found1: factor by strong probable prime test, using witnes  12123044576953
.
  Found1: factors are  53799857 1858741
  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  14  x =  0  y =  0  face =  [0, 0, 0]
 
  In strongfac
  Found1: x =  53799857
  Found1: y =  1858741
  face =  [53799857L, 1858741L, 0]
  Found1: factor by strong probable prime test, using witnes  45391315949900
.
  Found1: factors are  53799857 1858741
  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  15  x =  0  y =  0  face =  [0, 0, 0]
 
  In strongfac
  Found1: x =  53799857
  Found1: y =  1858741
  face =  [53799857L, 1858741L, 0]
  Found1: factor by strong probable prime test, using witnes  59571344259390
.
  Found1: factors are  53799857 1858741
  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  16  x =  0  y =  0  face =  [0, 0, 0]
 
  In strongfac
  Found1: x =  53799857
  Found1: y =  1858741
  face =  [53799857L, 1858741L, 0]
  Found1: factor by strong probable prime test, using witnes  78029752396948
.
  Found1: factors are  53799857 1858741
  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  17  x =  0  y =  0  face =  [0, 0, 0]
 
  In strongfac
  Found1: x =  53799857
  Found1: y =  1858741
  face =  [53799857L, 1858741L, 0]
  Found1: factor by strong probable prime test, using witnes  35863146075772
.
  Found1: factors are  53799857 1858741
  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  18  x =  0  y =  0  face =  [0, 0, 0]
 
  In strongfac
  Found1: x =  53799857
  Found1: y =  1858741
  face =  [53799857L, 1858741L, 0]
  Found1: factor by strong probable prime test, using witnes  19712913203085
.
  Found1: factors are  53799857 1858741
  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  19  x =  0  y =  0  face =  [0, 0, 0]
 
  In strongfac
  Found1: x =  53799857
  Found1: y =  1858741
  face =  [53799857L, 1858741L, 0]
  Found1: factor by strong probable prime test, using witnes  14607414373499
.
  Found1: factors are  53799857 1858741
  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  20  x =  0  y =  0  face =  [0, 0, 0]
 
  In strongfac
  Found1: x =  53799857
  Found1: y =  1858741
  face =  [53799857L, 1858741L, 0]
  Found1: factor by strong probable prime test, using witnes  57761947468766
.
  Found1: factors are  53799857 1858741
  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  21  x =  0  y =  0  face =  [0, 0, 0]
 
  In strongfac
  Found1: x =  53799857
  Found1: y =  1858741
  face =  [53799857L, 1858741L, 0]
  Found1: factor by strong probable prime test, using witnes  75604347243674
.
  Found1: factors are  53799857 1858741
  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
  Retrieved from strongfac, face =  [0, 0, 0]
  In fermat: k =  22  x =  0  y =  0  face =  [0, 0, 0]
 
  In strongfac
  Found1: x =  53799857
  Found1: y =  1858741
  face =  [53799857L, 1858741L, 0]
  Found1: factor by strong probable prime test, using witnes  3561873332543
 
  Found1: factors are  53799857 1858741
  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
 
  In strongfac
  Found1: x =  1858741
  Found1: y =  53799857
  face =  [1858741L, 53799857L, 0]
  Found1: factor by strong probable prime test, using witnes  96058894729069
.
  Found1: factors are  1858741 53799857
  Found1: returning  [1858741L, 53799857L, 0]  to fermat routine.
  Retrieved from strongfac, face =  [1858741L, 53799857L, 0]
  In fermat: k =  23  x =  1858741  y =  53799857  face =  [1858741L,
53799857L, 0]
  index of torial is  23
  z =  100000000000037  x =  1858741  y =  53799857  difficulty =  0
>>>
 
 
#    def strongfac(z,w):
#        x = gcd(z,w-1)
#        if x > 1:
#            if x < z:
#                y = z/x
#                print "Found factors by P-1 Method as part of Strong
probable prime test, using witness",w,"."
#                print " x = ",x," y = ",y
#                return [x,y,0]
#        w2 = (w * w)%z
#        s = ksqrt(w2)
#        if w2 == s * s:
#            if s != w:
#                x = gcd(z,kabs(w2 - s))
#                if x > 1:
#                    if x < z:
#                        print "Found factors by square = square as part of
Strong probable prime test, using witness",w,"."
#                        return [x,y,0]
#                
#        trace = 0
#        t = z - 1
#        a = 0
#        while t%2 == 0:
#            t = t/2
#            a = a + 1
#        test = pow(w,t,z)
#        if test ==1:
#            x = gcd(z,w-1)
#            if x > 1:
#                if x < z:
#                    y = z/x
#                    print " Found factor by Strong probable prime test,
using withness ",w,"."
#                    return [x,y,0]
#        else:
#            x = gcd(test-1,z)
#            if x > 1:
#                print " "
#                print " In strongfac "
#                print " Found1: x = ",x
#                if x < z:
#                    y = z/x
#                    print " Found1: y = ",y
#                    face = [x,y,0]
#                    print " face = ",face
#                    face[0] = x
#                    face[1] = y
#                    face[2] = 0
#                    print " Found1: factor by strong probable prime test,
using witness ",w," ."
#                    print " Found1: factors are ",face[0],face[1]
#                    print " Found1: returning ",face," to fermat routine."
#                    return face
#
#        if test + 1 == z:
#            x = gcd(w+1,z)
#            if x > 1:
#                if x < z:
#                    y = z/x
#                    print " Found factor by Strong probable prrime test,
using withness ",w,"."
#                    return [x,y,0]
#        for j in range (1,a):
#            test2 = (test * test)%z
#            test2sqrt = ksqrt(test2)
#            if test2sqrt * test2sqrt == test2:
#                diff = kabs(test - test2sqrt)
#                if diff !=0:
#                    x = gcd(z,kabs(test - test2sqrt))
#                    if x > 1:
#                        if x < z:
#                            y = z/x
#                            print " Found factors by strong probable prime
test using difference of squares and witness ",w,"."
#                            return [x,y,j]
#                y = gcd(z,test+test2sqrt)
#                if y > 1:
#                    if y < z:
#                        print " Found factors by strong probable prime test
using difference of squares and witness ",w,"."
#                        return [x,y,j]
 
 
 
#            test1 = test2 + 1
#            test = test2
#            if test1 == z:
#                pass
 
#            else:
#                x = gcd(test1,z)
#                if x > 1:
#                    if x < z:
#                        print " "
#                        print " In Strongfac "
                    
#                        y = z/x
#                        fac = [x,y,j]
#                        print " Foundj factor by strong probable prime test
 using witness,",w," ."
#                        print " Returning ",fac," to fermat routine."
#                        return fac
#        q = 0
#        fac = [0,0,0]
#        return fac
#         
 
 
#    def fermat(z,maxdiff,pmap,plist,sqlist,sqresidue,torials,limitsteps):
#        for j in range(2,3):
#            print " "
#            print " Try to find factors by using power of ",j," mod z as a
witness."
#            w2 = j
#            for k in range(100):
#                w = pow(j,torials[k],z)
#                face = strongfac(z,w)
#                print " Retrieved from strongfac, face = ",face
 
#                x = face[0]
#                y = face[1]
#                print " In fermat: k = ",k," x = ",x," y = ",y," face = "
face
#                if face[0] != 0:
#                    print " index of torial is ",k
#                    return face
#                if k == 0:
#                    w2 = w
#                else:
#                    w2 = pow(w2,torials[k],z)
#                    fac = strongfac(z,w2)
        
 

#        print " "    
#       print " Could not find factors by strong probable prime test."    
    

 
 
    Kermit Rose   <  kermit at polaris.net  >


From kermit at polaris.net  Thu Aug 17 05:51:16 2006
From: kermit at polaris.net (Kermit Rose)
Date: Wed, 16 Aug 2006 23:51:16 -0400 (Eastern Daylight Time)
Subject: [Tutor] Global variables
References: <44E11426.2060700@alum.rpi.edu>
Message-ID: <44E3E7AF.000009.00920@YOUR-4105E587B6>

 
 
From: Bob Gailer 
Date: 08/14/06 20:24:00 
To: kermit at polaris.net; tutor at python.org 
Subject: RE: [Tutor] Global variables 
 
A while back you attached factor34.py. Is that the program you are 
having trouble with? 
 
 
****
 
Yes!
 
And you said it misbehaves "consistently with certain numbers to be 
factored." 
What are these numbers? 
 
 
*****
 
One of the numbers for which strongfac fails to return factors which it
correctly calculates is
 
Search for a factor of  100000000000037
 
 
 
Kermit  <  kermit at polaris.net  >
 


From kermit at polaris.net  Thu Aug 17 06:17:47 2006
From: kermit at polaris.net (Kermit Rose)
Date: Thu, 17 Aug 2006 00:17:47 -0400 (Eastern Daylight Time)
Subject: [Tutor] Global variables
References: <000301c6c03d$9b8cc5b0$0201a8c0@XPpro>
Message-ID: <44E3EDEB.00000B.00920@YOUR-4105E587B6>

 
 
From: Alan Gauld 
Date: 08/15/06 03:37:21 
To: Kermit Rose; rabidpoobear at gmail.com 
Cc: tutor at python.org; dyoo at hkn.eecs.berkeley.edu 
Subject: Re: [Tutor] Global variables 
 
. 
 
The names have very little to do with it, the danger of global 
variable 
use is the reliance on side-effects and the tight coupling that you 
introduce between the calling module and the called module. 
Changes to the state of the calling module in an unpredictable 
manner lead to subtle bugs which are extremely hard to see and fix. 
 
*****
 
Huh???
 
What side effects do you have in mind?
 
I certainly did not know any side effects existed.
 
What do you mean by tight coupling?
 
The only change I can see that would lead to a bug would be if I changed the
name of the global variable in
the calling routine and not in the function it called.
 
I would know not to do that.
 
 
 
>>>>>>>>>>>
 
Confusion of names is of very little import, that really isn't the 
issue. 
 
**********
 
Is it that global variables are no implemented correctly?
 
I can't imagine what the issue would be if it isn't confusion of names.
 
>>>>>>>>>>
 
 
 
I'd be very very doubtful that its a bug in Python. 
Python is very well tested and while occasionally bugs do surface, 
the type of bug you are describing is extremely unl;ikely to have 
remained hidden. It is far more likely to be an error in the code 
or in the data. 
 
 
*******
 
I understand your skepiticism.   I would be too in if I were in your
position.
 
I've just sent the documentation to the list,  in my message to Luke.
 
>>>>>
 
 
All of which points to an error in the code not in Python. 
The way Python is written it is virtually never going to result in 
that kind of error dependant on data values. 
 
 
******
 
Which is why it surprised me.
 
>>>>>>>>>>>
 
 
That might happen 
is if the values are very close to zero and a type conversion 
occurs, but otherwise I'm very dubious about a Python bug 
of that type. 
 
 
*****
 
Indeed.  Errors of this type would be found by chance, like I found it.
 
It would be impractical to search for this type of error.
 
It is not a type conversion.
 
The error is occuring between the return statement in the called function
and the picking up of that value
in the calling function.
 
 
 
 
 
 
 
 


From amadeo.bellotti at gmail.com  Thu Aug 17 06:37:31 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Thu, 17 Aug 2006 00:37:31 -0400
Subject: [Tutor] (no subject)
Message-ID: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>

hello is there a way if a condition is not met to restart the whole program?
for example if and if statement returns true then re start the whole
program?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/83c7bc33/attachment.html 

From dkuhlman at rexx.com  Thu Aug 17 06:53:49 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Wed, 16 Aug 2006 21:53:49 -0700
Subject: [Tutor] Build a simple ftp server in python
In-Reply-To: <OF6E716D84.1F1CF49B-ONC12571CC.0031DFF9-C12571CC.00324C38@velux.com>
References: <mailman.33836.1155161799.27774.tutor@python.org>
	<OF6E716D84.1F1CF49B-ONC12571CC.0031DFF9-C12571CC.00324C38@velux.com>
Message-ID: <20060817045349.GA96382@cutter.rexx.com>

On Wed, Aug 16, 2006 at 11:09:26AM +0200, J?nos Juh?sz wrote:
> Hi All,
> 
> I am just plannig to make a small ftp server that would serv not a 
> filesystem, but some kind of objects, like stocks or assets.
> In that case I can use my favorite commander to delete, copy, move objects 
> from one place to another.
> 
> Have you got any idea which module to use ?
> 

Look at Twisted:

    http://twistedmatrix.com/projects/core/

and Medusa:

    http://www.nightmare.com/medusa/

And, you might be interested in this thread on twisted and medusa:

    http://www.gossamer-threads.com/lists/python/python/379675

Dave


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

From rabidpoobear at gmail.com  Thu Aug 17 08:28:41 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 17 Aug 2006 01:28:41 -0500
Subject: [Tutor] All of Kermit's E-Mails [was: Global Variables]
In-Reply-To: <44E3E7AF.000009.00920@YOUR-4105E587B6>
References: <44E11426.2060700@alum.rpi.edu>
	<44E3E7AF.000009.00920@YOUR-4105E587B6>
Message-ID: <44E40C99.3060901@gmail.com>

Hello, Kermit.
Kermit Rose wrote:
>  
>  
> From: Bob Gailer 
> Date: 08/14/06 20:24:00 
> To: kermit at polaris.net; tutor at python.org 
> Subject: RE: [Tutor] Global variables 
>  
> A while back you attached factor34.py. Is that the program you are 
> having trouble with? 
>  
>  
> ****
>  
> Yes!
>  
> And you said it misbehaves "consistently with certain numbers to be 
> factored." 
> What are these numbers? 
>  
>  
> *****
>  
> One of the numbers for which strongfac fails to return factors which it
> correctly calculates is
>  
> Search for a factor of  100000000000037
>   
I really dislike the way you reply.
Follow the standard format! Leave all the greater-than signs before the 
previous person's reply
so that it will be structured correctly and easy to read.  All of this 
star business is bad.
There are two reasons why I think this.
First, consider this example.

Hello, how are you today?
***
I'm fine.
Did you have a good day?
***
Yes, I did.

Now while I'm reading this, I see the dialog going like this.
person: 'hello, how are you today?'
kermit: 'i'm fine.  did you have a good day?'
Oh wait! there are stars there.  That must mean that part of what I 
thought was you
talking was actually person talking.  So I have to actually try to judge 
which part was
the original post and which part is your reply.
On this example it's easy to see that 'did you have a good day' is 
person's speech and not yours
because there are only two lines of text between the stars and we know 
that the first line
immediately after any set of stars has to be  your reply.

Now consider this example:
 > Hello, how are you today?
I'm fine.
 > Did you have a good day?
Yes, I did.

Tell me that isn't orders of magnitude clearer.

Point 2:
I recently read an article on UI design.
Basically, what it said was 'the easier it is for your users to 
intuitively understand your application,
the more they'll enjoy it and consider it a good application.  This is 
largely governed by how they've
experienced similar applications working in the past, and they expect if 
they perform similar
actions in your application they'll garner similar results as in your 
predecessor.'

How this applies to you:
Right away, when I see those stars, I get really agitated, because I 
know I'm going to have to
work twice as hard trying to decipher who's talking when I read your 
e-mail, and right off the bat
you've alienated me and made me not want to address the issue at hand.
Clearly you can see this as I've written quite a long reply that is 
based on nothing
to do with your original question.

The place where I had a problem understanding who was speaking in this 
particular e-mail was:

>A while back you attached factor34.py. Is that the program you are 
>having trouble with? 
>
>
>****
>
>Yes!
>
>And you said it misbehaves "consistently with certain numbers to be 
>factored." 
>What are these numbers? 
>
>
>*****
>
>One of the numbers for which strongfac fails to return factors which it
>correctly calculates is

As I was reading this, I assumed the 'Yes!' and following paragraph were 
part of the same thought.
When I got to the second set of stars, my immediate reaction was "Why is 
kermit replying to something she
just said?" That was followed by "Oh, somewhere along the line it 
must've switched between the original poster's
and kermit's dialog."  I figured out that the 'And you said it 
misbehaves ...' part was where the OP continued to speak.


Now that I'm done with that topic, let's move on.

 From one of your other e-mails:

 
 
>From: Alan Gauld 
 
>The names have very little to do with it, the danger of global 
>variable 
>use is the reliance on side-effects and the tight coupling that you 
>introduce between the calling module and the called module. 
>Changes to the state of the calling module in an unpredictable 
>manner lead to subtle bugs which are extremely hard to see and fix. 
>*****
>Huh???
>What side effects do you have in mind?
>I certainly did not know any side effects existed.
>What do you mean by tight coupling?
>The only change I can see that would lead to a bug would be if I changed the
>name of the global variable in
>the calling routine and not in the function it called.
>I would know not to do that.


Okay.
>From this it appears that you have no academic training in programming.
The term 'side-effect' means that something outside the scope of the 
called function is modified by the called function.


Here is a very basic example.

#--- test.py
a = ['a','b','c']
def modify_list(alist):
    del(alist[0])

modify_list(a)
modify_list(a)
print a
#---

#--- output of test.py
['c']
#---


Now remember that in Python, when you pass a variable to a function,
only the reference is passed to the function.
Imagine that variables are themselves references (which they are.)

a = ['a','b','c']

creates the following picture:

a ------> ['a','b','c']

modify_list(a)

doesn't do

modify_list(['a','b','c'])

it does

modify_list(ptr) where ptr ------> ['a','b','c'] <----- a

they both refer to the same object ( a python list containing three characters.)

now when in the body of modify_list we say del(alist[0]), what takes place is
the index operator, [0], says 'what object is the variable 'alist' pointing to?
and python says 'alist ----> ['a','b','c'] <---- a'
so when we delete the element out of alist we're also deleting the element
out of the calling function's list.
This is probably NOT desired behavior.
As such it's an unwanted side-effect.

A function printing to the screen is also considered a side-effect.
Anything a function does that affects anything outside of its own scope
is considered a side-effect.


To refresh your memory, here's the next part of the e-mail I'm going to address:

>The names have very little to do with it, the danger of global 
>variable 
>use is the reliance on side-effects and the tight coupling that you 
>introduce between the calling module and the called module. 
>Changes to the state of the calling module in an unpredictable 
>manner lead to subtle bugs which are extremely hard to see and fix. 
>*****
>What do you mean by tight coupling?
>The only change I can see that would lead to a bug would be if I changed the
>name of the global variable in
>the calling routine and not in the function it called.
>I would know not to do that.


'tight coupling' is an English phrase meaning roughly
(for our purposes) 'close interaction' or 'dependence on each other.'

you say, I quote:
'The only change ... that would lead to a bug would be if I changed the
name of the global variable in the calling routine.'
I think you're misunderstanding Alan.
consider this following example
(it was hard to come up with something this convoluted)

#--- start code
def b():
    global has_been_greeted
    has_been_greeted = False
    print "function B is doing lots of stuff"
    return "whatever we did in function B that's so important"

def greet():
    global has_been_greeted
    if has_been_greeted:
        print 'we already greeted you.'
    else:
        print 'hello!'
        has_been_greeted = True

def c():
    print "function C is doing lots of stuff."
    a = b()
    print "function C is using value a here."

b()
greet()
greet()
c()
greet()

# --- end code.

Now we know we're going to call b() every time on startup,
so we set has_been_greeted to false inside of it.
Then we call greet, once b() is done calculating its stuff,
so it will greet the customer.
Then we call greet again to make sure that we already greeted them.
(say we're debugging our program and we want to make sure greet's 
working correctly.)

Now we call function C, which relies on function b to get a value
that it needs for one of its calculations.
Oops, we forgot that b() resets has_been_greeted back to false
every time it's called.
Now when we call greet after function c again, it greets them again!
But it's already greeted them so it shouldn't have greeted them.

Now imagine this is much more complicated and there are multiple global 
variables
that you're setting all over the place to store your values,
and then imagine trying to find something this obscure.

A much more straightforward way to do this would be:

#--- start code
def b():
    print "function B is doing lots of stuff"
    return "whatever we did in function B that's so important"

def greet():
    print 'hello!'

def c():
    print "function C is doing lots of stuff."
    a = b()
    print "function C is using value a here."

b()
greet()
has_been_greeted = True
if has_been_greeted == False: greet()
c()
if has_been_greeted == False: greet()
#---

I know this was a stupid example but it's all I could come up with.
does it help you see how global variables could give you trouble?
Maybe Alan can fix my example so it makes more sense.



>>>>>>>>>>> >>>>>>>>>>>
>>>>>>>>>>>                       

I see here you started using Greater-than signs to separate the Original Post from your replies.
WTF. RTFM. This is almost as bad as before.
Now I don't have the additional stress of trying to sort out who is speaking at any given time,
you or the person you're replying to, but I have these big columns of multi-colored lines to deal with.
In my e-mail client, Thunderbird, it converts every > sign to a vertical line of a different color,
so I can tell the different levels of replies in any given e-mail.
This is super-helpful, unless something like this comes along, and all it does is space
out all the messages a tremendous amount and look ugly.
Why can't you just use the convention and leave the >> things there?
They're there for a reason.
Don't fix somethin' that ain't broke, please.
 

>Confusion of names is of very little import, that really isn't the 
>issue. 
 
>**********
 
>Is it that global variables are no implemented correctly?
 
>I can't imagine what the issue would be if it isn't confusion of names.

No, it's not that global variables are not implemented correctly.
You must understand that there are thousands of people using Python every day,
and phrases like 'not implemented correctly' or 'there's a bug in python' are
converted in my ears to '*i'm complaining because i can't get my program to work*'
It's identical, to me, as when I'm playing Counter-Strike and someone starts
yelling 'HACKER!' every time they get killed.

It's ____much____ more likely that the person is just good at Counter-Strike than they're cheating,
especially since there are a lot of anti-cheat measures.

It's ____much____ more likely that your program has a bug than Python itself,
because there is a lot of quality-control when a programming language is used
frequently by many very skilled coders.
 

>>>>>>>>>> >>>>>>>>>>
>>>>>>>>>>                     

You already know my feelings about this.

 
 
>I'd be very very doubtful that its a bug in Python. 
>Python is very well tested and while occasionally bugs do surface, 
>the type of bug you are describing is extremely unl;ikely to have 
>remained hidden. It is far more likely to be an error in the code 
>or in the data. 
>*******
>I understand your skepiticism.   I would be too in if I were in your
>position.
>I've just sent the documentation to the list,  in my message to Luke.

Alan is being diplomatic here.

I would not call what you sent 'documentation.'
The tangled mess of your functions doesn't prove there's a bug in python,
it just makes me think you messed up the value somewhere along the way.


>>>>> >>>>>
>>>>>           
Yay, more of this stuff.

 
>All of which points to an error in the code not in Python. 
>The way Python is written it is virtually never going to result in 
>that kind of error dependant on data values. 
 
 
>******
 
>Which is why it surprised me.

What Alan means is that your program incorrectly handles certain data values
because your functions aren't written correctly.

Your first thought when your program doesn't do what you expect it to
should not be to blame the return statement of being buggy,
but to first blame yourself.
It's much more likely that you're at fault.
I'm not saying this directly at you.
If I wrote a function that returned incorrect values,
I would assume it's my fault too.

You have to understand that Python has been used for years
and if there was such a fundamental bug, no matter how obscure (only occuring on certain return values),
it would have been found by now.

 

>>>>>>>>>>> >>>>>>>>>>>
>>>>>>>>>>>                       
:(
 
 
>That might happen 
>is if the values are very close to zero and a type conversion 
>occurs, but otherwise I'm very dubious about a Python bug 
>of that type. 
 
 
>*****
 
>Indeed.  Errors of this type would be found by chance, like I found it.
 
>It would be impractical to search for this type of error.
 
>It is not a type conversion.
 
Because it's impractical to search for a certain type of error it must not be that error?
Just dwell on that statement a bit and tell me if you still believe it.



>The error is occuring between the return statement in the called function
>and the picking up of that value
>in the calling function. 

so show us.
This is the way I would prove this, if it were my program that uncovered this 'bug.'


#---
def func_that_causes_bug(a):

    print "function is doing a bunch of complex calculations and such."
    v = 2322**a
    c = 55/float(v)
    d = v - a + 543
    value = d / 45

    print "this is where the problem arises."
    print "Before I return the value, it is :%s" %  value
    return value

tmp = func_that_causes_bug(564)
print "And after I return the value, it is :%s" % tmp

#---
 
Do you understand why this would evidence the bug you mentioned?
You say it's a problem with the returning of the value.
So print the value immediately before the return and immediately after.
We'll see if it changes in transit as you claim.




Onto your next e-mail:


 >Can you post actual code to illustrate the problem?  Don't post your
 >entire module; just show us the functions involved, the input that
 >causes the problem, and what output you expect to get.
 >--
 >John.
 >
 >******* 
 >
 >Here is the output that illustratrates the problem.  After the output I'll
 >list the code for the called function,
 >strongfac,
 > 
 >and the calling function,  fermat.
 
[snip a ton of debug output.]

This doesn't help us at all.  What the heck was all that?
You must understand that I have no idea what your function is supposed 
to do.
Treat me like a child.  Explain everything to me.

What part of this output isn't what you wanted?


 >#    def strongfac(z,w):
 >#        x = gcd(z,w-1)
 >#        if x > 1:
 >#            if x < z:
 >[snip the rest of strongfac]
 >#    def fermat(z,maxdiff,pmap,plist,sqlist,sqresidue,torials,limitsteps):
 >#        for j in range(2,3):
 >#            print " "
 >#            print " Try to find factors by using power of ",j," mod z 
as a
 >[snip the rest of fermat]


Why the CRAP did you put # signs before every line?
I spent about 10 minutes pressing delete, down-arrow, delete, down-arrow.
Going through all that trouble just so I could run the code was a pain 
in the rear.
Remember when we were talking about UI usability earlier?
Your code usability would be greatly improved if I didn't have to remove
a comment from every line to test it.

Also, in your example call:
 
 >IDLE 1.1.2
 > >>> import factor34
 > >>> from factor34 import testrange
 > >>> testrange(10**14+37,10**14+37)

You called testrange.
Now John originally said 'show us which functions are involved.'
Well, after I had gone through the trouble of un-commenting all your code,
it turned out that I didn't even have all the pieces there.
So I went back in e-mail history and downloaded the attached 
'factor34.py' file.
Now I wish I didn't have to do this, because you could've made 
improvements in it since then.
But it's the only way I can get a functional test file.

Turns out testrange depends on x depends on  y depends on z depends on .....
basically all of the functions in the module depend on each other.

This is obviously a case for ... .dun-dun-dun!.... object-oriented 
programming.
When you have a collection of functions that all operate together to 
create something,
you make a Class to contain them.

I think just in the process of doing this you might learn what's wrong 
with your program.



Link me to all the Wikipedia articles I need in order to understand what 
you're trying to do.
I'll help you rewrite this program from scratch if you want.
We'll make it object-oriented the whole way.
But there is no hope I will understand factor34.
I will not even try.


Sorry if I was too harsh anywhere along the way.
Feel free to point any of this out and I'll apologize.
But this is my honest opinion of the e-mails I've received from you so far.

I don't think this is a good programming project for you to be learning
a new language with.  Perhaps you should do something simpler.
If you'd like some recommendations I'd be happy to give some.

Have a good day.
-Luke

From emilia12 at mail.bg  Thu Aug 17 09:19:05 2006
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Thu, 17 Aug 2006 10:19:05 +0300
Subject: [Tutor] threads and webpy
In-Reply-To: <44E34792.4030406@gmail.com>
References: <mailman.41.1155722411.1676.tutor@python.org>
	<1155743768.c8b5c03c24d33@mail.bg> <44E34792.4030406@gmail.com>
Message-ID: <1155799145.3d10c7f49700d@mail.bg>

> I just looked at web.py.
> It's not a webserver.  It's a toolkit you use to write
> your own webserver.
> Why are you under the impression that it's a webserver?
> Did you just google for 'web server in Python' and find
> this?

you are right, i mean that it is the core of the webserver

> If you're using some code that you've written (or found)
> to handle web
> requests
> using the 'web.py' module, then show us your code and
> we'll tell you
> how to make it into a class that listens on a single IP
> and how to
> start two listen() methods of the class using threads, or
> maybe even
> handling multiple IPs using a single class instance.
> But just knowing that you are using 'web.py' isn't very
> helpful.
> What actual code are you using to run the webserver?
i am playng around this code :
<code>
import socket
import sys
import web
import datetime

urls = (
    '/(.*)', 'view'
)

class view:
    def GET(self, name):
        print datetime.datetime.today()

if __name__ == "__main__":
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    sys.argv.append(ip +':8080') # <-- probably this is not
the right way, but it works
    web.run(urls)

</code>

> (Or maybe web.py contains a simple webserver in the
> module when it's run
> as main?)
yes - in this case it responds to http request like a server

regards
e.

-----------------------------

??? ?? ???????? 10% ???????? ?? ??????
?? ?????????? ??????????? ? ???????? ?? HP
http://digiteq.com/


From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 10:02:20 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 01:02:20 -0700 (PDT)
Subject: [Tutor] Actual code that illustrates problem
In-Reply-To: <44E3E590.000005.00920@YOUR-4105E587B6>
References: <44E3E590.000005.00920@YOUR-4105E587B6>
Message-ID: <Pine.LNX.4.64.0608170024240.31579@hkn.eecs.berkeley.edu>

> #    def strongfac(z,w):
[function body cut]

Ok, let's go through this step by step.

     * What is the intent of strongfac?
     * What are the inputs?  What is 'z', and what is 'w'?
     * What are the outputs?  What is the return value of strongfac?

Same questions for fermat().  What are the inputs and outputs, and what's 
the intent?

Get those out and documented, because although I think I can guess at it, 
I'd rather know that we are sharing the same understanding.


There's a bit of code in strongfac() that's nonsensical from a purely 
technical sense.  For example:

> #                    face = [x,y,0]
[some code cut]
> #                    face[0] = x
> #                    face[1] = y
> #                    face[2] = 0

The three assignments to face[0] through face[2] don't do anything 
effective and clutter the code.



In fermat(), there are magic numbers:

#        for j in range(2,3):
                         ^^^^

#            for k in range(100):
                             ^^^

These seem pretty arbitrary.  Can you explain them?



The strongfac() function you have is a good case for writing smaller 
functions: I can not tell where the function really ends.  I see that you 
have several sub-tests, which I'll categorize as:

     * P-1
     * square = square
     * ...

and there's a few others that I can not categorize yet.  But I bet you 
can.  Have you considered breaking those out as independent helper 
functions?


Most of us don't have experience with number theory.  What people here on 
the list have is experience with writing software.  My experience informs 
me that the functions you're writing are way too large.  They are 
monolithic and imposing enough that very few people will be able to (or 
want to!) understand their reasoning.  They really cry out to be broken 
into smaller subtest functions that can be individually understood.

(And even if your program were running perfectly well, I'd still strongly 
recommend you practice the skill of small, easy-to-understand functions.)



You mentioned later that:

> One of the numbers for which strongfac fails to return factors which it
> correctly calculates is 100000000000037

Two questions:

     * How do you know that it is being "correctly calculated?"

     * How do you know that your program is doing something wrong?

That is, state explicitely to us what you expected the program to do. 
What is the expected result, in terms of return values, that your function 
failed to produce?  What part of the program --- which particular subtest 
--- should have returned those values?  Where are you looking at?


Again, you have to assume that we don't know anything about number theory. 
Things that may seem "obvious" to you are not obvious to this audience. 
*grin*

From nimrodx at slingshot.co.nz  Thu Aug 17 13:04:59 2006
From: nimrodx at slingshot.co.nz (nimrodx)
Date: Thu, 17 Aug 2006 21:04:59 +1000
Subject: [Tutor] [whitelist] Re:  regular expressions question
In-Reply-To: <001801c6be13$fb72d220$0201a8c0@XPpro>
References: <44DDC3AA.8010908@slingshot.co.nz>
	<002a01c6bdf2$60c69480$0201a8c0@XPpro>
	<44DDE5D1.1080101@slingshot.co.nz>
	<001801c6be13$fb72d220$0201a8c0@XPpro>
Message-ID: <44E44D5B.6000605@slingshot.co.nz>

Hi Alan,

I found a pretty complicated way to do it (Alan's way is way more elegant).
In case someone is searching the archive, maybe they will find something 
in it that is useful.
It uses the regular experessions module.

import re

def dehexlify_websites(fle):
   # get binary data
   inpt = open(fle,'rb')
   dat = inpt.read()
   inpt.close()
   #strip out the hex "0"'s
   pattern = r"\x00"
   res = re.sub(pattern, "", dat)
   #-----------------------------------------
   #it seemed easier to do it in two passes
   #create the pattern regular expression for the stuff we want to keep
   web = re.compile(
                    r"(?P<addr>[/a-zA-Z0-9\.\-:\_%\?&=]+)"
                    )
   #grab them all and put them in temp variable
   res = re.findall(web,res)
   tmp = ""
   #oops need some new lines at the end of each one to mark end of
    #web address,
   #and need it all as one string
   for i in res:
       tmp = tmp + i+'\n'
   #compile reg expr for everything between :// and the newline
   web2 = re.compile(r":/(?P<address>[^\n]+)")
   #find the websites
   #make them into an object we can pass
   res2 = re.findall(web2,tmp)
   #return 'em
   return res2


Thanks Alan,

Matt


Alan Gauld wrote:
>> if you look carefully at the string below, you see
>> that in amongst the "\x" stuff you have the text I want:
>> z tfile://home/alpha
>
> OK, those characters are obviously string data and it looks
> like its using 16 bit characters, so yes some kind of
> unicode string. In between and at the end ;lies the binary
> data in whatever format it is.
>
>>>> Here is the first section of the file:
>>>> '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l' 
>>>>
>
>
>> In a hex editor it turns out to be readable and sensible url's with 
>> spaces between each digit, and a bit of crud at the end of url's, 
>> just as above.
>
> Here's a fairly drastic approach:
>
>>>> s = 
>>>> '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01 
>>>>
> \xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x 
>
> 00l'
>>>> ''.join([c for c in s if c.isalnum() or c in '/: '])
> 'ztfile:/home/al'
>>>>
>
> But it gets close...
>
> Alan g.
>


From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 10:04:06 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 01:04:06 -0700 (PDT)
Subject: [Tutor] (no subject)
In-Reply-To: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0608170102290.31579@hkn.eecs.berkeley.edu>


> hello is there a way if a condition is not met to restart the whole 
> program? for example if and if statement returns true then re start the 
> whole program?

Question before we go on: why are you trying to do this?

It's possible to do this, but it sounds so unusual that I want to know 
more about the problem.

From anilmrn at yahoo.com  Thu Aug 17 11:12:59 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 17 Aug 2006 02:12:59 -0700 (PDT)
Subject: [Tutor] threads and webpy
In-Reply-To: <1155743768.c8b5c03c24d33@mail.bg>
Message-ID: <20060817091259.75509.qmail@web55903.mail.re3.yahoo.com>

did u try os.spawnv()
to spawn other unix commands

emilia12 at mail.bg wrote: > Hi!
Hi !

> I don't know what web.py is.
> Is it something you wrote?
no, this is a simple webserver, (http://webpy.org/)
> You'll have to write multi-threaded code if you want it
> to run multiple
> threads :)
> (Unless, of course, Web.py supports threads?)

i will ask the authors about this ...

> What's your experience with Python?
> Do you need help with threads in general? threads in
> Python?
yes, but python related part of threads
>  >Maybe i can do this with 'threads' but how ? is there
> some
>  >example ??
> There are plenty of examples of threaded code that you
> could find by
> googling around,
> or do you mean 'is there some example [of multi-threading
> the web.py
> program]??'
> If the latter case, I guess you could find that by
> googling as well, if
> it exists.
yes - i will ask the webpy authors

but i expected to fond out a way to start two (or more)
scripts (web.py) in different threads from one puthon's
scrypt. OR two pythons interpretators to execute the above
scrypt ?

cheers
e.


-----------------------------

??????. ???? ? ?????? ?? 4 ??????.

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


 		
---------------------------------
Do you Yahoo!?
 Next-gen email? Have it all with the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/b3fd258f/attachment.html 

From anilmrn at yahoo.com  Thu Aug 17 11:15:30 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 17 Aug 2006 02:15:30 -0700 (PDT)
Subject: [Tutor] threads and webpy
In-Reply-To: <44E34792.4030406@gmail.com>
Message-ID: <20060817091530.3530.qmail@web55907.mail.re3.yahoo.com>

hi like
your post about how to make it listen on one ip and then on two ips 
isnt this general python, can you please explain how to go about this, this would be very useful
thanks

 then show us your code and we'll tell you
how to make it into a class that listens on a single IP and how to
start two listen() methods of the class using threads, or maybe even
handling multiple IPs using a single class instance.
But just knowing that you are using 'web.py' isn't very helpful.
What actual code are you using to run the webserver?
(Or maybe web.py contains a simple webserver in the module when it's 
run 
as main?)
HTH,
-Luke


Luke Paireepinart <rabidpoobear at gmail.com> wrote: 
> yes - i will ask the webpy authors
>
> but i expected to fond out a way to start two (or more)
> scripts (web.py) in different threads from one puthon's
> scrypt. OR two pythons interpretators to execute the above
> scrypt ?
>   
Python is a programming language. It's not a question about whether it's 
possible;
rather, it's who will do it.  If all you really want to do is start 2 
web.py scripts
from one python script you'd do something like this:
# ---- (non-working code)
import subprocess
subprocess.Popen('python web.py')
subprocess.Popen('python web.py')
#-----
This may or may not work.  You may only be able to subprocess actual 
executable files.
This is probably not what you want to do, though.
You'll probably have to learn how to program in Python to do this.
 ... ... ... ... ... ...

I just looked at web.py.
It's not a webserver.  It's a toolkit you use to write your own webserver.
Why are you under the impression that it's a webserver?
Did you just google for 'web server in Python' and find this?
If you're using some code that you've written (or found) to handle web 
requests
using the 'web.py' module, then show us your code and we'll tell you
how to make it into a class that listens on a single IP and how to
start two listen() methods of the class using threads, or maybe even
handling multiple IPs using a single class instance.
But just knowing that you are using 'web.py' isn't very helpful.
What actual code are you using to run the webserver?
(Or maybe web.py contains a simple webserver in the module when it's run 
as main?)
HTH,
-Luke

> cheers
> e.
>
>
> -----------------------------
>
> ??????. ???? ? ?????? ?? 4 ??????.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

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


 				
---------------------------------
Do you Yahoo!?
 Next-gen email? Have it all with the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/544a4e12/attachment.htm 

From anilmrn at yahoo.com  Thu Aug 17 11:17:26 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 17 Aug 2006 02:17:26 -0700 (PDT)
Subject: [Tutor] about threads
In-Reply-To: <1155710247.b9eec2c3f7c1a@mail.bg>
Message-ID: <20060817091727.68118.qmail@web55909.mail.re3.yahoo.com>

you can configure lighttpd virtual hosts to spawn new webpy instances for each of your ip address
Emilia can you explain your problem a little more I have spent quite some time using and asking questions abt the problems ur posting...
emilia12 at mail.bg wrote: Hi all,

my question is probably about the threads... I have two IPs
and i want to run web.py server for each IP in the same
time from one script file. I can run them in two command
boxes (and this works) but i want to do this from one ;-)
Maybe i can do this with 'threads' but how ? is there some
example ??

regards
e.
 		
---------------------------------
Do you Yahoo!?
 Next-gen email? Have it all with the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/1237fea9/attachment-0001.html 

From anilmrn at yahoo.com  Thu Aug 17 11:19:08 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 17 Aug 2006 02:19:08 -0700 (PDT)
Subject: [Tutor] about threads
In-Reply-To: <44E2C0B9.8060003@gmail.com>
Message-ID: <20060817091908.75152.qmail@web55912.mail.re3.yahoo.com>


You'll have to write multi-threaded code if you want it to run multiple 
threads :)
(Unless, of course, Web.py supports threads?)
Luke, what is the easiest way to run multithreaded programs from webpy
is there a page that has common gotchas and pitfalls for doing the same.


Luke Paireepinart <rabidpoobear at gmail.com> wrote: emilia12 at mail.bg wrote:
> Hi all,
>   
Hi!
> my question is probably about the threads... I have two IPs
> and i want to run web.py server for each IP in the same
> time from one script file. I can run them in two command
> boxes (and this works) but i want to do this from one ;-)
>
>   
if you run two instances of the python interpreter (like you're doing 
when you start two command windows,)
they're executing in different threads, it's just that the threads are 
OS level instead of application level.
Windows automatically switches between the two instances of the 
interpreter and gives them both time to do something.
This is why you can run an E-mail application at the same time as your 
web browser.
I suspect that OS-level threading in this way would be more efficient in 
regard to speed, but
it'd use more RAM because two interpreter instances would be loaded into 
memory at the same time.
I don't know what web.py is.
Is it something you wrote?
You'll have to write multi-threaded code if you want it to run multiple 
threads :)
(Unless, of course, Web.py supports threads?)
What's your experience with Python?
Do you need help with threads in general? threads in Python?
 >Maybe i can do this with 'threads' but how ? is there some
 >example ??
There are plenty of examples of threaded code that you could find by 
googling around,
or do you mean 'is there some example [of multi-threading the web.py 
program]??'
If the latter case, I guess you could find that by googling as well, if 
it exists.

> regards
> e.
>   

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


 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1&cent;/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/dbaeb6b4/attachment.htm 

From anilmrn at yahoo.com  Thu Aug 17 11:48:46 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 17 Aug 2006 02:48:46 -0700 (PDT)
Subject: [Tutor] Low level socket and threading code in python in HUGE
	websites -
Message-ID: <20060817094846.71075.qmail@web55902.mail.re3.yahoo.com>

What kind of low-level socket and threading code is necessary for a db 
  intensive site such as yahoo. How do we use it from python? does 
  anyone  have experience using it
 

http://redditblog.blogspot.com/2005/12/on-lisp.html 
 >From moving to python by the founders of reddit 
 

Because of the low-level socket and threading code we had to write, 
 reddit would not run on my Mac, and I was always tethered to our 
 FreeBSD development server. Not being able to program offline is a 
 pain. 
 
I would imagine that they aren't just using a database. 
 most of the "low level socket stuff" I've seen is about setting   
 timeouts and doing Async IO. 
 

 		
---------------------------------
Do you Yahoo!?
 Get on board. You're invited to try the new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/d9375179/attachment.html 

From anilmrn at yahoo.com  Thu Aug 17 11:55:04 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 17 Aug 2006 02:55:04 -0700 (PDT)
Subject: [Tutor] web application and database caching technique
Message-ID: <20060817095504.35141.qmail@web55911.mail.re3.yahoo.com>

i m trying to build a webapplication, i need to cache db records as it has become very slow the sql queries and retrival
can you guys helpe me out in designing cache structures/ hash tables for these cases 


1. Scenario One: 
    * Huge number of reads 
    * Few writes 
    * One row accessed from db per request 
    * All data written to db is used. 
    * Medium number of records. 
 
Since the large number of read need to be fast I chose this design: 
 
A hashtable caches records. They are cleared based on expiration time 
 and limit on maximum number of cached records. When a record is updated 
 in the db, it is deleted from the cache and recached next time it is 
 queried. This part could be handled by implementation you linked to. 
 
A persistent background thread periodically flushes the changed/new 
 values in the cache to the database. Additional calculations could be 
 added here to chose the optimal cache entrees to delete or precache. 
 
2. Scenario Two: 
    * Few reads 
    * Huge number of writes 
    * Many rows accessed from db per request 
    * Most data written to db is discarded. 
    * Huge number of small records. 
 
This is the strangest so far. Because of the huge number of records, 
 most of which will just be discarded anyway, I try to keep away from 
 the database as much as possible. When it's time to flush them to the 
 db I aggregate the records into groups, cpickle, and lzo them. I am 
 still playing with this but I notice a good performance improvement 
 already. 
 
3. Scenario Three: 
    * Huge number of writes 
    * Huge number of reads 
    * One row accessed from db per request 
    * Small number of records. 
 
This is the same as the first except I have space to cache everything. 
 This means I can get rid of the time() check for each cache check. 

 		
---------------------------------
Stay in the know. Pulse on the new Yahoo.com.  Check it out. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/5e7d90f8/attachment.htm 

From anilmrn at yahoo.com  Thu Aug 17 11:56:59 2006
From: anilmrn at yahoo.com (anil maran)
Date: Thu, 17 Aug 2006 02:56:59 -0700 (PDT)
Subject: [Tutor] server push
Message-ID: <20060817095659.94897.qmail@web55910.mail.re3.yahoo.com>

Hi guys 
 i was wondering if someone has successfuly used server push for apps 
 such as meebo etc using webpy 
 if so can you share some guidelines on using them 

I have a continuously running python webserver and a website, if there is a new mail or message, how do i ping and let the website or the user know without polling, using twisted web2

thanks a lot 
 

New server software is often required to make applications built using 
 Comet scale, but the patterns for event-driven IO on the server side 
 are becoming better distributed. Even Apache will provide a Comet-ready worker module in the upcoming 2.2 release. Until then, tools like Twisted, POE, Nevow, mod_pubsub, and other higher-level event-driven IO abstractions are making Comet available to developers on the bleeding edge. Modern OSes almost all now support some sort of kernel-level event-driven IO system as well. I've even heard that Java's NIO packages will start to take advantage of them in a forthcoming release. These tools are quietly making the event-driven future a reality. 
 
 			
---------------------------------
Do you Yahoo!?
 Everyone is raving about the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/a5ddeaba/attachment.html 

From kent37 at tds.net  Thu Aug 17 12:55:09 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 17 Aug 2006 06:55:09 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
Message-ID: <44E44B0D.7050309@tds.net>

Amadeo Bellotti wrote:
> hello is there a way if a condition is not met to restart the whole 
> program? for example if and if statement returns true then re start 
> the whole program?

You can probably achieve what you want just by structuring the program 
correctly. My guess you need to use nested loops, something like this:

while True:
  initialize_everything()
  while True:
    if something_is_wrong():
      break
    do_some_work()

This will do_some_work() until something_is_wrong(), then it will 
initialize_everything() and try again.

If the test for something_is_wrong() is buried deep in the code you can 
break the loop by raising an exception which you catch in the top-level 
loop.

Kent


From bds at waywood.co.uk  Thu Aug 17 14:52:56 2006
From: bds at waywood.co.uk (Barnaby Scott)
Date: Thu, 17 Aug 2006 13:52:56 +0100
Subject: [Tutor] Communicating with Win2000 runas.exe
Message-ID: <44E466A8.4010902@waywood.co.uk>

I have a problem which I was hoping that Python could solve for me, but
I have become stuck for days now after only 2 lines of code.

My son has a Microsoft game on a shared family computer, which Microsoft
in its infinite wisdom requires you to run as 'administrator'. Call me
old-fashioned but I don't want to promote an 8 year-old to administrator
just so he can run his game!

Enter 'runas.exe'...

However, because we are on Windows 2000, runas does not allow you to
save a password - it has to be entered every time: not much further forward.

So I'm thinking along these lines:

import subprocess
sp = subprocess.Popen(r'C:\WINNT\SYSTEM32\runas.exe /user:administrator
C:\Program Files\Microsoft Games\Age of Mythology\aom.exe')
#some sort of code to send the password here...
#help!

Sure enough, this brings up a prompt asking for the administrator's
password, but I can't get anything to work in terms of getting the 
script to provide the password.

Am I barking up the wrong tree here? Any clues would be gratefully
received. (Even if I do get this to work, my next trick is to hide the
password from any prying eyes looking at the script...)

Thanks

Barnaby Scott



From tim.golden at viacom-outdoor.co.uk  Thu Aug 17 15:50:09 2006
From: tim.golden at viacom-outdoor.co.uk (Tim Golden)
Date: Thu, 17 Aug 2006 14:50:09 +0100
Subject: [Tutor] Communicating with Win2000 runas.exe
Message-ID: <CCAC78D42E32184F8E26DC163DB98306C1B397@vogbs009.gb.vo.local>

[Barnaby Scott]

| So I'm thinking along these lines:
| 
| import subprocess
| sp = subprocess.Popen(r'C:\WINNT\SYSTEM32\runas.exe 
| /user:administrator
| C:\Program Files\Microsoft Games\Age of Mythology\aom.exe')
| #some sort of code to send the password here...
| #help!

I *think* -- and I'm happy to be wrong -- that there's
no way you're going to get that password in there. One
place to start looking might be:

pywinauto - http://pywinauto.pbwiki.com/

which lets you automate Windows in general; don't know
how much use it'll be here. 

Alternatively, look into the pywin32 package, and in 
particular at the win32security functions which let you 
impersonate another user. They're not trivial to use, 
but their use has been explained a few times over the 
years I think. Mostly by Roger Upole who wrote most if 
not all of the Python bindings.

Here's a post which looks useful; you'll have to hunt
around for others:

http://groups.google.com/group/comp.lang.python/msg/6bbefb9d4d45d253

I suggest you ask this question again on the main
python / python-win32 lists; it's a bit too platform-specific
for the tutor list, I would say.

TJG

________________________________________________________________________
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________

From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 16:34:00 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 07:34:00 -0700 (PDT)
Subject: [Tutor] (no subject) (fwd)
Message-ID: <Pine.LNX.4.64.0608170733570.745@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Thu, 17 Aug 2006 09:44:40 -0400
From: Amadeo Bellotti <amadeo.bellotti at gmail.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] (no subject)

Mr. Yoo im working on a program to write a sudoku puzzle and if something is
wrong with the last row i need to re make the whole puzzle over again.

On 8/17/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
>> hello is there a way if a condition is not met to restart the whole
>> program? for example if and if statement returns true then re start the
>> whole program?
>
> Question before we go on: why are you trying to do this?
>
> It's possible to do this, but it sounds so unusual that I want to know
> more about the problem.
>

From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 16:54:47 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 07:54:47 -0700 (PDT)
Subject: [Tutor] (no subject)
In-Reply-To: <Pine.LNX.4.64.0608170733570.745@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0608170733570.745@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.64.0608170741090.745@hkn.eecs.berkeley.edu>

> Mr. Yoo im working on a program to write a sudoku puzzle and if 
> something is wrong with the last row i need to re make the whole puzzle 
> over again.

Hi Amadeo,

In the future, please use the "Reply to All" feature of your email client, 
so that we can keep the conversation on the mailing list.

Here's a separate question that's related to the first: can you write a 
function that asks the user to enter a word, and continues prompting until 
the user enters a non-empty word?

From amadeo.bellotti at gmail.com  Thu Aug 17 16:59:24 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Thu, 17 Aug 2006 10:59:24 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <Pine.LNX.4.64.0608170741090.745@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0608170733570.745@hkn.eecs.berkeley.edu>
	<Pine.LNX.4.64.0608170741090.745@hkn.eecs.berkeley.edu>
Message-ID: <d7253a230608170759x49d2cfb4y1bb5faabb0290444@mail.gmail.com>

Yes I can Mr. Yoo, but i dont really want to make my whole program a loop.

On 8/17/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
> > Mr. Yoo im working on a program to write a sudoku puzzle and if
> > something is wrong with the last row i need to re make the whole puzzle
> > over again.
>
> Hi Amadeo,
>
> In the future, please use the "Reply to All" feature of your email client,
> so that we can keep the conversation on the mailing list.
>
> Here's a separate question that's related to the first: can you write a
> function that asks the user to enter a word, and continues prompting until
> the user enters a non-empty word?
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/9ff9de5c/attachment.html 

From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 17:46:39 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 08:46:39 -0700 (PDT)
Subject: [Tutor] (no subject)
In-Reply-To: <d7253a230608170759x49d2cfb4y1bb5faabb0290444@mail.gmail.com>
References: <Pine.LNX.4.64.0608170733570.745@hkn.eecs.berkeley.edu>
	<Pine.LNX.4.64.0608170741090.745@hkn.eecs.berkeley.edu>
	<d7253a230608170759x49d2cfb4y1bb5faabb0290444@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0608170836110.4371@hkn.eecs.berkeley.edu>



>> > Mr. Yoo im working on a program to write a sudoku puzzle and if
>> > something is wrong with the last row i need to re make the whole puzzle
>> > over again.

>> Here's a separate question that's related to the first: can you write a
>> function that asks the user to enter a word, and continues prompting until
>> the user enters a non-empty word?

Hi Amadeo,


> Yes I can Mr. Yoo, but i dont really want to make my whole program a 
> loop.

Ok.  Why not?  I'm curious: is there a particular constraint you're trying 
to work under, or is it something else?

Also, I'm not sure what you mean by "whole program".


In any case, here's a way to do it without an explicit 'for' or 'while' 
loop:

####################################
def ask_for_input():
     msg = raw_input("enter a word:")
     if msg:
         return msg
     else:
         return ask_for_input()
####################################

This would not be the idiomatic way to do this in Python only because of a 
technical limitation in the main Python implementation (it doesn't support 
"tail call optimization").

Still, would this be more acceptable to you, or do you also consider this 
a "loop"?

(Personally, I do. *grin*)

From kermit at polaris.net  Thu Aug 17 17:49:00 2006
From: kermit at polaris.net (Kermit Rose)
Date: Thu, 17 Aug 2006 11:49:00 -0400 (Eastern Daylight Time)
Subject: [Tutor] All of Kermit's E-Mails
References: <44E40C99.3060901@gmail.com>
Message-ID: <44E48FE7.000001.03640@YOUR-4105E587B6>

 
 
From: Luke Paireepinart 
Date: 08/17/06 02:29:01 
To: Kermit Rose 
Cc: tutor at python.org 
Subject: Re: [Tutor] All of Kermit's E-Mails [was: Global Variables] 
 
 
>>>
 
I really dislike the way you reply. 
Follow the standard format! Leave all the greater-than signs before the 
previous person's reply 
so that it will be structured correctly and easy to read. All of this 
star business is bad. 
 
*************
 
Suggest an alternative,
because my email program does not insert the > sign like the standard email
program does.
 
I also prefer the standard format, and the first few times I replied in
email I
typed in all the > in front of each line.
 
After a while I decided that I should find some alternative equivalent that
took less time.
 
>>>
 
Okay. 
>From this it appears that you have no academic training in programming. 
The term 'side-effect' means that something outside the scope of the 
called function is modified by the called function. 
 
 
Here is a very basic example. 
 
#--- test.py 
a = ['a','b','c'] 
def modify_list(alist): 
del(alist[0]) 
 
modify_list(a) 
modify_list(a) 
print a 
#--- 
 
#--- output of test.py 
['c'] 
#--- 
 
********************
 
>From your example:
 
You haven't declared any variable global.
does 
a = [a',b'c']  
implicitly  declare the variable "a" to be global because it is not inside a
function definition?
 
I did not know Python syntax  would permit statements to not be inside some
function definition.
 
I see that modify_list deletes the zero'th element.
 
The structure of my factor functions are such that this type of mistake
could not happen.
 
If I knew how, I would follow up Alan's suggestion of making the module into
a class.
 
>>>
 
Now remember that in Python, when you pass a variable to a function, 
only the reference is passed to the function. 
Imagine that variables are themselves references (which they are.) 
 
a = ['a','b','c'] 
 
creates the following picture: 
 
a ------> ['a','b','c'] 
 
modify_list(a) 
 
doesn't do 
 
modify_list(['a','b','c']) 
 
it does 
 
modify_list(ptr) where ptr ------> ['a','b','c'] <----- a 
 
they both refer to the same object ( a python list containing three
characters.) 
 
now when in the body of modify_list we say del(alist[0]), what takes place
is 
the index operator, [0], says 'what object is the variable 'alist' pointing
to? 
and python says 'alist ----> ['a','b','c'] <---- a' 
so when we delete the element out of alist we're also deleting the element 
out of the calling function's list. 
This is probably NOT desired behavior. 
As such it's an unwanted side-effect. 
 
*******************
 
This confuses me.
 
Isn't the calling functions list  [a',b',c'} ?
 
Therefore,  wouldn't the resultt of modify_list(a) 
be 
[b',c']?
 
That's what I would expect it to be and what I would want it to do.
 
>>>
 
 
A function printing to the screen is also considered a side-effect. 
Anything a function does that affects anything outside of its own scope 
is considered a side-effect. 
 
*****************
 
Ok.  Why is this  bad.  If I'm using global  variables, this would be
exactly what I would want.
 
But I don't insist on using global variables.
 
The idea of making a factor class appeals to me.  I haven't yet learned how.
 
.>>>
 
 
To refresh your memory, here's the next part of the e-mail I'm going to
address: 
 
>The names have very little to do with it, the danger of global 
>variable 
>use is the reliance on side-effects and the tight coupling that you 
>introduce between the calling module and the called module. 
>Changes to the state of the calling module in an unpredictable 
>manner lead to subtle bugs which are extremely hard to see and fix. 
>***** 
>What do you mean by tight coupling? 
>The only change I can see that would lead to a bug would be if I changed
the 
>name of the global variable in 
>the calling routine and not in the function it called. 
>I would know not to do that. 
 
 
'tight coupling' is an English phrase meaning roughly 
(for our purposes) 'close interaction' or 'dependence on each other.' 
 
you say, I quote: 
'The only change ... that would lead to a bug would be if I changed the 
name of the global variable in the calling routine.' 
I think you're misunderstanding Alan. 
consider this following example 
(it was hard to come up with something this convoluted) 
 
#--- start code 
def b(): 
global has_been_greeted 
has_been_greeted = False 
print "function B is doing lots of stuff" 
return "whatever we did in function B that's so important" 
 
def greet(): 
global has_been_greeted 
if has_been_greeted: 
print 'we already greeted you.' 
else: 
print 'hello!' 
has_been_greeted = True 
 
def c(): 
print "function C is doing lots of stuff." 
a = b() 
print "function C is using value a here." 
 
b() 
greet() 
greet() 
c() 
greet() 
 
# --- end code. 
 
Now we know we're going to call b() every time on startup, 
so we set has_been_greeted to false inside of it. 
Then we call greet, once b() is done calculating its stuff, 
so it will greet the customer. 
Then we call greet again to make sure that we already greeted them. 
(say we're debugging our program and we want to make sure greet's 
working correctly.) 
 
Now we call function C, which relies on function b to get a value 
that it needs for one of its calculations. 
Oops, we forgot that b() resets has_been_greeted back to false 
every time it's called. 
Now when we call greet after function c again, it greets them again! 
But it's already greeted them so it shouldn't have greeted them. 
 
Now imagine this is much more complicated and there are multiple global 
variables 
that you're setting all over the place to store your values, 
and then imagine trying to find something this obscure. 
 
A much more straightforward way to do this would be: 
 
#--- start code 
def b(): 
print "function B is doing lots of stuff" 
return "whatever we did in function B that's so important" 
 
def greet(): 
print 'hello!' 
 
def c(): 
print "function C is doing lots of stuff." 
a = b() 
print "function C is using value a here." 
 
b() 
greet() 
has_been_greeted = True 
if has_been_greeted == False: greet() 
c() 
if has_been_greeted == False: greet() 
#--- 
 
I know this was a stupid example but it's all I could come up with. 
does it help you see how global variables could give you trouble? 
Maybe Alan can fix my example so it makes more sense. 
 
*************************
 
I believe I understand your example.
 
Basically you are saying that if my module becomes sufficiently complicated,
I may lose track of how I use the global variables and violate my preset
rules for how to use them.
 
>>>
 
 
I see here you started using Greater-than signs to separate the Original
Post from your replies. 
WTF. RTFM. This is almost as bad as before. 
 
 
****************
 
Please suggest an alternative that is relatively quick to compensate for my
email program, 
Incredimail, which does not have an option to insert the > in from of each
line of the original post.
 
>>>
 
 
Now I don't have the additional stress of trying to sort out who is speaking
at any given time, 
you or the person you're replying to, but I have these big columns of
multi-colored lines to deal with. 
In my e-mail client, Thunderbird, it converts every > sign to a vertical
line of a different color, 
so I can tell the different levels of replies in any given e-mail. 
This is super-helpful, unless something like this comes along, and all it
does is space 
out all the messages a tremendous amount and look ugly. 
Why can't you just use the convention and leave the >> things there? 
They're there for a reason. 
Don't fix somethin' that ain't broke, please. 
 
 
***********
 
Unfortunately, in my email client, Incredimail, it is  broken.
 
Thanks for telling me the effect of the > sign in your email client,
Thunderbird.
 
I changed all my long lines of > signs to exactly three > signs on a line.
 
 
>>> 
 
No, it's not that global variables are not implemented correctly. 
You must understand that there are thousands of people using Python every
day, 
and phrases like 'not implemented correctly' or 'there's a bug in python'
are 
converted in my ears to '*i'm complaining because i can't get my program to
work*' 
It's identical, to me, as when I'm playing Counter-Strike and someone starts

yelling 'HACKER!' every time they get killed. 
 
 
*******
 
:)   Yes.  I understand your response.
 
 
>>>
 
It's ____much____ more likely that the person is just good at Counter-Strike
than they're cheating, 
especially since there are a lot of anti-cheat measures. 
 
It's ____much____ more likely that your program has a bug than Python itself
 
because there is a lot of quality-control when a programming language is
used 
frequently by many very skilled coders. 
 
 ****************
 
Well,  I would not have claimed a possible bug in Python if I could see how
my code could possibly have
been responsible for 
 
a variable to have one value in the called function,
and have a different value when it's returned to the calling function.
 
>>>
 
 
 Alan is being diplomatic here. 
 
I would not call what you sent 'documentation.' 
 
The tangled mess of your functions doesn't prove there's a bug in python, 
it just makes me think you messed up the value somewhere along the way. 
 
 
******************
 
Suggest a way for me to make more clear what is happening.
 
>>>
 
What Alan means is that your program incorrectly handles certain data values

because your functions aren't written correctly. 
 
Your first thought when your program doesn't do what you expect it to 
should not be to blame the return statement of being buggy, 
 
 
but to first blame yourself. 
It's much more likely that you're at fault. 
I'm not saying this directly at you. 
If I wrote a function that returned incorrect values, 
I would assume it's my fault too. 
 
 
********
 
Indeed.   I first seek to find the error in my code.
 
Only after I proved that the variable changed in value between just before
the return statement
in the called routine
 
and after its reception in the calling routine
 
did I suggest that there may be a bug in Python.
 
>>>
 
 
You have to understand that Python has been used for years 
and if there was such a fundamental bug, no matter how obscure (only
occuring on certain return values), 
it would have been found by now. 
 
 
*****
 
I would have expected so also.
 
 
That is why this strange behavior surprised me.
 
 
 >>>
 
 
Because it's impractical to search for a certain type of error it must not
be that error? 
Just dwell on that statement a bit and tell me if you still believe it. 
 
 
 
>The error is occuring between the return statement in the called function 
>and the picking up of that value 
>in the calling function. 
 
so show us. 
 
This is the way I would prove this, if it were my program that uncovered
this 'bug.' 
 
 
#--- 
def func_that_causes_bug(a): 
 
print "function is doing a bunch of complex calculations and such." 
v = 2322**a 
c = 55/float(v) 
d = v - a + 543 
value = d / 45 
 
print "this is where the problem arises." 
print "Before I return the value, it is :%s" % value 
return value 
 
tmp = func_that_causes_bug(564) 
print "And after I return the value, it is :%s" % tmp 
 
#--- 
 
*****
 
That is exactly what I did!!!!
 
 
>>>
 
Do you understand why this would evidence the bug you mentioned? 
You say it's a problem with the returning of the value. 
So print the value immediately before the return and immediately after. 
We'll see if it changes in transit as you claim. 
 
*****
 
Yes.  That is exactly what I did!!!
 
 
>>>
 
 
 
 
>Can you post actual code to illustrate the problem? Don't post your 
>entire module; just show us the functions involved, the input that 
>causes the problem, and what output you expect to get. 
>-- 
>John. 
> 
>******* 
> 
>Here is the output that illustratrates the problem. After the output I'll 
>list the code for the called function, 
>strongfac, 
> 
>and the calling function, fermat. 
 
[snip a ton of debug output.] 
 
 
This doesn't help us at all. What the heck was all that? 
You must understand that I have no idea what your function is supposed 
to do. 
Treat me like a child. Explain everything to me. 
 
What part of this output isn't what you wanted? 
 
***********
 
Huh?
 
That "ton of debug output" is exactly what you said you wanted.
 
So perhaps we should take a closer look at it.
 
Perhaps we should talk in private email  a few times to get the output that
is generated
more readable to you and the others.
 
 
>>>
 
 
># def strongfac(z,w): 
># x = gcd(z,w-1) 
># if x > 1: 
># if x < z: 
>[snip the rest of strongfac] 
># def fermat(z,maxdiff,pmap,plist,sqlist,sqresidue,torials,limitsteps): 
># for j in range(2,3): 
># print " " 
># print " Try to find factors by using power of ",j," mod z 
as a 
>[snip the rest of fermat] 
 
 
Why the CRAP did you put # signs before every line? 
I spent about 10 minutes pressing delete, down-arrow, delete, down-arrow. 
Going through all that trouble just so I could run the code was a pain 
in the rear. 
 
 
******
Either my email program or your email program removes leading blanks.
 
Putting a # in column 1 is
 
one way to transmit the code in a way that preserves the indentation.
 
Suggest an alternative way of transmitting code.
 
>>>
 
Remember when we were talking about UI usability earlier? 
Your code usability would be greatly improved if I didn't have to remove 
a comment from every line to test it. 
 
******
 
What does UI mean?
 
Could you construct a program to delete column 1 from each line?
 
Perhaps such a program already exist in the editor.
 
 
>>>
 
Also, in your example call: 
 
>IDLE 1.1.2 
> >>> import factor34 
> >>> from factor34 import testrange 
> >>> testrange(10**14+37,10**14+37) 
 
You called testrange. 
Now John originally said 'show us which functions are involved.' 
Well, after I had gone through the trouble of un-commenting all your code, 
it turned out that I didn't even have all the pieces there. 
 
 
So I went back in e-mail history and downloaded the attached 
'factor34.py' file. 
Now I wish I didn't have to do this, because you could've made 
improvements in it since then. 
But it's the only way I can get a functional test file. 
 
Turns out testrange depends on x depends on y depends on z depends on ..... 
basically all of the functions in the module depend on each other. 
 
This is obviously a case for ... .dun-dun-dun!.... object-oriented 
programming. 
When you have a collection of functions that all operate together to 
create something, 
you make a Class to contain them. 
 
I think just in the process of doing this you might learn what's wrong 
with your program. 
 
 
***
 
I am quite willing to make a Class to contain them, after I learn how.
 
And perhaps, after we rewrite my module as a class, 
the strange behavior will change, perhaps it won't.
 
If the strange behavior does not change, then it should be easier tracing 
what is happening.
 
>>>
 
 Link me to all the Wikipedia articles I need in order to understand what 
you're trying to do. 
 
 
I'll help you rewrite this program from scratch if you want. 
We'll make it object-oriented the whole way. 
But there is no hope I will understand factor34. 
I will not even try. 
 
*****
 
Thanks very much.  I will be glad to get your help making my module into a
class.
 
I don't know what information you might need to understand what I'm trying
to do.
 
So, if we get started converting to object oriented format, then we may
figure out
what Wikipedia articles might be useful.
 
 
 
>>>
 
Sorry if I was too harsh anywhere along the way. 
Feel free to point any of this out and I'll apologize. 
But this is my honest opinion of the e-mails I've received from you so far. 
 
******
 
No problem.  I value honesty.
 
 
>>>
 
I don't think this is a good programming project for you to be learning 
a new language with. Perhaps you should do something simpler. 
If you'd like some recommendations I'd be happy to give some. 
 
 
***
 
This project is important to me, independently of my need to learn Python
well.
 
>>>
 
Have a good day. 
-Luke 
 
 
****
 
Thank you very much.
 
 
Kermit Rose    <  kermit at polaris.net  >
 
 
 


From kermit at polaris.net  Thu Aug 17 18:13:29 2006
From: kermit at polaris.net (Kermit Rose)
Date: Thu, 17 Aug 2006 12:13:29 -0400 (Eastern Daylight Time)
Subject: [Tutor] Actual code that illustrates problem
References: <Pine.LNX.4.64.0608170024240.31579@hkn.eecs.berkeley.edu>
Message-ID: <44E495A9.000003.03640@YOUR-4105E587B6>

>>>
 
From: Danny Yoo 
Date: 08/17/06 04:02:35 
To: Kermit Rose 
Cc: Tutor 
Subject: Re: [Tutor] Actual code that illustrates problem 
 
> # def strongfac(z,w): 
[function body cut] 
 
Ok, let's go through this step by step. 
 
* What is the intent of strongfac? 
 
*******
 
To try to find factors of z, using w.
 
>>>
 
* What are the inputs? What is 'z', and what is 'w'? 
 
******
 
z is the number to be factores.
 
w is a "witness", a number that may help find the factors of z.
 
>>>
 
* What are the outputs? What is the return value of strongfac? 
 
****
 
The output is the return value of strongfac.
 
fac = [ x, y, difficulty of factoring z using w]
 
or  
fac = [0,0,0] if strongfac could not factor z using w.
 
 
 
>>>
 
Same questions for fermat(). What are the inputs and outputs, and what's 
the intent? 
 
The input z is the number to be factored.
 
The other inputs are constants which may help in finding factors of z.
 
 
>>>
 
Get those out and documented, because although I think I can guess at it, 
I'd rather know that we are sharing the same understanding. 
 
****
 
????
 
How?
 
 
>>> 
 
There's a bit of code in strongfac() that's nonsensical from a purely 
technical sense. For example: 
 
> # face = [x,y,0] 
[some code cut] 
> # face[0] = x 
> # face[1] = y 
> # face[2] = 0 
 
The three assignments to face[0] through face[2] don't do anything 
effective and clutter the code. 
 
 ***
 
In fact, I knew that.  I inserted it in an attempt to overide the apparent
bug that I saw.
 
Sometimes it worked.
 
>>>
 
In fermat(), there are magic numbers: 
 
# for j in range(2,3): 
^^^^ 
 
# for k in range(100): 
^^^ 
 
These seem pretty arbitrary. Can you explain them? 
 
*****
 
Yes.  These are limits of ranges.  I had not yet evolved the module to
replace the range limits with parameters.
 
>>> 
 
The strongfac() function you have is a good case for writing smaller 
functions: I can not tell where the function really ends. I see that you 
have several sub-tests, which I'll categorize as: 
 
* P-1 
* square = square 
* ... 
 
and there's a few others that I can not categorize yet. But I bet you 
can. Have you considered breaking those out as independent helper 
functions? 
 
 
*****
 
I have considered it. 
 
>>>
 
Most of us don't have experience with number theory. What people here on 
the list have is experience with writing software. My experience informs 
me that the functions you're writing are way too large. They are 
monolithic and imposing enough that very few people will be able to (or 
want to!) understand their reasoning. They really cry out to be broken 
into smaller subtest functions that can be individually understood. 
 
********
 
Luke has promised to work with me to write my module as a class.
 
Perhaps this will automatically shorten the individual functions.
 
I don't expect that you would need to know much number theory to understand
what my program is doing, but I'll be glad to answer any question you may
have of it.
 
 
>>>  
 
You mentioned later that: 
 
> One of the numbers for which strongfac fails to return factors which it 
> correctly calculates is 100000000000037 
 
Two questions: 
 
* How do you know that it is being "correctly calculated?" 
 
****
 
Part of the process of finding  any factor is to divide it into z to get
remainder equal to zero.
 
Also when I noticed the problem, I printed it out in strong fac, and also in
fermat 
and then saw the strange behavior of having one value before return 
and another value after return.
 
>>>
 
* How do you know that your program is doing something wrong? 
 
That is, state explicitely to us what you expected the program to do. 
What is the expected result, in terms of return values, that your function 
failed to produce? What part of the program --- which particular subtest 
--- should have returned those values? Where are you looking at? 
 
 
****
I first noticed it when I had
 
Strong fac calculate the factors if possible.  If it found factors,
 
it printed out that it had found factors using w, and it printed the value
of w.
 
After I noticed that strongfac printed out that it had found factors, but
fermat
did not pick up those factors, I looked more closely.
 
After I had documented to myself that the return value had changed by the
time it got back
to fermat,  I emailed the Tutor list.
 
>>> 
 
Again, you have to assume that we don't know anything about number theory. 
Things that may seem "obvious" to you are not obvious to this audience. 
*grin* 
 
 
****
 
So noted.   I had not intended to ask any number theory questions here.
 
Kermit   <  kermit at polaris.net   >
 
 
 
 
 


From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 18:16:02 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 09:16:02 -0700 (PDT)
Subject: [Tutor] All of Kermit's E-Mails
In-Reply-To: <44E48FE7.000001.03640@YOUR-4105E587B6>
References: <44E40C99.3060901@gmail.com>
	<44E48FE7.000001.03640@YOUR-4105E587B6>
Message-ID: <Pine.LNX.4.64.0608170859450.4371@hkn.eecs.berkeley.edu>

> Suggest an alternative way of transmitting code.

Hi Kermit,

Try sending the code as a file attachment.  It's large enough that we want 
to make sure it goes through without being messed up, but small enough 
that it can still be posted to the list.

Alternatively, post the code on the web somewhere and send the list a link 
to the URL.  This is preferable for large blocks of code, and your 
factoring program is large enough that this would also be a good way to 
share the code with the mailing list.


Just as a side note: you may want to investigate a good email client such 
as Thunderbird if you have spare time.

     http://www.mozilla.com/thunderbird/

Much of the frustration I've been seeing on this thread deals with 
IncrediMail's feature set; what it is providing you isn't so well suited 
for the kind of technical communication that's on this list.


> This is obviously a case for ... .dun-dun-dun!.... object-oriented 
> programming. When you have a collection of functions that all operate 
> together to create something, you make a Class to contain them.

I'm going to have to interject and disagree with Luke here; for Kermit's 
application, classes are not necessary.  Kermit's still trying to learn 
basic structured programming with functions; I'm not convinced that 
leaning Kermit toward Object Oriented Programming is going to help matters 
much.


Good luck to you!

From singh01 at gmail.com  Thu Aug 17 18:14:00 2006
From: singh01 at gmail.com (Nagendra Singh)
Date: Thu, 17 Aug 2006 12:14:00 -0400
Subject: [Tutor] Which Book
Message-ID: <cd2d0ceb0608170914u2b1fdc6dt8ac9d045cb69fcef@mail.gmail.com>

Hi All,

I have very little programming experience, I have decided to learn
Python..there are tons of material and refernces on the web-pages, can
you guys please suggest what is the best way to start or which ONE
book which I should follow to start.

thanks..

Nagendra

From jim at well.com  Thu Aug 17 18:34:50 2006
From: jim at well.com (jim stockford)
Date: Thu, 17 Aug 2006 09:34:50 -0700
Subject: [Tutor] Which Book
In-Reply-To: <cd2d0ceb0608170914u2b1fdc6dt8ac9d045cb69fcef@mail.gmail.com>
References: <cd2d0ceb0608170914u2b1fdc6dt8ac9d045cb69fcef@mail.gmail.com>
Message-ID: <4DE95732-2E0E-11DB-B3EC-000A95EA5592@well.com>


    i think it's a mistake to concentrate on one book.
Cull responses and pick three books to start with.
    The benefit is that where one book presents a
poor explanation, another will do a good job (and
one book will omit certain things that another
presents).
    Also, you'll probably find yourself more often
refreshed by turning from one book to another as
you proceed.

On Aug 17, 2006, at 9:14 AM, Nagendra Singh wrote:

> Hi All,
>
> I have very little programming experience, I have decided to learn
> Python..there are tons of material and refernces on the web-pages, can
> you guys please suggest what is the best way to start or which ONE
> book which I should follow to start.
>
> thanks..
>
> Nagendra
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 18:57:40 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 09:57:40 -0700 (PDT)
Subject: [Tutor] Actual code that illustrates problem
In-Reply-To: <44E495A9.000003.03640@YOUR-4105E587B6>
References: <Pine.LNX.4.64.0608170024240.31579@hkn.eecs.berkeley.edu>
	<44E495A9.000003.03640@YOUR-4105E587B6>
Message-ID: <Pine.LNX.4.64.0608170916190.4371@hkn.eecs.berkeley.edu>



> To try to find factors of z, using w.
>
>>>>
>
> * What are the inputs? What is 'z', and what is 'w'?
>
> ******
>
> z is the number to be factores.
>
> w is a "witness", a number that may help find the factors of z.

[My apologies in advance; this message is a bit long.]



Hi Kermit,

Ok, good.  You should add this as a comment to the function's header, so 
that other people can see this.  Here is an example:

def strongfac(z, w):
     """z is the number to be factored.
        w is a witness that may help find the factors of z.
     """
     ## rest of function body.

At the very beginning of the function body, we're allowed to make a string 
that acts as function documentation.  Python programmers expect this kind 
of "documentation string" at the head of a function, so that they're 
prepared for what comes next.



> * What are the outputs? What is the return value of strongfac?
>
> The output is the return value of strongfac.
> fac = [ x, y, difficulty of factoring z using w]
> or
> fac = [0,0,0] if strongfac could not factor z using w.

Great!  Ok, I'm assuming that 'x' and 'y' are two arbitrary factors of 
'z'.  Are there other properties about x and y that you want to state, 
such as: "x is always prime", or do we make no guarantees about this?



At this point, I'm distilling what you've said into a documentation 
string:

def strongfac(z, w):
     """strongfac: number number -> [x, y, difficulty]

     Factors z into two pieces, returning those two pieces as well as the
     difficulty in factoring z.  w is a witness that may help find the
     factors of z.

     If no factors can be found, returns [0, 0, 0].
     """
     ## rest of function body.


Does this make sense so far?  The point is to make it easy for humans to 
understand your program.




>> # face = [x,y,0]
> [some code cut]
>> # face[0] = x
>> # face[1] = y
>> # face[2] = 0
>
>> The three assignments to face[0] through face[2] don't do anything 
>> effective and clutter the code.
>
> In fact, I knew that.  I inserted it in an attempt to overide the 
> apparent bug that I saw.
>
> Sometimes it worked.

This is a bad sign.  It should not have worked.  *grin*

Next time you hit something mysterious like this, mention it to the list. 
It'll be a good puzzle for the others here to take a look at.  Your code 
should be as rational as possible.  Don't just add code in hoping that 
it'll fix some problem: try to understand why it's not working first. 
Look for root causes.




>> In fermat(), there are magic numbers:
> [cut]
>> These seem pretty arbitrary. Can you explain them?

> Yes.  These are limits of ranges.  I had not yet evolved the module to 
> replace the range limits with parameters.



About strongfac():

> Have you considered breaking those out as independent helper functions?
>
> I have considered it.

Consider it more strongly.  *grin*



Here, I'll help you get started.  strongfac() starts off looking something 
like this:

#################################################################
def strongfac(z,w):
     x = gcd(z,w-1)
     if x > 1:
         if x < z:
             y = z/x
             return [x,y,0]
     w2 = (w * w)%z
     s = ksqrt(w2)
     if w2 == s * s:
         if s != w:
             x = gcd(z,kabs(w2 - s))
             if x > 1:
                 if x < z:
                     return [x,y,0]
     ## other tests
################################################################

(I'm trimming out the print statements just to keep this small.)


Those two tests, the P-1 and square=square tests, can be broken out into 
two separate functions.  Let's see what this might look like:

############################################################
def check_p_minus_1(z, w):
     """Checks to see if z can be factored by the P-1 Method.
     If so, returns [x, y, 0]; otherwise, returns [0, 0, 0].
     """
     x = gcd(z,w-1)
     if x > 1:
         if x < z:
             y = z/x
             return [x,y,0]
     return [0, 0, 0]
############################################################

This "refactoring" allows us to look at check_p_minus_1's action in 
isolation, and also makes it easier to ask questions like: what happens if 
x > z?  Is it really possible that the return value from gcd() is bigger 
than the initial inputs to gcd()?  (As far as I understand gcd(), NO!)

So this refactoring is useful just as a matter of letting someone just 
look at a small bit of code and understand it completely.  As far as I can 
understand, check_p_minus_1() should work even if it's simplified to:

##########################
def check_p_minus_1(z, w):
     x = gcd(z, w-1)
     if x != 1:
         return [x, z/x, 0]
     return [0, 0, 0]
##########################




Anyway, once we break out the P-1 check out into a separate function, we 
can rewrite strongfac() to use check_p_minus_1():

################################
def strongfac(z, w):
     face = check_p_minus_1(z, w)
     if face != [0, 0, 0]:
         return face
     ## ... other tests here
################################


Can you try this?  Can you try breaking out the square=square test in a 
similar way to how I treated the check_p_minus_1() code?




The high level goal here is to turn strongfac() into a very simple looking 
function.  In pseudocode, it'll look something like:

############################
def strongfac(z, w):
     use check_p_minus_1 test and return if it succeeds
     use square=square test and return if it succeeds
     ...
############################

This will make strongfac very regular to read.  It'll also make it much 
easier to trace why one of your return values isn't returning what you 
want.

From kent37 at tds.net  Thu Aug 17 19:11:19 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 17 Aug 2006 13:11:19 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>	
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
Message-ID: <44E4A337.30701@tds.net>

Amadeo Bellotti wrote:
> Mr. Johnson i was hoping i didnt have to make my whole program into a 
> loop because its about 900 lines of code and tabbing that would take a 
> long time
If your whole program is 900 lines without a subroutine then you have 
more problems than just tabbing...really, a program this big should have 
many functions to divide up the work. Looking for a workaround for poor 
program structure is not a good solution in the long run; fixing the 
program structure so it is workable is a better idea.

As a practical matter, many editors allow you to select and indent a 
block, including TextPad and Eclipse, the two editors I usually use.

Kent

PS please reply to the list, not to me personally.
>
>
>
> On 8/17/06, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> 
> wrote:
>
>     Amadeo Bellotti wrote:
>     > hello is there a way if a condition is not met to restart the whole
>     > program? for example if and if statement returns true then re start
>     > the whole program?
>
>     You can probably achieve what you want just by structuring the
>     program
>     correctly. My guess you need to use nested loops, something like this:
>
>     while True:
>       initialize_everything()
>       while True:
>         if something_is_wrong():
>           break
>         do_some_work()
>
>     This will do_some_work() until something_is_wrong(), then it will
>     initialize_everything() and try again.
>
>     If the test for something_is_wrong() is buried deep in the code
>     you can
>     break the loop by raising an exception which you catch in the
>     top-level
>     loop.
>
>     Kent
>
>     _______________________________________________
>     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>     http://mail.python.org/mailman/listinfo/tutor
>     <http://mail.python.org/mailman/listinfo/tutor>
>
>



From amadeo.bellotti at gmail.com  Thu Aug 17 19:28:56 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Thu, 17 Aug 2006 13:28:56 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <44E4A337.30701@tds.net>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
	<44E4A337.30701@tds.net>
Message-ID: <d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>

thank you Mr. Johnson this is my first program so its a little sloppy. I'm
using gedit ill check out the other editors that u have thank you

On 8/17/06, Kent Johnson <kent37 at tds.net> wrote:
>
> Amadeo Bellotti wrote:
> > Mr. Johnson i was hoping i didnt have to make my whole program into a
> > loop because its about 900 lines of code and tabbing that would take a
> > long time
> If your whole program is 900 lines without a subroutine then you have
> more problems than just tabbing...really, a program this big should have
> many functions to divide up the work. Looking for a workaround for poor
> program structure is not a good solution in the long run; fixing the
> program structure so it is workable is a better idea.
>
> As a practical matter, many editors allow you to select and indent a
> block, including TextPad and Eclipse, the two editors I usually use.
>
> Kent
>
> PS please reply to the list, not to me personally.
> >
> >
> >
> > On 8/17/06, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>>
> > wrote:
> >
> >     Amadeo Bellotti wrote:
> >     > hello is there a way if a condition is not met to restart the
> whole
> >     > program? for example if and if statement returns true then re
> start
> >     > the whole program?
> >
> >     You can probably achieve what you want just by structuring the
> >     program
> >     correctly. My guess you need to use nested loops, something like
> this:
> >
> >     while True:
> >       initialize_everything()
> >       while True:
> >         if something_is_wrong():
> >           break
> >         do_some_work()
> >
> >     This will do_some_work() until something_is_wrong(), then it will
> >     initialize_everything() and try again.
> >
> >     If the test for something_is_wrong() is buried deep in the code
> >     you can
> >     break the loop by raising an exception which you catch in the
> >     top-level
> >     loop.
> >
> >     Kent
> >
> >     _______________________________________________
> >     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
> >     http://mail.python.org/mailman/listinfo/tutor
> >     <http://mail.python.org/mailman/listinfo/tutor>
> >
> >
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/8aadaf96/attachment-0001.html 

From broek at cc.umanitoba.ca  Thu Aug 17 19:37:27 2006
From: broek at cc.umanitoba.ca (Brian van den Broek)
Date: Thu, 17 Aug 2006 13:37:27 -0400
Subject: [Tutor] All of Kermit's E-Mails
In-Reply-To: <Pine.LNX.4.64.0608170859450.4371@hkn.eecs.berkeley.edu>
References: <44E40C99.3060901@gmail.com>	<44E48FE7.000001.03640@YOUR-4105E587B6>
	<Pine.LNX.4.64.0608170859450.4371@hkn.eecs.berkeley.edu>
Message-ID: <44E4A957.8000703@cc.umanitoba.ca>

Danny Yoo said unto the world upon 17/08/06 12:16 PM:
>> Suggest an alternative way of transmitting code.
> 
> Hi Kermit,

<snip>

> Just as a side note: you may want to investigate a good email client such 
> as Thunderbird if you have spare time.
> 
>      http://www.mozilla.com/thunderbird/
> 
> Much of the frustration I've been seeing on this thread deals with 
> IncrediMail's feature set; what it is providing you isn't so well suited 
> for the kind of technical communication that's on this list.

<snip>


Hi Kermit,

I'd like to second Danny's suggestion of Thunderbird. It is a very 
nice client by the same people that produce firefox.

I spent a few minutes trying to find out how to set IncrediMail to 
quote properly. Unfortunately, there is no downloadable documentation 
(at least not separate from the program itself). Searching 
<http://www.incredimail.com/english/help/searchfaq.asp> for `quote' 
gave no results :-(  So, IncrediMail doesn't quite seem so Incredi to 
me ;-)

For what its worth, the feature set that they promote it with (things 
such as ``Amazing animations'', ''beautiful email backgrounds'', and 
the ability to ''add funny animations to your emails'') are all likely 
to be *very* unwelcome on any python or other technical list.

If you really like IncrediMail for your personal email, you might 
think of installing Thunderbird, getting a gmail account and using the 
combination to post to technical lists, keeping IncrediMail for 
messages to friends, etc.[*] (If you need help with any of that, you 
can write me off-list.)

[*] My guess is that after a while, you'll find yourself switching to 
Tbird. :-)

Best wishes,

Brian vdB

From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 19:39:56 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 10:39:56 -0700 (PDT)
Subject: [Tutor] (no subject)
In-Reply-To: <d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
	<44E4A337.30701@tds.net>
	<d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
Message-ID: <Pine.LNX.4.64.0608171038100.28403@hkn.eecs.berkeley.edu>

> thank you Mr. Johnson this is my first program so its a little sloppy. I'm
> using gedit ill check out the other editors that u have thank you

More fundamentally, spend some time to learn about functions; they'll 
address much of the original concerns you had.  See any of the tutorials 
on:

     http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

and almost all of them should talk about what functions are, and how to 
use them.

Best of wishes!

From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 19:42:50 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 10:42:50 -0700 (PDT)
Subject: [Tutor] Making it easier to discuss programs  (fwd)
Message-ID: <Pine.LNX.4.64.0608171041190.28403@hkn.eecs.berkeley.edu>


Kermit accidently added a typo to the tutor at python.org address; I'll 
forward this message to the list for him.


---------- Forwarded message ----------
Date: Thu, 17 Aug 2006 13:38:10 -0400
From: Kermit Rose <kermit at polaris.net>
To: dyoo at hkn.eecs.berkeley.edu, "Luke Paireepinart; tutor"@python.org
Subject: Making it easier to discuss programs

From" Danny Yoo
/*Date:*/ 08/17/06 12:16:16
To: Kermit Rose
/*Cc:*/ Luke Paireepinart <mailto:rabidpoobear at gmail.com>; tutor at python.org 
<mailto:tutor at python.org>
/*Subject:*/ Re: [Tutor] All of Kermit's E-Mails




>  Hi Kermit,

> Try sending the code as a file attachment.  It's large enough that we want
> to make sure it goes through without being messed up, but small enough
>  that it can still be posted to the list.

> Alternatively, post the code on the web somewhere and send the list a link
> to the URL.  This is preferable for large blocks of code, and your
> factoring program is large enough that this would also be a good way to
> share the code with the mailing list.

I will consider making it a permanent part of my web page.

After I upload it, I can send you the specific URL for it.


> Just as a side note: you may want to investigate a good email client such
> as Thunderbird if you have spare time.

>     http://www.mozilla.com/thunderbird/

> Much of the frustration I've been seeing on this thread deals with
> IncrediMail's feature set; what it is providing you isn't so well suited
> for the kind of technical communication that's on this list.


I've download and installed Thunderbird.

I'm sending this message through Thunderbird.

I did notice one annoying feature of Thunderbird. 
When I used the up arrow , intending to go up a line, it went up a page.

I got around this by using the mouse cursor to move up a line.

Does everyone else, that uses Thunderbird,  have to move up a few lines by 
using the mouse cursor, or
is there another way,
for example by setting preferences?


>From Luke:

>> This is obviously a case for ... .dun-dun-dun!.... object-oriented
>> programming. When you have a collection of functions that all operate
>> together to create something, you make a Class to contain them.

> I'm going to have to interject and disagree with Luke here; for Kermit's
> application, classes are not necessary.  Kermit's still trying to learn
> basic structured programming with functions; I'm not convinced that
> leaning Kermit toward Object Oriented Programming is going to help matters
> much.


>Good luck to you!
>
Thank you.  I will consider everyone's suggestions.

Those that make sense to me I will try to implement.

Kermit   <  kermit at polaris.net  >

From kermit at polaris.net  Thu Aug 17 19:46:23 2006
From: kermit at polaris.net (Kermit Rose)
Date: Thu, 17 Aug 2006 13:46:23 -0400
Subject: [Tutor] Undeliverable Mail
In-Reply-To: <10608171338.AA09686@smtp.nettally.com>
References: <10608171338.AA09686@smtp.nettally.com>
Message-ID: <44E4AB6F.3070904@polaris.net>


> From" Danny Yoo
> /*Date:*/ 08/17/06 12:16:16
> To: Kermit Rose
> /*Cc:*/ Luke Paireepinart <mailto:rabidpoobear at gmail.com>; 
> tutor at python.org <mailto:tutor at python.org>
> /*Subject:*/ Re: [Tutor] All of Kermit's E-Mails
>
>
>
>  
>  >  Hi Kermit,
>  
>  > Try sending the code as a file attachment.  It's large enough that we 
> want
>  > to make sure it goes through without being messed up, but small enough
>  >  that it can still be posted to the list.
>  
>  > Alternatively, post the code on the web somewhere and send the list a 
> link
>  > to the URL.  This is preferable for large blocks of code, and your
>  > factoring program is large enough that this would also be a good way to
>  > share the code with the mailing list.
>
> I will consider making it a permanent part of my web page.
>
> After I upload it, I can send you the specific URL for it.
>
>  
>  > Just as a side note: you may want to investigate a good email client such
>  > as Thunderbird if you have spare time.
>  
>  >     http://www.mozilla.com/thunderbird/
>  
>  > Much of the frustration I've been seeing on this thread deals with
>  > IncrediMail's feature set; what it is providing you isn't so well suited
>  > for the kind of technical communication that's on this list.
>  
>
> I've download and installed Thunderbird.
>
> I'm sending this message through Thunderbird.
>
> I did notice one annoying feature of Thunderbird.  
>
> When I used the up arrow , intending to go up a line, it went up a page.
>
> I got around this by using the mouse cursor to move up a line.
>
> Does everyone else, that uses Thunderbird,  have to move up a few lines 
> by using the mouse cursor, or
>
> is there another way,
>
> for example by setting preferences?
>
>
>
>
>
> From Luke:
>
>
>
> >> This is obviously a case for ... .dun-dun-dun!.... object-oriented
>
> >> programming. When you have a collection of functions that all operate
>
> >> together to create something, you make a Class to contain them.
>
>
>
> > I'm going to have to interject and disagree with Luke here; for Kermit's
>
> > application, classes are not necessary.  Kermit's still trying to learn
>
> > basic structured programming with functions; I'm not convinced that
>
> > leaning Kermit toward Object Oriented Programming is going to help 
> matters
>
> > much.
>
>
>
>
>
> >Good luck to you!
>
> >
>
> Thank you.  I will consider everyone's suggestions.
>
>
>
> Those that make sense to me I will try to implement.
>
>
>
> Kermit   <  kermit at polaris.net  >
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>   


From amadeo.bellotti at gmail.com  Thu Aug 17 19:47:44 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Thu, 17 Aug 2006 13:47:44 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <Pine.LNX.4.64.0608171038100.28403@hkn.eecs.berkeley.edu>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
	<44E4A337.30701@tds.net>
	<d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
	<Pine.LNX.4.64.0608171038100.28403@hkn.eecs.berkeley.edu>
Message-ID: <d7253a230608171047t4454e2b0ic8c86d75b7a49238@mail.gmail.com>

Thank you again i no im a newbie and really inexperianced but thank you

On 8/17/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
> > thank you Mr. Johnson this is my first program so its a little sloppy.
> I'm
> > using gedit ill check out the other editors that u have thank you
>
> More fundamentally, spend some time to learn about functions; they'll
> address much of the original concerns you had.  See any of the tutorials
> on:
>
>      http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
>
> and almost all of them should talk about what functions are, and how to
> use them.
>
> Best of wishes!
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/ba9e76ea/attachment.htm 

From amadeo.bellotti at gmail.com  Thu Aug 17 19:51:24 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Thu, 17 Aug 2006 13:51:24 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <Pine.LNX.4.64.0608170836110.4371@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0608170733570.745@hkn.eecs.berkeley.edu>
	<Pine.LNX.4.64.0608170741090.745@hkn.eecs.berkeley.edu>
	<d7253a230608170759x49d2cfb4y1bb5faabb0290444@mail.gmail.com>
	<Pine.LNX.4.64.0608170836110.4371@hkn.eecs.berkeley.edu>
Message-ID: <d7253a230608171051l30770baeof835232d7a4dfe1a@mail.gmail.com>

thank you again but i think i found a way to fix it

On 8/17/06, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
>
> >> > Mr. Yoo im working on a program to write a sudoku puzzle and if
> >> > something is wrong with the last row i need to re make the whole
> puzzle
> >> > over again.
>
> >> Here's a separate question that's related to the first: can you write a
> >> function that asks the user to enter a word, and continues prompting
> until
> >> the user enters a non-empty word?
>
> Hi Amadeo,
>
>
> > Yes I can Mr. Yoo, but i dont really want to make my whole program a
> > loop.
>
> Ok.  Why not?  I'm curious: is there a particular constraint you're trying
> to work under, or is it something else?
>
> Also, I'm not sure what you mean by "whole program".
>
>
> In any case, here's a way to do it without an explicit 'for' or 'while'
> loop:
>
> ####################################
> def ask_for_input():
>      msg = raw_input("enter a word:")
>      if msg:
>          return msg
>      else:
>          return ask_for_input()
> ####################################
>
> This would not be the idiomatic way to do this in Python only because of a
> technical limitation in the main Python implementation (it doesn't support
> "tail call optimization").
>
> Still, would this be more acceptable to you, or do you also consider this
> a "loop"?
>
> (Personally, I do. *grin*)
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/ecd70e7d/attachment.html 

From broek at cc.umanitoba.ca  Thu Aug 17 20:05:06 2006
From: broek at cc.umanitoba.ca (Brian van den Broek)
Date: Thu, 17 Aug 2006 14:05:06 -0400
Subject: [Tutor] Which Book
In-Reply-To: <cd2d0ceb0608170914u2b1fdc6dt8ac9d045cb69fcef@mail.gmail.com>
References: <cd2d0ceb0608170914u2b1fdc6dt8ac9d045cb69fcef@mail.gmail.com>
Message-ID: <44E4AFD2.4030701@cc.umanitoba.ca>

Nagendra Singh said unto the world upon 17/08/06 12:14 PM:
> Hi All,
> 
> I have very little programming experience, I have decided to learn
> Python..there are tons of material and refernces on the web-pages, can
> you guys please suggest what is the best way to start or which ONE
> book which I should follow to start.
> 
> thanks..
> 
> Nagendra


``Beware the man of one book.''
     Saint Thomas Aquinas

Free ($ sense) books I read and liked:

http://www.ibiblio.org/obp/thinkCSpy/  (easy)

http://diveintopython.org/  (less easy)


Both of those can be bought in dead-tree form, as can 
<http://www.oreilly.com/catalog/lpython2/>


I'd start with the first and if you don't like it, try the next. 
Either way, multiple books compliment each other.

Best,

Brian vdB

From kermit at polaris.net  Thu Aug 17 20:20:51 2006
From: kermit at polaris.net (Kermit Rose)
Date: Thu, 17 Aug 2006 14:20:51 -0400
Subject: [Tutor] Actual code that illustrates problem
In-Reply-To: <Pine.LNX.4.64.0608170916190.4371@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.64.0608170024240.31579@hkn.eecs.berkeley.edu>
	<44E495A9.000003.03640@YOUR-4105E587B6>
	<Pine.LNX.4.64.0608170916190.4371@hkn.eecs.berkeley.edu>
Message-ID: <44E4B383.3040504@polaris.net>

Danny Yoo wrote:
>
>
> Hi Kermit,
>
> Ok, good.  You should add this as a comment to the function's header, 
> so that other people can see this.  Here is an example:
>
> def strongfac(z, w):
>     """z is the number to be factored.
>        w is a witness that may help find the factors of z.
>     """
>     ## rest of function body.

Ok.  I've added the suggested documentation for strongfac.

>
>> * What are the outputs? What is the return value of strongfac?
>>
>> The output is the return value of strongfac.
>> fac = [ x, y, difficulty of factoring z using w]
>> or
>> fac = [0,0,0] if strongfac could not factor z using w.
>
> Great!  Ok, I'm assuming that 'x' and 'y' are two arbitrary factors of 
> 'z'.  Are there other properties about x and y that you want to state, 
> such as: "x is always prime", or do we make no guarantees about this?
>
>
Yes.  That is correct.  There is not any expectation that x and y would 
be prime unless z just happens to be the product of exactly two primes.



>
> At this point, I'm distilling what you've said into a documentation 
> string:
>
> def strongfac(z, w):
>     """strongfac: number number -> [x, y, difficulty]
>
>     Factors z into two pieces, returning those two pieces as well as the
>     difficulty in factoring z.  w is a witness that may help find the
>     factors of z.
>
>     If no factors can be found, returns [0, 0, 0].
>     """
>     ## rest of function body.
>
>
> Does this make sense so far?  The point is to make it easy for humans 
> to understand your program.
>
>

Yes.  I've replaced the previously suggested documentation with the above.





>
>>> # face = [x,y,0]
>> [some code cut]
>>> # face[0] = x
>>> # face[1] = y
>>> # face[2] = 0
>>
>>> The three assignments to face[0] through face[2] don't do anything 
>>> effective and clutter the code.
>>
>> In fact, I knew that.  I inserted it in an attempt to overide the 
>> apparent bug that I saw.
>>
>> Sometimes it worked.
>
> This is a bad sign.  It should not have worked.  *grin*
>
> Next time you hit something mysterious like this, mention it to the 
> list. It'll be a good puzzle for the others here to take a look at.  
> Your code should be as rational as possible.  Don't just add code in 
> hoping that it'll fix some problem: try to understand why it's not 
> working first. Look for root causes.
>
>
I agree.  I reasoned as follows.

The root cause is that Python is not returning the correct value of a list.

So before I return the list, I will remind Python what's in the list.



>
> About strongfac():
>
>
>
> Can you try this?  Can you try breaking out the square=square test in 
> a similar way to how I treated the check_p_minus_1() code?
>
>
>

I have followed your suggestion and have done so.

>
> The high level goal here is to turn strongfac() into a very simple 
> looking function.  In pseudocode, it'll look something like:
>
> ############################
> def strongfac(z, w):
>     use check_p_minus_1 test and return if it succeeds
>     use square=square test and return if it succeeds
>     ...
> ############################
>
> This will make strongfac very regular to read.  It'll also make it 
> much easier to trace why one of your return values isn't returning 
> what you want.
> you want.

Ok.  I will work on splitting up the rest of strong fac into a set of 
functions.

I will attempt to maintain a compromise between having too many levels 
of function calls and
having any one function be too long.


Kermit  <  kermit at polaris.net  >





From kermit at polaris.net  Thu Aug 17 20:38:58 2006
From: kermit at polaris.net (Kermit Rose)
Date: Thu, 17 Aug 2006 14:38:58 -0400
Subject: [Tutor] All of Kermit's E-Mails
In-Reply-To: <44E4A957.8000703@cc.umanitoba.ca>
References: <44E40C99.3060901@gmail.com>	<44E48FE7.000001.03640@YOUR-4105E587B6>
	<Pine.LNX.4.64.0608170859450.4371@hkn.eecs.berkeley.edu>
	<44E4A957.8000703@cc.umanitoba.ca>
Message-ID: <44E4B7C2.9070905@polaris.net>

Brian van den Broek wrote:
>
>
> Hi Kermit,
>
> I'd like to second Danny's suggestion of Thunderbird. It is a very 
> nice client by the same people that produce firefox.
>
> I spent a few minutes trying to find out how to set IncrediMail to 
> quote properly. Unfortunately, there is no downloadable documentation 
> (at least not separate from the program itself). Searching 
> <http://www.incredimail.com/english/help/searchfaq.asp> for `quote' 
> gave no results :-(  So, IncrediMail doesn't quite seem so Incredi to 
> me ;-)

I agree.  In fact, I never did use any of the proudly proclaimed 
features of IncrediMail .  I used it only because when I accidently 
clobbered my previous email program
Pegasus,

IncrediMail  was the first replacement  email program I found on the 
internet.



>
> For what its worth, the feature set that they promote it with (things 
> such as ``Amazing animations'', ''beautiful email backgrounds'', and 
> the ability to ''add funny animations to your emails'') are all likely 
> to be *very* unwelcome on any python or other technical list.
>
Yes.   I simply ignored their special features as long as I could get it 
to send simple emails.  

When several of you on the tutor list showed me that IncrediMail caused 
frustration, I agreed to, and did, switch to Thunderbird. 

Before Danny's suggestion, I did not know of the existence of Thunderbird.


Now if I can only get Thunderbird to quit treating the up and down arrow 
as a page up or page down,
whenever it's at the top line or bottom line of what it thinks is a page.


Kermit   <  kermit at polaris.net   >



From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 20:58:36 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 11:58:36 -0700 (PDT)
Subject: [Tutor] Actual code that illustrates problem
In-Reply-To: <44E4B383.3040504@polaris.net>
References: <Pine.LNX.4.64.0608170024240.31579@hkn.eecs.berkeley.edu>
	<44E495A9.000003.03640@YOUR-4105E587B6>
	<Pine.LNX.4.64.0608170916190.4371@hkn.eecs.berkeley.edu>
	<44E4B383.3040504@polaris.net>
Message-ID: <Pine.LNX.4.64.0608171147480.10406@hkn.eecs.berkeley.edu>

>>>> # face = [x,y,0]
>>> [some code cut]
>>>> # face[0] = x
>>>> # face[1] = y
>>>> # face[2] = 0
>
> I agree.  I reasoned as follows.
>
> The root cause is that Python is not returning the correct value of a list.
>
> So before I return the list, I will remind Python what's in the list.

Hi Kermit,

Let's take those last three assignments out: they don't do anything as far 
as I can see.  If you do see a functional change in your program after 
doing so, I'll be very surprised and intrigued.  *grin*

The reason for taking them out is to, again, make the program as short 
and sweet as we can for humans to read.  A program's readability matters.


> Ok.  I will work on splitting up the rest of strong fac into a set of 
> functions.

That sounds good!  Definitely keep us up-to-date while you do it.  We can 
give suggestions if we see something that can be simplified, and we want 
to make sure you don't run into any big ruts as you do this.

Once your program is in smaller functional chunks, let's look again at 
your original problem.  I'm hoping that it'll be easier to chase the 
problem down then.


> I will attempt to maintain a compromise between having too many levels 
> of function calls and having any one function be too long.

I wouldn't worry about having heavy function call depth too much yet.  If 
it does turn out to be an issue, reversing the refactoring by inlining 
should be mechanically easy to do.


Good luck to you!

From josipl2000 at yahoo.com  Thu Aug 17 20:59:11 2006
From: josipl2000 at yahoo.com (josip)
Date: Thu, 17 Aug 2006 11:59:11 -0700 (PDT)
Subject: [Tutor] banners
Message-ID: <20060817185911.69182.qmail@web60811.mail.yahoo.com>

  Hi, I want to solve thi question, but I don't know how
  Can someone help?
   
  When dot matrix printers were at the height of hi- tech fashion, university students
  used to create banners with words on them using special characters (e.g. a banner
  with a student?s initials on it formed out of # characters). Write a Python program that
  spells out your name or nickname using special characters. Call your program
  banner.py.
  *              *     *
  *              *
  *              *
  ********    *
  *              *    *
  *              *    *
  *              *    *
   
   
   
  Thanks!

 		
---------------------------------
Get your email and more, right on the  new Yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/4bb1f086/attachment.htm 

From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 21:15:36 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 12:15:36 -0700 (PDT)
Subject: [Tutor] banners
In-Reply-To: <20060817185911.69182.qmail@web60811.mail.yahoo.com>
References: <20060817185911.69182.qmail@web60811.mail.yahoo.com>
Message-ID: <Pine.LNX.4.64.0608171207250.10406@hkn.eecs.berkeley.edu>



On Thu, 17 Aug 2006, josip wrote:

>  Hi, I want to solve thi question, but I don't know how

[homework question cut]

This is homework; our policy is not to give much help on this, as it's 
your work to do.  Do you have any specific questions?  Otherwise, all I 
can do here is point you toward introductory Python tutorial material at:

     http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

As far as I can tell, you should be able to solve this problem after 
reading the first section of any Python tutorial.

Try to do this homework problem on your own.  Frankly speaking, it is not 
a difficult problem; it's easy in the sense that you can do this if you 
honestly read through your course materials.

From Mike.Hansen at atmel.com  Thu Aug 17 21:58:33 2006
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 17 Aug 2006 13:58:33 -0600
Subject: [Tutor] Which Book
Message-ID: <57B026980605A64F9B23484C5659E32E255516@poccso.US.ad.atmel.com>

> 
> Hi All,
> 
> I have very little programming experience, I have decided to learn
> Python..there are tons of material and refernces on the web-pages, can
> you guys please suggest what is the best way to start or which ONE
> book which I should follow to start.
> 
> thanks..
> 
> Nagendra

http://pyfaq.infogami.com/tutor-what-are-some-good-books-on-python 

From alan.gauld at freenet.co.uk  Thu Aug 17 22:55:18 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 17 Aug 2006 21:55:18 +0100
Subject: [Tutor] Low level socket and threading code in python in
	HUGEwebsites -
References: <20060817094846.71075.qmail@web55902.mail.re3.yahoo.com>
Message-ID: <004101c6c23f$730fc7a0$0201a8c0@XPpro>

Anil,

I don't know if this is the kind of thuing they did on reddit, but a
few years ago I was working on a large network management
system (in C++ FWIW). It was monitoring a network of around
100,000 nodes.To ensure a timely flow of alarm traffic the server
had 4 network cards and the code used multi threading and
low level comms code to access those 4 IP addresses.

But the Sun Sparcstation I was using at the time onlky
had one network card and IP address, so the code couldn't
run without mmajor invasive debug statements, almosty
rendering the threading inactive. So in practice I had to
run my code on the server each time I worked on the
threaded code.

I don;t know if thats the kind of issue he means but it might be
an example of the kind of thing that a big web farm might
experience.

On another project I had similar issues where my workstation
didn't have enough RAM to compile (actually link)  the code
(in C++ again), so although I could edit the code on my local
machine I had to do the builds on the server (I only had
128M RAM, the server had 512M - and at the time
128M RAM cost over $400 - 8x16M modules!)

HTH,

Alan G.

----- Original Message ----- 
From: "anil maran" <anilmrn at yahoo.com>
To: <tutor at python.org>
Sent: Thursday, August 17, 2006 10:48 AM
Subject: [Tutor] Low level socket and threading code in python in 
HUGEwebsites -


> What kind of low-level socket and threading code is necessary for a 
> db
>  intensive site such as yahoo. How do we use it from python? does
>  anyone  have experience using it
>
>
> http://redditblog.blogspot.com/2005/12/on-lisp.html
> >From moving to python by the founders of reddit
>
>
> Because of the low-level socket and threading code we had to write,
> reddit would not run on my Mac, and I was always tethered to our
> FreeBSD development server. Not being able to program offline is a
> pain.
>
> I would imagine that they aren't just using a database.
> most of the "low level socket stuff" I've seen is about setting
> timeouts and doing Async IO.
>
>
>
> ---------------------------------
> Do you Yahoo!?
> Get on board. You're invited to try the new Yahoo! Mail Beta. 


From alan.gauld at freenet.co.uk  Thu Aug 17 22:58:24 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 17 Aug 2006 21:58:24 +0100
Subject: [Tutor] web application and database caching technique
References: <20060817095504.35141.qmail@web55911.mail.re3.yahoo.com>
Message-ID: <004d01c6c23f$e17f6ab0$0201a8c0@XPpro>

>i m trying to build a webapplication, i need to cache db records 
> as it has become very slow the sql queries and retrival
> can you guys helpe me out in designing cache structures/ hash 
> tables for these cases 

Which database? Most relational databases have caching as a 
feature that you can configure. It may be that you can simply 
increase the size of the database cache on the server?

A lot easier and usually a lot more efficient and reliable too.

Fixing database scaleability issues is rarely best done 
outside of the database! (Small volume query improvements 
are another matter entirely!)

Alan G.

From dyoo at hkn.eecs.berkeley.edu  Thu Aug 17 23:27:06 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 14:27:06 -0700 (PDT)
Subject: [Tutor] web application and database caching technique
In-Reply-To: <004d01c6c23f$e17f6ab0$0201a8c0@XPpro>
References: <20060817095504.35141.qmail@web55911.mail.re3.yahoo.com>
	<004d01c6c23f$e17f6ab0$0201a8c0@XPpro>
Message-ID: <Pine.LNX.4.64.0608171422300.891@hkn.eecs.berkeley.edu>



On Thu, 17 Aug 2006, Alan Gauld wrote:

>> i m trying to build a webapplication, i need to cache db records as it 
>> has become very slow the sql queries and retrival can you guys helpe me 
>> out in designing cache structures/ hash tables for these cases

I second Alan's suggestion: talk to your database administrator and make 
sure you're not doing something that he or she is responsible for. 
Offhand, it sounds like you're trying to reinvent database indices.

From alan.gauld at freenet.co.uk  Thu Aug 17 23:39:30 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 17 Aug 2006 22:39:30 +0100
Subject: [Tutor] Which Book
References: <cd2d0ceb0608170914u2b1fdc6dt8ac9d045cb69fcef@mail.gmail.com>
Message-ID: <009a01c6c245$9f4d40d0$0201a8c0@XPpro>

> I have very little programming experience, I have decided to learn
> Python..there are tons of material and references on the web-pages, 
> can
> you guys please suggest what is the best way to start or which ONE
> book which I should follow to start.

Despite the fact that my tutor is available in paper form I personally
don't recommend buying a beginners book - -they quickly become
redundant so they are poor value. I would advocate working through
the web tutorials (mine if you like:-) and then buy a goood reference
book (or two). Maybe a general treference like Python in a Nutshell
plus maybe a specialised one in the areas you are interested in
(Networks, Databases, Web, GUI, text processing etc)

But tastes in books is so subjective its hard to give recommendations.
I like generalist books like Programming Python, but many people
don't like that one at all. I didn't particularly like Text Processing 
in
Python, even though its the best book in its class - but I just didn't
like the style much. But I know others who think its a bit of a
masterpiece...

A lot will depend on your previoius experience too.
For example if you can already program in another language and
have a fair grasp of computer science terminology then my book
would be a complete waste of time, but if you only have ac minimal
experience and don;t know the CS terms my book would be a good
choice (he says immodestly!)

Best thing if possible is to borrow a copy (from a friend or library)
or if there is a web version read a bit there first.

HTH,

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


From alan.gauld at freenet.co.uk  Thu Aug 17 23:50:34 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 17 Aug 2006 22:50:34 +0100
Subject: [Tutor] (no subject)
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com><44E44B0D.7050309@tds.net><d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com><44E4A337.30701@tds.net>
	<d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
Message-ID: <00ac01c6c247$2b350780$0201a8c0@XPpro>

> thank you Mr. Johnson this is my first program so its a little 
> sloppy. I'm
> using gedit ill check out the other editors that u have thank you

If you have Python you will have either IDLE or Pythonwin (or both)
Both of these will allow block indent/unindent so simply load the
code into IDLE to do the indentation.. You can go back to gedit
afterwards if you like.

But as Kent said you should ideally aimto write the code as
functions, each about 5-50 lines long (less than 5 and the advantage
is minimal, mor than 50 is just too long - around 12 lines per 
functoion
is a good average IMHO

But don't use number of lines as the deciding factor! Divide the code
into blocks of code that do something logical that you can describe
in a few words (see the comments from Danny to Kermit for examples!)
Use those few words to name the function. Consider how to pass key
data between the funbctions using parameters and return values.

If you don't know how to write functions take a look at the Functions
topic of my tutor.

HTH,

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


From alan.gauld at freenet.co.uk  Thu Aug 17 23:55:56 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 17 Aug 2006 22:55:56 +0100
Subject: [Tutor] All of Kermit's E-Mails
References: <44E40C99.3060901@gmail.com>	<44E48FE7.000001.03640@YOUR-4105E587B6><Pine.LNX.4.64.0608170859450.4371@hkn.eecs.berkeley.edu>
	<44E4A957.8000703@cc.umanitoba.ca>
Message-ID: <00bc01c6c247$eb439820$0201a8c0@XPpro>

> gave no results :-(  So, IncrediMail doesn't quite seem so Incredi 
> to me ;-)

I'll second that!

I have an elderly friend who loves the net and is on lots of non 
techie mailing lists.
She was waxing lyrical about incredimail to me and was amazed that I 
didn't use
it, it was so good.

So I downloaded it and used it for 1 day before giving up in disgust
- I couldn't find a single feature that lifted it above even the
most basic Outlook Express functions! It's big on frippery and zero
on useful functions. (For my purposes at least - my friend still 
thinks
its the best thing out there! - and sends me every message with
an HTML attached version for free... :-()

Alan G. 


From alan.gauld at freenet.co.uk  Fri Aug 18 00:45:01 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 17 Aug 2006 23:45:01 +0100
Subject: [Tutor] Actual code that illustrates problem
References: <44E3E590.000005.00920@YOUR-4105E587B6>
Message-ID: <00ea01c6c24e$c7188b70$0201a8c0@XPpro>

While others have made good suggestions to clarify the code I thought
I'd try to tackle the question of whether we had a bug in Python.

Unfortunately the debug output does not come from the code that's
posted so its difficult to figure out what's been happening.

For example, one apparently good and one "faulty" test:

>  In strongfac
>  Found1: x =  53799857
>  Found1: y =  1858741
>  face =  [53799857L, 1858741L, 0]
>  Found1: factor by strong probable prime test, using witnes 
> 15306543515214

Note the mis-spelling of witnes(sic) - it does not appear in the code!

>  Found1: factors are  53799857 1858741
>  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
>  Retrieved from strongfac, face =  [0, 0, 0]
>  In fermat: k =  13  x =  0  y =  0  face =  [0, 0, 0]

Similarly the first line has the text "factors are 53..."

But in the code all instances of "factors are" are followed by the 
word "by"

So I conclude the tests are not from this code. The fault may be in 
this code
but I can't be sure...

However a couple of observations might help:

> #    def strongfac(z,w):
> #        x = gcd(z,w-1)
> #        if x > 1:
> #            if x < z:

You can simpliffy this 2 stage test using either boolean operartors:

if x > 1 and x < z:

OR, almost uniquie to pyhon:

if 1 < x < z:

That removes one whole layer of indentation.
This trick can be applied in many places in the algorithm.


Also


> #                y = z/x
> #                print "Found factors by P-1 Method as part of 
> Strong
> probable prime test, using witness",w,"."
> #                print " x = ",x," y = ",y
> #                return [x,y,0]
> #        w2 = (w * w)%z
> #        s = ksqrt(w2)
> #        if w2 == s * s:
> #            if s != w:
> #                x = gcd(z,kabs(w2 - s))
> #                if x > 1:
> #                    if x < z:
> #                        print "Found factors by square = square as 
> part of
> Strong probable prime test, using witness",w,"."
> #                        return [x,y,0]

If x was not between 1 and z in the first test y is not defined at 
this point.

> #        trace = 0
> #        t = z - 1
> #        a = 0
> #        while t%2 == 0:
> #            t = t/2
> #            a = a + 1
> #        test = pow(w,t,z)
> #        if test ==1:
> #            x = gcd(z,w-1)
> #            if x > 1:
> #                if x < z:
> #                    y = z/x
> #                    print " Found factor by Strong probable prime 
> test,
>using withness ",w,"."
> #                    return [x,y,0]
> #        else:
> #            x = gcd(test-1,z)
> #            if x > 1:
> #                print " "
> #                print " In strongfac "
> #                print " Found1: x = ",x

You could do all of this with a single print:

print "\n In strongfac \nFound1: x = ", x

I won't go any further because its pointless given the discrepency 
between
the data and the code, but hopefully those pointers will be helpful in 
your
efforts to tidy the code into separate functions.

Alan G. 


From alan.gauld at freenet.co.uk  Fri Aug 18 00:52:16 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 17 Aug 2006 23:52:16 +0100
Subject: [Tutor] banners
References: <20060817185911.69182.qmail@web60811.mail.yahoo.com>
	<Pine.LNX.4.64.0608171207250.10406@hkn.eecs.berkeley.edu>
Message-ID: <011601c6c250$35735180$0201a8c0@XPpro>

> As far as I can tell, you should be able to solve this problem after 
> reading the first section of any Python tutorial.

I'm not so sure Danny, figuring out how to draw the letters in the
banner is not obvious after having read a hello-world program
example. There are some tricky-ish aspects to this one.

To the OP, Danny is right that we don't give answers to homeworks
but if you give it a try and get stuck come back to us with the
code you have written and we might ask you some questions
to make you think about the solution...

Alan G. 


From dyoo at hkn.eecs.berkeley.edu  Fri Aug 18 01:28:00 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 17 Aug 2006 16:28:00 -0700 (PDT)
Subject: [Tutor] banners
In-Reply-To: <011601c6c250$35735180$0201a8c0@XPpro>
References: <20060817185911.69182.qmail@web60811.mail.yahoo.com>
	<Pine.LNX.4.64.0608171207250.10406@hkn.eecs.berkeley.edu>
	<011601c6c250$35735180$0201a8c0@XPpro>
Message-ID: <Pine.LNX.4.64.0608171621240.23790@hkn.eecs.berkeley.edu>

> I'm not so sure Danny, figuring out how to draw the letters in the 
> banner is not obvious after having read a hello-world program example. 
> There are some tricky-ish aspects to this one.

Hi Alan,

It's simpler than that: the homework states that the message is hardcoded 
to show either josip's name or nickname.  If the homework had asked to 
more generally print a banner of a arbitrary message, that would be 
harder, but his homework assignment is much easier because of the 
hardcoded nature of it.


If I were to write this, my banner.py would be required to display:

*****   *   *
*   *   *   *
*  *      *
**        *

on the screen.


So the parameterization is based on the person who is writing it.  It's 
very much a program in the same difficulty level as "Hello World", which 
is why I'm trying very hard not to say more about it.

From kermit at polaris.net  Fri Aug 18 02:09:37 2006
From: kermit at polaris.net (Kermit Rose)
Date: Thu, 17 Aug 2006 20:09:37 -0400
Subject: [Tutor] Actual code that illustrates problem
In-Reply-To: <00ea01c6c24e$c7188b70$0201a8c0@XPpro>
References: <44E3E590.000005.00920@YOUR-4105E587B6>
	<00ea01c6c24e$c7188b70$0201a8c0@XPpro>
Message-ID: <44E50541.9070609@polaris.net>

Alan Gauld wrote:
>
> While others have made good suggestions to clarify the code I thought
> I'd try to tackle the question of whether we had a bug in Python.
>
> Unfortunately the debug output does not come from the code that's
> posted so its difficult to figure out what's been happening.
>
> For example, one apparently good and one "faulty" test:
>
>>  In strongfac
>>  Found1: x =  53799857
>>  Found1: y =  1858741
>>  face =  [53799857L, 1858741L, 0]
>>  Found1: factor by strong probable prime test, using witnes 
>> 15306543515214
>
> Note the mis-spelling of witnes(sic) - it does not appear in the code!
>
Hmm....    Perhaps I caught that spelling error between the time I sent 
the attached program file and the time I reran the program to demostrate 
the error.


>>  Found1: factors are  53799857 1858741
>>  Found1: returning  [53799857L, 1858741L, 0]  to fermat routine.
>>  Retrieved from strongfac, face =  [0, 0, 0]
>>  In fermat: k =  13  x =  0  y =  0  face =  [0, 0, 0]
>
> Similarly the first line has the text "factors are 53..."
>
> But in the code all instances of "factors are" are followed by the 
> word "by"
>
> So I conclude the tests are not from this code. The fault may be in 
> this code
> but I can't be sure...
>
After I've followed the many good suggestions for making my program more 
concise and readable,
I'll re-run it and see if I get the same difficulty at the same z's to 
factor.

I will upload the source to my web page and create a path to it in my 
index.html file.


> However a couple of observations might help:
>
>> #    def strongfac(z,w):
>> #        x = gcd(z,w-1)
>> #        if x > 1:
>> #            if x < z:
>
> You can simpliffy this 2 stage test using either boolean operartors:
>
> if x > 1 and x < z:
>
> OR, almost uniquie to pyhon:
>
> if 1 < x < z:
>

Hmmmmmm.

A good syntax to remember.


> That removes one whole layer of indentation.
> This trick can be applied in many places in the algorithm.
>
>
> Also
>
>
>> #                y = z/x
>> #                print "Found factors by P-1 Method as part of Strong
>> probable prime test, using witness",w,"."
>> #                print " x = ",x," y = ",y
>> #                return [x,y,0]
>> #        w2 = (w * w)%z
>> #        s = ksqrt(w2)
>> #        if w2 == s * s:
>> #            if s != w:
>> #                x = gcd(z,kabs(w2 - s))
>> #                if x > 1:
>> #                    if x < z:
>> #                        print "Found factors by square = square as 
>> part of
>> Strong probable prime test, using witness",w,"."
>> #                        return [x,y,0]
>
> If x was not between 1 and z in the first test y is not defined at 
> this point.
>
Yep.  I should have calculated y = z/x before printing.

The syntax checker would have found this as soon as I encountered a z 
that took me to that point.

I'll fix it before re-submitting.


>> #        trace = 0
>> #        t = z - 1
>> #        a = 0
>> #        while t%2 == 0:
>> #            t = t/2
>> #            a = a + 1
>> #        test = pow(w,t,z)
>> #        if test ==1:
>> #            x = gcd(z,w-1)
>> #            if x > 1:
>> #                if x < z:
>> #                    y = z/x
>> #                    print " Found factor by Strong probable prime test,
>> using withness ",w,"."
>> #                    return [x,y,0]
>> #        else:
>> #            x = gcd(test-1,z)
>> #            if x > 1:
>> #                print " "
>> #                print " In strongfac "
>> #                print " Found1: x = ",x
>
> You could do all of this with a single print:
>
> print "\n In strongfac \nFound1: x = ", x
>
uuuuuuuuuh..     Too compact for me.

I need to see the logic more spread out.



> I won't go any further because its pointless given the discrepency 
> between
> the data and the code, but hopefully those pointers will be helpful in 
> your
> efforts to tidy the code into separate functions.
>
> Alan G.

Also a warning to me to not edit the final output to compensate for 
faulty programming.

Thank you.

Kermit  <   kermit at polaris.net   >



From amonroe at columbus.rr.com  Fri Aug 18 02:22:04 2006
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu, 17 Aug 2006 20:22:04 -0400
Subject: [Tutor] All of Kermit's E-Mails
In-Reply-To: <44E48FE7.000001.03640@YOUR-4105E587B6>
References: <44E40C99.3060901@gmail.com>
	<44E48FE7.000001.03640@YOUR-4105E587B6>
Message-ID: <901544463741.20060817202204@columbus.rr.com>

 
> my email program does not insert the > sign like the standard email
> program does.

"The Bat" mail client does a great job of it, but it's not free.
http://www.ritlabs.com/

You might try Pegasus Mail, although I don't remember how well it does
it. http://www.pmail.com/

If you were desperate and crazy, you could also try typing the
messages in XNews's editor and copy/paste them to your mail.
http://xnews.newsguy.com/


Alan


From amadeo.bellotti at gmail.com  Fri Aug 18 04:22:58 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Thu, 17 Aug 2006 22:22:58 -0400
Subject: [Tutor] Which Book
In-Reply-To: <009a01c6c245$9f4d40d0$0201a8c0@XPpro>
References: <cd2d0ceb0608170914u2b1fdc6dt8ac9d045cb69fcef@mail.gmail.com>
	<009a01c6c245$9f4d40d0$0201a8c0@XPpro>
Message-ID: <d7253a230608171922g5116bc04m90f44278ff118173@mail.gmail.com>

A good book is Practical Python by Magnus Lie Hetland.

On 8/17/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
> > I have very little programming experience, I have decided to learn
> > Python..there are tons of material and references on the web-pages,
> > can
> > you guys please suggest what is the best way to start or which ONE
> > book which I should follow to start.
>
> Despite the fact that my tutor is available in paper form I personally
> don't recommend buying a beginners book - -they quickly become
> redundant so they are poor value. I would advocate working through
> the web tutorials (mine if you like:-) and then buy a goood reference
> book (or two). Maybe a general treference like Python in a Nutshell
> plus maybe a specialised one in the areas you are interested in
> (Networks, Databases, Web, GUI, text processing etc)
>
> But tastes in books is so subjective its hard to give recommendations.
> I like generalist books like Programming Python, but many people
> don't like that one at all. I didn't particularly like Text Processing
> in
> Python, even though its the best book in its class - but I just didn't
> like the style much. But I know others who think its a bit of a
> masterpiece...
>
> A lot will depend on your previoius experience too.
> For example if you can already program in another language and
> have a fair grasp of computer science terminology then my book
> would be a complete waste of time, but if you only have ac minimal
> experience and don;t know the CS terms my book would be a good
> choice (he says immodestly!)
>
> Best thing if possible is to borrow a copy (from a friend or library)
> or if there is a web version read a bit there first.
>
> HTH,
>
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060817/27bb538b/attachment.htm 

From broek at cc.umanitoba.ca  Fri Aug 18 04:38:49 2006
From: broek at cc.umanitoba.ca (Brian van den Broek)
Date: Thu, 17 Aug 2006 22:38:49 -0400
Subject: [Tutor] All of Kermit's E-Mails
In-Reply-To: <44E4B7C2.9070905@polaris.net>
References: <44E40C99.3060901@gmail.com>	<44E48FE7.000001.03640@YOUR-4105E587B6>
	<Pine.LNX.4.64.0608170859450.4371@hkn.eecs.berkeley.edu>
	<44E4A957.8000703@cc.umanitoba.ca> <44E4B7C2.9070905@polaris.net>
Message-ID: <44E52839.1010500@cc.umanitoba.ca>

Kermit Rose said unto the world upon 17/08/06 02:38 PM:

> Now if I can only get Thunderbird to quit treating the up and down arrow 
> as a page up or page down,
> whenever it's at the top line or bottom line of what it thinks is a page.


Hi Kermit,

I'm glad you've given Thunderbird a try and that you seem to have 
taken all of the advice in the right spirit.

I'm not sure what you mean by a `page' in the context of email. Could 
you describe the exhibited and expected behaviour in a bit more detail?

For now, have you tried clicking in the message body and then using 
the arrows? (That's all I've got.)

You might also what to try the mozilla support forums and knowledge base.

Best,

Brian




From amadeo.bellotti at gmail.com  Fri Aug 18 06:06:51 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Fri, 18 Aug 2006 00:06:51 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <00ac01c6c247$2b350780$0201a8c0@XPpro>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
	<44E4A337.30701@tds.net>
	<d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
	<00ac01c6c247$2b350780$0201a8c0@XPpro>
Message-ID: <d7253a230608172106j561257bcyac65802ba17a4a9b@mail.gmail.com>

thank you but IDLE doesnt seem to work on Suse 9.2 do you know a way to fix
it?

On 8/17/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
> > thank you Mr. Johnson this is my first program so its a little
> > sloppy. I'm
> > using gedit ill check out the other editors that u have thank you
>
> If you have Python you will have either IDLE or Pythonwin (or both)
> Both of these will allow block indent/unindent so simply load the
> code into IDLE to do the indentation.. You can go back to gedit
> afterwards if you like.
>
> But as Kent said you should ideally aimto write the code as
> functions, each about 5-50 lines long (less than 5 and the advantage
> is minimal, mor than 50 is just too long - around 12 lines per
> functoion
> is a good average IMHO
>
> But don't use number of lines as the deciding factor! Divide the code
> into blocks of code that do something logical that you can describe
> in a few words (see the comments from Danny to Kermit for examples!)
> Use those few words to name the function. Consider how to pass key
> data between the funbctions using parameters and return values.
>
> If you don't know how to write functions take a look at the Functions
> topic of my tutor.
>
> HTH,
>
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060818/43219c5d/attachment.htm 

From bds at waywood.co.uk  Fri Aug 18 06:08:25 2006
From: bds at waywood.co.uk (Barnaby Scott)
Date: Fri, 18 Aug 2006 05:08:25 +0100
Subject: [Tutor] Communicating with Win2000 runas.exe
In-Reply-To: <CCAC78D42E32184F8E26DC163DB98306C1B397@vogbs009.gb.vo.local>
References: <CCAC78D42E32184F8E26DC163DB98306C1B397@vogbs009.gb.vo.local>
Message-ID: <44E53D39.3020100@waywood.co.uk>

Tim Golden wrote:
> [Barnaby Scott]
> 
> | So I'm thinking along these lines:
> | 
> | import subprocess
> | sp = subprocess.Popen(r'C:\WINNT\SYSTEM32\runas.exe 
> | /user:administrator
> | C:\Program Files\Microsoft Games\Age of Mythology\aom.exe')
> | #some sort of code to send the password here...
> | #help!
> 
> I *think* -- and I'm happy to be wrong -- that there's
> no way you're going to get that password in there. One
> place to start looking might be:
> 
> pywinauto - http://pywinauto.pbwiki.com/
> 
> which lets you automate Windows in general; don't know
> how much use it'll be here. 
> 
> Alternatively, look into the pywin32 package, and in 
> particular at the win32security functions which let you 
> impersonate another user. They're not trivial to use, 
> but their use has been explained a few times over the 
> years I think. Mostly by Roger Upole who wrote most if 
> not all of the Python bindings.
> 
> Here's a post which looks useful; you'll have to hunt
> around for others:
> 
> http://groups.google.com/group/comp.lang.python/msg/6bbefb9d4d45d253
> 
> I suggest you ask this question again on the main
> python / python-win32 lists; it's a bit too platform-specific
> for the tutor list, I would say.
> 
> TJG

Thanks for your tips. In fact the first link you gave put me onto 
Sendkeys (http://www.rutherfurd.net/python/sendkeys/), which is a 
prerequisite for pywinauto. In the end that was all I needed. In case 
anyone else is interested here is my code now (with SendKeys installed):


import subprocess, SendKeys

subprocess.Popen(r'C:\WINNT\system32\runas.exe /user:administrator 
"C:\Program Files\Microsoft Games\Age of Mythology\aom.exe"')

SendKeys.SendKeys('{PAUSE 1}MyAdministratorPassword{ENTER}')


Worth knowing about - might be quite useful for all sorts of things, 
however 'quick and dirty' it feels as a technique!

Thanks again

BDS

From john at fouhy.net  Fri Aug 18 06:15:49 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 18 Aug 2006 16:15:49 +1200
Subject: [Tutor] (no subject)
In-Reply-To: <d7253a230608172106j561257bcyac65802ba17a4a9b@mail.gmail.com>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
	<44E4A337.30701@tds.net>
	<d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
	<00ac01c6c247$2b350780$0201a8c0@XPpro>
	<d7253a230608172106j561257bcyac65802ba17a4a9b@mail.gmail.com>
Message-ID: <5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com>

On 18/08/06, Amadeo Bellotti <amadeo.bellotti at gmail.com> wrote:
> thank you but IDLE doesnt seem to work on Suse 9.2 do you know a way to fix
> it?

Why not -- what goes wrong?  Is there an error message?

-- 
John.

From dkuhlman at rexx.com  Fri Aug 18 06:30:55 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Thu, 17 Aug 2006 21:30:55 -0700
Subject: [Tutor] (no subject)
In-Reply-To: <d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
	<44E4A337.30701@tds.net>
	<d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
Message-ID: <20060818043055.GA13819@cutter.rexx.com>

On Thu, Aug 17, 2006 at 01:28:56PM -0400, Amadeo Bellotti wrote:
> thank you Mr. Johnson this is my first program so its a little sloppy. I'm
> using gedit ill check out the other editors that u have thank you
> 

I'd also encourage you to look at other editors, as others on this
list have.

However, if you like and want to stay with gedit, try to do the
following (if you have not already) -- Click on menu item
Edit/Preferences, then click on the Plugins tab and enable 
"Indent lines" plugin.  After doing so, there should be Indent and
Unindent items in the Edit menu.  Highlight a block of code, and
try those operations.

Indent and Unindent operations will enable you to easily convert top
level code into a function: specifically, Indent block and add a
"def" statement at the top.

I apologize if the above is overly simple-minded and if you are
already past this.

Dave



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

From amadeo.bellotti at gmail.com  Fri Aug 18 06:50:11 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Fri, 18 Aug 2006 00:50:11 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
	<44E4A337.30701@tds.net>
	<d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
	<00ac01c6c247$2b350780$0201a8c0@XPpro>
	<d7253a230608172106j561257bcyac65802ba17a4a9b@mail.gmail.com>
	<5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com>
Message-ID: <d7253a230608172150i5ddcf565y75ce4634e7d7b2b2@mail.gmail.com>

Mr. Kuhlman it says python is not configured for tk.

but on another note does anyone know how to make a 2d array?

On 8/18/06, John Fouhy <john at fouhy.net> wrote:
>
> On 18/08/06, Amadeo Bellotti <amadeo.bellotti at gmail.com> wrote:
> > thank you but IDLE doesnt seem to work on Suse 9.2 do you know a way to
> fix
> > it?
>
> Why not -- what goes wrong?  Is there an error message?
>
> --
> John.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060818/30fc2a37/attachment.html 

From john at fouhy.net  Fri Aug 18 07:00:36 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 18 Aug 2006 17:00:36 +1200
Subject: [Tutor] (no subject)
In-Reply-To: <d7253a230608172150i5ddcf565y75ce4634e7d7b2b2@mail.gmail.com>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
	<44E4A337.30701@tds.net>
	<d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
	<00ac01c6c247$2b350780$0201a8c0@XPpro>
	<d7253a230608172106j561257bcyac65802ba17a4a9b@mail.gmail.com>
	<5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com>
	<d7253a230608172150i5ddcf565y75ce4634e7d7b2b2@mail.gmail.com>
Message-ID: <5e58f2e40608172200s9a00c59x1ae39c411f86495c@mail.gmail.com>

On 18/08/06, Amadeo Bellotti <amadeo.bellotti at gmail.com> wrote:
> Mr. Kuhlman it says python is not configured for tk.
>
> but on another note does anyone know how to make a 2d array?

Are you in charge of your machine, or does someone else administer it?

I don't know SUSE very well, but I expect that you can fix this by
installing a package called something like "python-tkinter".

-- 
John.

From tim.golden at viacom-outdoor.co.uk  Fri Aug 18 09:34:46 2006
From: tim.golden at viacom-outdoor.co.uk (Tim Golden)
Date: Fri, 18 Aug 2006 08:34:46 +0100
Subject: [Tutor] Communicating with Win2000 runas.exe
Message-ID: <CCAC78D42E32184F8E26DC163DB98306C1B39F@vogbs009.gb.vo.local>

[Tim Golden]
| > [Barnaby Scott]
| > 
| > | So I'm thinking along these lines:
| > | 
| > | import subprocess
| > | sp = subprocess.Popen(r'C:\WINNT\SYSTEM32\runas.exe 
| > | /user:administrator
| > | C:\Program Files\Microsoft Games\Age of Mythology\aom.exe')
| > | #some sort of code to send the password here...
| > | #help!
| > 
| > I *think* -- and I'm happy to be wrong -- that there's
| > no way you're going to get that password in there. One
| > place to start looking might be:
| > 
| > pywinauto - http://pywinauto.pbwiki.com/
| > 
| > which lets you automate Windows in general; don't know
| > how much use it'll be here. 

[Barnaby Scott]
| Thanks for your tips. In fact the first link you gave put me onto 
| Sendkeys (http://www.rutherfurd.net/python/sendkeys/), which is a 
| prerequisite for pywinauto. In the end that was all I needed. In case 
| anyone else is interested here is my code now (with SendKeys 
| installed):

Excellent! I'm glad it turned out to be so easy, and thanks for
posting the code and the link.

TJG

________________________________________________________________________
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________

From alan.gauld at freenet.co.uk  Fri Aug 18 09:43:34 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 18 Aug 2006 08:43:34 +0100
Subject: [Tutor] banners
References: <20060817185911.69182.qmail@web60811.mail.yahoo.com>
	<Pine.LNX.4.64.0608171207250.10406@hkn.eecs.berkeley.edu>
	<011601c6c250$35735180$0201a8c0@XPpro>
	<Pine.LNX.4.64.0608171621240.23790@hkn.eecs.berkeley.edu>
Message-ID: <000501c6c29a$0d52f350$0201a8c0@XPpro>

> It's simpler than that: the homework states that the message is 
> hardcoded to show either josip's name or nickname.

Ah, OK, I hadn't noticed that.
In that case yes it can be as simple as hello world.

Alan G. 


From alan.gauld at freenet.co.uk  Fri Aug 18 09:47:54 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 18 Aug 2006 08:47:54 +0100
Subject: [Tutor] Actual code that illustrates problem
References: <44E3E590.000005.00920@YOUR-4105E587B6>
	<00ea01c6c24e$c7188b70$0201a8c0@XPpro>
	<44E50541.9070609@polaris.net>
Message-ID: <000701c6c29a$9da92d20$0201a8c0@XPpro>

>>> #                print " "
>>> #                print " In strongfac "
>>> #                print " Found1: x = ",x
>>
>> You could do all of this with a single print:
>>
>> print "\n In strongfac \nFound1: x = ", x
>>
> uuuuuuuuuh..     Too compact for me.
> I need to see the logic more spread out.

\n is the newline character.
An alternative is to use triple quotes:

print '''
In strongfac
Found1: x = ''',x

But that still clutters up the code listing with extra lines that 
have nothing to do with the algorithm - the main advantage in  
reducing to one print statement..

Alan G.

From alan.gauld at freenet.co.uk  Fri Aug 18 09:50:09 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 18 Aug 2006 08:50:09 +0100
Subject: [Tutor] (no subject)
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
	<44E4A337.30701@tds.net>
	<d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
	<00ac01c6c247$2b350780$0201a8c0@XPpro>
	<d7253a230608172106j561257bcyac65802ba17a4a9b@mail.gmail.com>
Message-ID: <002b01c6c29a$fa21a960$0201a8c0@XPpro>


> thank you but IDLE doesnt seem to work on Suse 9.2 do you know a way 
> to fix
> it?

I've only used IDLE on Linux a few times but it certainly works
on RedHat, Mandriva and Slackware. And it used to work on
Suse 5 - the only time I ever used Suse...

What hapens when you try to run IDLE? It may just be a case of
fixing a path setting or somesuch.

Alan G.



From alan.gauld at freenet.co.uk  Fri Aug 18 09:53:51 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 18 Aug 2006 08:53:51 +0100
Subject: [Tutor] All of Kermit's E-Mails
References: <44E40C99.3060901@gmail.com><44E48FE7.000001.03640@YOUR-4105E587B6>
	<901544463741.20060817202204@columbus.rr.com>
Message-ID: <003301c6c29b$7264b5c0$0201a8c0@XPpro>

> "The Bat" mail client does a great job of it, but it's not free.
> http://www.ritlabs.com/
>
> You might try Pegasus Mail, although I don't remember how well it 
> does
> it. http://www.pmail.com/

Since you seem to be on a PC plain old Outlook Express will do
a better job that Incredimail and its installed by default!

It will also allow you to read the gmans news archive of the tutor 
list
which I confess to finding so useful I may be unsubscribing from
the digest service and use that instead... Even if you set up a
separate free email account for your python emails...

Alan G. 


From anilmrn at yahoo.com  Fri Aug 18 10:24:21 2006
From: anilmrn at yahoo.com (anil maran)
Date: Fri, 18 Aug 2006 01:24:21 -0700 (PDT)
Subject: [Tutor] (no subject)
In-Reply-To: <44E44B0D.7050309@tds.net>
Message-ID: <20060818082421.48084.qmail@web55912.mail.re3.yahoo.com>

it is amazing the amount of knowledge that is being
disseminated on this group, guido should love it that
u guys are doing such a good job, keep it up guys
anil

--- Kent Johnson <kent37 at tds.net> wrote:

> Amadeo Bellotti wrote:
> > hello is there a way if a condition is not met to
> restart the whole 
> > program? for example if and if statement returns
> true then re start 
> > the whole program?
> 
> You can probably achieve what you want just by
> structuring the program 
> correctly. My guess you need to use nested loops,
> something like this:
> 
> while True:
>   initialize_everything()
>   while True:
>     if something_is_wrong():
>       break
>     do_some_work()
> 
> This will do_some_work() until something_is_wrong(),
> then it will 
> initialize_everything() and try again.
> 
> If the test for something_is_wrong() is buried deep
> in the code you can 
> break the loop by raising an exception which you
> catch in the top-level 
> loop.
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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

From anilmrn at yahoo.com  Fri Aug 18 10:27:53 2006
From: anilmrn at yahoo.com (anil maran)
Date: Fri, 18 Aug 2006 01:27:53 -0700 (PDT)
Subject: [Tutor] Low level socket and threading code in python in
	HUGEwebsites -
In-Reply-To: <004101c6c23f$730fc7a0$0201a8c0@XPpro>
Message-ID: <20060818082753.75918.qmail@web55907.mail.re3.yahoo.com>

thanks alan it is very enlightening
can one of you guys who have experience building sites
such as yahoo mail and stuff, explain what parts of a
webserver needs to be multithreaded
thanks

--- Alan Gauld <alan.gauld at freenet.co.uk> wrote:

> Anil,
> 
> I don't know if this is the kind of thuing they did
> on reddit, but a
> few years ago I was working on a large network
> management
> system (in C++ FWIW). It was monitoring a network of
> around
> 100,000 nodes.To ensure a timely flow of alarm
> traffic the server
> had 4 network cards and the code used multi
> threading and
> low level comms code to access those 4 IP addresses.
> 
> But the Sun Sparcstation I was using at the time
> onlky
> had one network card and IP address, so the code
> couldn't
> run without mmajor invasive debug statements,
> almosty
> rendering the threading inactive. So in practice I
> had to
> run my code on the server each time I worked on the
> threaded code.
> 
> I don;t know if thats the kind of issue he means but
> it might be
> an example of the kind of thing that a big web farm
> might
> experience.
> 
> On another project I had similar issues where my
> workstation
> didn't have enough RAM to compile (actually link) 
> the code
> (in C++ again), so although I could edit the code on
> my local
> machine I had to do the builds on the server (I only
> had
> 128M RAM, the server had 512M - and at the time
> 128M RAM cost over $400 - 8x16M modules!)
> 
> HTH,
> 
> Alan G.
> 
> ----- Original Message ----- 
> From: "anil maran" <anilmrn at yahoo.com>
> To: <tutor at python.org>
> Sent: Thursday, August 17, 2006 10:48 AM
> Subject: [Tutor] Low level socket and threading code
> in python in 
> HUGEwebsites -
> 
> 
> > What kind of low-level socket and threading code
> is necessary for a 
> > db
> >  intensive site such as yahoo. How do we use it
> from python? does
> >  anyone  have experience using it
> >
> >
> >
> http://redditblog.blogspot.com/2005/12/on-lisp.html
> > >From moving to python by the founders of reddit
> >
> >
> > Because of the low-level socket and threading code
> we had to write,
> > reddit would not run on my Mac, and I was always
> tethered to our
> > FreeBSD development server. Not being able to
> program offline is a
> > pain.
> >
> > I would imagine that they aren't just using a
> database.
> > most of the "low level socket stuff" I've seen is
> about setting
> > timeouts and doing Async IO.
> >
> >
> >
> > ---------------------------------
> > Do you Yahoo!?
> > Get on board. You're invited to try the new Yahoo!
> Mail Beta. 
> 
> 


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

From anilmrn at yahoo.com  Fri Aug 18 10:29:29 2006
From: anilmrn at yahoo.com (anil maran)
Date: Fri, 18 Aug 2006 01:29:29 -0700 (PDT)
Subject: [Tutor] web application and database caching technique
In-Reply-To: <004d01c6c23f$e17f6ab0$0201a8c0@XPpro>
Message-ID: <20060818082929.80856.qmail@web55906.mail.re3.yahoo.com>

Postgresql 8
and python 2.4
let me find out how to do the caching on db, thanks if
you have other pointers on how to cache db in python
pls let me know

--- Alan Gauld <alan.gauld at freenet.co.uk> wrote:

> >i m trying to build a webapplication, i need to
> cache db records 
> > as it has become very slow the sql queries and
> retrival
> > can you guys helpe me out in designing cache
> structures/ hash 
> > tables for these cases 
> 
> Which database? Most relational databases have
> caching as a 
> feature that you can configure. It may be that you
> can simply 
> increase the size of the database cache on the
> server?
> 
> A lot easier and usually a lot more efficient and
> reliable too.
> 
> Fixing database scaleability issues is rarely best
> done 
> outside of the database! (Small volume query
> improvements 
> are another matter entirely!)
> 
> Alan G.
> 


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

From anilmrn at yahoo.com  Fri Aug 18 10:33:04 2006
From: anilmrn at yahoo.com (anil maran)
Date: Fri, 18 Aug 2006 01:33:04 -0700 (PDT)
Subject: [Tutor] Twisted Medusa Athena frameworks
Message-ID: <20060818083304.2134.qmail@web55913.mail.re3.yahoo.com>

hi guys
i m trying to create a simple site, and on certain
event triggers the server or python program needs to 
send out messages to the site.

i m  tyring to accomplish it using twisted or medusa
or 

Does any one have experience using it
or the asyncore module in python
please help
thanks a ton
anil

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

From alan.gauld at freenet.co.uk  Fri Aug 18 10:38:20 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 18 Aug 2006 09:38:20 +0100
Subject: [Tutor] 2D array question [was (no subject)]
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com><44E44B0D.7050309@tds.net><d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com><44E4A337.30701@tds.net><d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com><00ac01c6c247$2b350780$0201a8c0@XPpro><d7253a230608172106j561257bcyac65802ba17a4a9b@mail.gmail.com><5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com>
	<d7253a230608172150i5ddcf565y75ce4634e7d7b2b2@mail.gmail.com>
Message-ID: <006c01c6c2a1$c1fa3000$0201a8c0@XPpro>

> Mr. Kuhlman it says python is not configured for tk.

Gaarrgh! Why do linux distros do this? Stooopid...

You will need to fetch another version of Python with 
Tk support built in. Its a compile time option so you can 
either fetch the source an build it yourself or find a Suse 
package with Tk support already selected.

Its really stupid for Suse to do that, it only saves a tiny 
amount of space and means you can't run any programs 
based on Tkinter...

> but on another note does anyone know how to make a 2d array?

This should probably be a separate post.

Also can you change the subject line in your posts so people 
can fiind the thread easily. I've changed it on this one to pick 
up the 2D array issue....

A 2D array is just a table. There are several ways to do that 
in Python but the easiest is just a list of lists: Think of a chess 
game as an example where the boars is represented by 
an 8x8 2D array:

chessBoard = [
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0]
]

Now you can access the third row, 4th column with:

chessBoard[2][3]   # remember zero indexing!

Is that clear?

You can also use tuples similarly, or nested dictionaries.
A lot will depend on the data you are storing and how you 
want to access it.

Finally you can create a Class with bespoke methods to 
more closely model your problem, but the class will usaually 
have one of the above solutions internally anyhow!

HTH.

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

From anilmrn at yahoo.com  Fri Aug 18 10:56:53 2006
From: anilmrn at yahoo.com (anil maran)
Date: Fri, 18 Aug 2006 01:56:53 -0700 (PDT)
Subject: [Tutor] editors
Message-ID: <20060818085653.38477.qmail@web55902.mail.re3.yahoo.com>

what editors do you guys use?

emacs
vi?
xemacs

are there any plugins to configure autocomplete, i
want something to do good autocomplete such as showing
what type of arguments are available etc
thanks

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

From matthew at CuneiformSoftware.com  Fri Aug 18 11:41:47 2006
From: matthew at CuneiformSoftware.com (Matthew Webber)
Date: Fri, 18 Aug 2006 10:41:47 +0100
Subject: [Tutor] editors
In-Reply-To: <20060818085653.38477.qmail@web55902.mail.re3.yahoo.com>
Message-ID: <002901c6c2aa$885fb3c0$0200a8c0@kookaburra>

I use Eclipse (www.eclipse.org) with the pydev plugin
(pydev.sourceforge.net). Eclipse is written in Java (you need the JVM to run
it, and a decent amount of memory) and was originally intended for Java
development (that's what most of the docs reflect). It now has plugins
available for other languages. It also has am SVN plugin.
Matthew 

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of anil maran
Sent: 18 August 2006 09:57
To: tutor at python.org
Subject: [Tutor] editors

what editors do you guys use?

emacs
vi?
xemacs

are there any plugins to configure autocomplete, i
want something to do good autocomplete such as showing
what type of arguments are available etc
thanks



From kent37 at tds.net  Fri Aug 18 12:52:06 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 18 Aug 2006 06:52:06 -0400
Subject: [Tutor] Actual code that illustrates problem
In-Reply-To: <000701c6c29a$9da92d20$0201a8c0@XPpro>
References: <44E3E590.000005.00920@YOUR-4105E587B6>	<00ea01c6c24e$c7188b70$0201a8c0@XPpro>	<44E50541.9070609@polaris.net>
	<000701c6c29a$9da92d20$0201a8c0@XPpro>
Message-ID: <44E59BD6.1080308@tds.net>

Alan Gauld wrote:
>>>> #                print " "
>>>> #                print " In strongfac "
>>>> #                print " Found1: x = ",x
>>>>         
>>> You could do all of this with a single print:
>>>
>>> print "\n In strongfac \nFound1: x = ", x
>>>
>>>       
>> uuuuuuuuuh..     Too compact for me.
>> I need to see the logic more spread out.
>>     
>
> \n is the newline character.
> An alternative is to use triple quotes:
>
> print '''
> In strongfac
> Found1: x = ''',x
>
> But that still clutters up the code listing with extra lines that 
> have nothing to do with the algorithm - the main advantage in  
> reducing to one print statement..

This is obviously a matter of personal preference. I prefer the longer 
form as well - I usually use a separate print statement for each line of 
output. I would say it has everything to do with the function, if not 
the algorithm - it clearly represents the form the output will take.

Kent


From kent37 at tds.net  Fri Aug 18 12:56:55 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 18 Aug 2006 06:56:55 -0400
Subject: [Tutor] 2D array question [was (no subject)]
In-Reply-To: <006c01c6c2a1$c1fa3000$0201a8c0@XPpro>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com><44E44B0D.7050309@tds.net><d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com><44E4A337.30701@tds.net><d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com><00ac01c6c247$2b350780$0201a8c0@XPpro><d7253a230608172106j561257bcyac65802ba17a4a9b@mail.gmail.com><5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com>	<d7253a230608172150i5ddcf565y75ce4634e7d7b2b2@mail.gmail.com>
	<006c01c6c2a1$c1fa3000$0201a8c0@XPpro>
Message-ID: <44E59CF7.1070407@tds.net>

Alan Gauld wrote:
>> but on another note does anyone know how to make a 2d array?
>>     
>
> A 2D array is just a table. There are several ways to do that 
> in Python 
<snip several good suggestions>

If you need high-performance arrays you should look at numpy:
http://numpy.scipy.org/

Kent


From alan.gauld at freenet.co.uk  Fri Aug 18 12:57:51 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 18 Aug 2006 11:57:51 +0100
Subject: [Tutor] editors
References: <20060818085653.38477.qmail@web55902.mail.re3.yahoo.com>
Message-ID: <001c01c6c2b5$277b50e0$0201a8c0@XPpro>

> what editors do you guys use?
>
> emacs
> vi?
> xemacs

Yes. All of the above

Also

ed, ex, Axe, xedit, pine, Scite, IPFS, EDT, Notepad, Textpad, etc etc.

But the bulk of my Python editing these days is done
on either Pythonwin/Scite or vim. The more I use Pyhonwin
the more I prefer it to IDLE, but for serious editing sessions
I still fall back on vim.

But put me on a Unix box and its emacs for big edits vim for quick
stuff - I'm not sure why the difference!

But editor preferences are almost as deeply personal as
language preferences.

> are there any plugins to configure autocomplete, i
> want something to do good autocomplete such as showing
> what type of arguments are available etc

Both IDLE and Pythonwin do those things.
I assume other IDEs like Blackadder, Kimono and Eclipse
will also do so.

BTW One feature of Scite I like is the tabbed windows, however
despite the fact that Pythonwin uses the Scinbtilla/Scite editor
I can't find a way to turn that on in Pythonwin - does anyone
else know?

Alan G 


From kent37 at tds.net  Fri Aug 18 13:18:35 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 18 Aug 2006 07:18:35 -0400
Subject: [Tutor] Low level socket and threading code in python
 in	HUGEwebsites -
In-Reply-To: <20060818082753.75918.qmail@web55907.mail.re3.yahoo.com>
References: <20060818082753.75918.qmail@web55907.mail.re3.yahoo.com>
Message-ID: <44E5A20B.8060400@tds.net>

anil maran wrote:
> thanks alan it is very enlightening
> can one of you guys who have experience building sites
> such as yahoo mail and stuff, explain what parts of a
> webserver needs to be multithreaded

Generally you need a thread or process for each HTTP request, otherwise 
you will process requests serially (one at a time) which severely limits 
the number of concurrent users you can have.

Kent


From tiagosaboga at terra.com.br  Fri Aug 18 14:47:53 2006
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Fri, 18 Aug 2006 09:47:53 -0300
Subject: [Tutor] man pages parser
Message-ID: <200608180947.54028.tiagosaboga@terra.com.br>

Hi!

I'm working on a front-end to various unix command-line utilities, and I want 
to be able to retrieve informations from man pages, specially existing 
options and their help strings. Do you know a good way to handle this? I 
could parse directly the troff sources (is there already a parser for that?), 
the resulting man pages, or I could first translate it to docbook (with 
doclifter) or html (mantohtml) and than use a xml or html parser. 

All these options require a good amount of time for me, as I don't know any of 
the parsers, and I don't know the languages, except for html. It's why I'm 
asking here first if there is a better solution or other advices...

Thanks.

Tiago Saboga.

From dyoo at hkn.eecs.berkeley.edu  Fri Aug 18 16:11:31 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 18 Aug 2006 07:11:31 -0700 (PDT)
Subject: [Tutor] man pages parser
In-Reply-To: <200608180947.54028.tiagosaboga@terra.com.br>
References: <200608180947.54028.tiagosaboga@terra.com.br>
Message-ID: <Pine.LNX.4.64.0608180710450.31094@hkn.eecs.berkeley.edu>

> to be able to retrieve informations from man pages, specially existing
> options and their help strings. Do you know a good way to handle this? I
> could parse directly the troff sources (is there already a parser for that?)

Hi Tiago,

Someone else has done this already.  *grin*  Check out ESR's doclifter:

     http://www.catb.org/~esr/doclifter/

From kermit at polaris.net  Fri Aug 18 17:14:43 2006
From: kermit at polaris.net (Kermit Rose)
Date: Fri, 18 Aug 2006 11:14:43 -0400
Subject: [Tutor] Actual code that illustrates problem
In-Reply-To: <000701c6c29a$9da92d20$0201a8c0@XPpro>
References: <44E3E590.000005.00920@YOUR-4105E587B6>
	<00ea01c6c24e$c7188b70$0201a8c0@XPpro>
	<44E50541.9070609@polaris.net>
	<000701c6c29a$9da92d20$0201a8c0@XPpro>
Message-ID: <44E5D963.5080400@polaris.net>

Alan Gauld wrote:
>
>>>> #                print " "
>>>> #                print " In strongfac "
>>>> #                print " Found1: x = ",x
>>>
>>> You could do all of this with a single print:
>>>
>>> print "\n In strongfac \nFound1: x = ", x
>>>
>> uuuuuuuuuh..     Too compact for me.
>> I need to see the logic more spread out.
>
> \n is the newline character.
>
>

Ah.  Thanks.  Explaining the  backslash n helped me understand.

I will use the backslash n to reduce lines of print statements.

Kermit   <  kermit at polaris.net  >




From artificiallystupid at yahoo.com  Fri Aug 18 17:35:29 2006
From: artificiallystupid at yahoo.com (Johnston Jiaa)
Date: Fri, 18 Aug 2006 08:35:29 -0700 (PDT)
Subject: [Tutor] first programming project
Message-ID: <20060818153529.71944.qmail@web50404.mail.yahoo.com>

I have read through many beginner texts on programming
and believe myself to be fairly decent at python, but
I have no idea how to do anything worthwhile.  I
understand that before coding a project it's best to
design it and write some pseudocode first.  I want to
create a fun GUI assignment manager.  I read about the
Tkinter toolkit and would like to use it to write my
program.  I made a list of features:

- root window will be split into three sections: 
categories, assignments, and an animated creature that
responds to actions

- assignments will have three attributes:  priority,
points (grade points for completeness and creative
points for how interestingly assignment was done),
dates (assigned, completed)
- sub-assignments can be added to assignments to break
it up into steps
- each assignment will fit into a marking period
category with two averages (grade average and creative
average)
- grade average is the percentage found by dividing
points earned by total possible points

- creature will have two statuses (hunger status, mood
status)
- hunger status effected by grade points and averages
- mood status effected by creative points and averages
- each time assignment completed, food appears in
creature section and user may feed it or store it in a
bin (food more nourishing for higher-point
assignments)
- increments of creative points (maybe for every 10?)
add mini-games to play with creature

That's the general idea of my program.  I have never
written a real program before, am I missing any steps?
 Is there something I am missing from having this be a
complete program?  Any help at all is greatly
appreciated.

Johnston Jiaa

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

From jim at well.com  Fri Aug 18 18:04:01 2006
From: jim at well.com (jim stockford)
Date: Fri, 18 Aug 2006 09:04:01 -0700
Subject: [Tutor] first programming project
In-Reply-To: <20060818153529.71944.qmail@web50404.mail.yahoo.com>
References: <20060818153529.71944.qmail@web50404.mail.yahoo.com>
Message-ID: <29ED1D28-2ED3-11DB-B3EC-000A95EA5592@well.com>


    i hope this helps: what a fun idea! do it!

    my way is to do a bad job fast then re-visit the
plans and reimplement and test and re-visit and
reimplement and test and....
    consider writing a main program that does the
primary work and outputs as text-only.
    maybe then create four classes: the master,
which gets input and drives the other three: the
category, the assignment, and the creature. Or
you could implement functions instead of classes.


On Aug 18, 2006, at 8:35 AM, Johnston Jiaa wrote:

> I have read through many beginner texts on programming
> and believe myself to be fairly decent at python, but
> I have no idea how to do anything worthwhile.  I
> understand that before coding a project it's best to
> design it and write some pseudocode first.  I want to
> create a fun GUI assignment manager.  I read about the
> Tkinter toolkit and would like to use it to write my
> program.  I made a list of features:
>
> - root window will be split into three sections:
> categories, assignments, and an animated creature that
> responds to actions
>
> - assignments will have three attributes:  priority,
> points (grade points for completeness and creative
> points for how interestingly assignment was done),
> dates (assigned, completed)
> - sub-assignments can be added to assignments to break
> it up into steps
> - each assignment will fit into a marking period
> category with two averages (grade average and creative
> average)
> - grade average is the percentage found by dividing
> points earned by total possible points
>
> - creature will have two statuses (hunger status, mood
> status)
> - hunger status effected by grade points and averages
> - mood status effected by creative points and averages
> - each time assignment completed, food appears in
> creature section and user may feed it or store it in a
> bin (food more nourishing for higher-point
> assignments)
> - increments of creative points (maybe for every 10?)
> add mini-games to play with creature
>
> That's the general idea of my program.  I have never
> written a real program before, am I missing any steps?
>  Is there something I am missing from having this be a
> complete program?  Any help at all is greatly
> appreciated.
>
> Johnston Jiaa
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From amadeo.bellotti at gmail.com  Fri Aug 18 18:04:20 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Fri, 18 Aug 2006 12:04:20 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <002b01c6c29a$fa21a960$0201a8c0@XPpro>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
	<44E4A337.30701@tds.net>
	<d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
	<00ac01c6c247$2b350780$0201a8c0@XPpro>
	<d7253a230608172106j561257bcyac65802ba17a4a9b@mail.gmail.com>
	<002b01c6c29a$fa21a960$0201a8c0@XPpro>
Message-ID: <d7253a230608180904o315883c4ob8cba52cd621a799@mail.gmail.com>

Mr. Gauld I run it from termainal on GNOME and it says "** IDLE can't import
Tkinter.  Your Python may not be configured for Tk. **"

and Yea I am Administrator this is my Home computer after all im only 15.

On 8/18/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
>
> > thank you but IDLE doesnt seem to work on Suse 9.2 do you know a way
> > to fix
> > it?
>
> I've only used IDLE on Linux a few times but it certainly works
> on RedHat, Mandriva and Slackware. And it used to work on
> Suse 5 - the only time I ever used Suse...
>
> What hapens when you try to run IDLE? It may just be a case of
> fixing a path setting or somesuch.
>
> Alan G.
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060818/61012bb3/attachment.html 

From amadeo.bellotti at gmail.com  Fri Aug 18 18:06:39 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Fri, 18 Aug 2006 12:06:39 -0400
Subject: [Tutor] 2D array question [was (no subject)]
In-Reply-To: <006c01c6c2a1$c1fa3000$0201a8c0@XPpro>
References: <d7253a230608162137r446e2f18l55427aabc449e331@mail.gmail.com>
	<44E44B0D.7050309@tds.net>
	<d7253a230608170644l7158e761ufdb4b9b87ec369f8@mail.gmail.com>
	<44E4A337.30701@tds.net>
	<d7253a230608171028n41cd8f8cqf71a3464560b570b@mail.gmail.com>
	<00ac01c6c247$2b350780$0201a8c0@XPpro>
	<d7253a230608172106j561257bcyac65802ba17a4a9b@mail.gmail.com>
	<5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com>
	<d7253a230608172150i5ddcf565y75ce4634e7d7b2b2@mail.gmail.com>
	<006c01c6c2a1$c1fa3000$0201a8c0@XPpro>
Message-ID: <d7253a230608180906u746a1918o78efd9183633bfed@mail.gmail.com>

thank you so much Mr. Gauld that really helped

On 8/18/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
> > Mr. Kuhlman it says python is not configured for tk.
>
> Gaarrgh! Why do linux distros do this? Stooopid...
>
> You will need to fetch another version of Python with
> Tk support built in. Its a compile time option so you can
> either fetch the source an build it yourself or find a Suse
> package with Tk support already selected.
>
> Its really stupid for Suse to do that, it only saves a tiny
> amount of space and means you can't run any programs
> based on Tkinter...
>
> > but on another note does anyone know how to make a 2d array?
>
> This should probably be a separate post.
>
> Also can you change the subject line in your posts so people
> can fiind the thread easily. I've changed it on this one to pick
> up the 2D array issue....
>
> A 2D array is just a table. There are several ways to do that
> in Python but the easiest is just a list of lists: Think of a chess
> game as an example where the boars is represented by
> an 8x8 2D array:
>
> chessBoard = [
>     [0,0,0,0,0,0,0,0],
>     [0,0,0,0,0,0,0,0],
>     [0,0,0,0,0,0,0,0],
>     [0,0,0,0,0,0,0,0],
>     [0,0,0,0,0,0,0,0],
>     [0,0,0,0,0,0,0,0],
>     [0,0,0,0,0,0,0,0],
>     [0,0,0,0,0,0,0,0]
> ]
>
> Now you can access the third row, 4th column with:
>
> chessBoard[2][3]   # remember zero indexing!
>
> Is that clear?
>
> You can also use tuples similarly, or nested dictionaries.
> A lot will depend on the data you are storing and how you
> want to access it.
>
> Finally you can create a Class with bespoke methods to
> more closely model your problem, but the class will usaually
> have one of the above solutions internally anyhow!
>
> HTH.
>
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060818/bb6189a4/attachment.htm 

From alan.gauld at freenet.co.uk  Fri Aug 18 20:05:39 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 18 Aug 2006 19:05:39 +0100
Subject: [Tutor] man pages parser
References: <200608180947.54028.tiagosaboga@terra.com.br>
Message-ID: <002b01c6c2f0$ea0e8ec0$0201a8c0@XPpro>

> to be able to retrieve informations from man pages, specially 
> existing
> options and their help strings.

I'd actually try parsing the man page sources. They are already in
a layout language so finding the options should be easy - there is
a man macro for that I believe. But i've never tried it!

If that turns out to be harder than I think, then an XML option
would be next best. But i donlt know of a man2xml command.

Finally the man2html route is definitely possible and BeautifulSoup
should be able to find the option tags for you - but it may find
many others besides so you might need some clever selection
criteria. But the parsing at least should be done for you.

> could parse directly the troff sources (is there already a parser 
> for that?),

I don;t know if there is a parser, but ISTR there is a specific option
tag in the man macros for command options so it should be easy to
find and extract the data by looking for

.OP

or whatever the tag is. The good news is that troff macros are nearly
always located at the marging and start with a dot so they are easy
to locate using simple regex.

Actually I just had a quick look and its not so good after all, the
format seems to be

.SH Options
......text in here
.B  <option>

But worse not all pages follow the official format as exemplified in
the "yes" man page, some don;t even have an Options SubHeading...

Another option(sic) to consider is parsing the .cat files that are
produced by man on first use - a bit like pyhon produces .pyc files).
They are plain text so might be easier to search.

Finally you could look at the info files(written in LaTeX, if they 
exist
for all your commands.

But I think an xml/html solution is looking better!

HTH,

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


From alan.gauld at freenet.co.uk  Fri Aug 18 20:08:03 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 18 Aug 2006 19:08:03 +0100
Subject: [Tutor] man pages parser
References: <200608180947.54028.tiagosaboga@terra.com.br>
	<Pine.LNX.4.64.0608180710450.31094@hkn.eecs.berkeley.edu>
Message-ID: <002f01c6c2f1$40212a20$0201a8c0@XPpro>

> Someone else has done this already.  *grin*  Check out ESR's 
> doclifter:
>
>     http://www.catb.org/~esr/doclifter/

Looks like that gets you to XML format, in that case I'd recommend
that you go fetch ElementTree and use that to parse the XML files.

Alan G. 


From alan.gauld at freenet.co.uk  Fri Aug 18 20:20:18 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 18 Aug 2006 19:20:18 +0100
Subject: [Tutor] first programming project
References: <20060818153529.71944.qmail@web50404.mail.yahoo.com>
Message-ID: <003901c6c2f2$f6323ec0$0201a8c0@XPpro>

Its a pretty reasonable project, certainly not trivial but not
impossible either.

> design it and write some pseudocode first.  I want to
> create a fun GUI assignment manager.  I read about the
> Tkinter toolkit and would like to use it to write my
> program.  I made a list of features:
>
> - root window will be split into three sections:
> categories, assignments, and an animated creature that
> responds to actions

OK, This is one part of your project - the GUI.
I'd leave it to last! :-)
Not least because as a beginner its likely to take up a fair
bit of time and trying to debug the code and the GUI will
be doubly difficult!

> - assignments will have three attributes:  priority,
> points (grade points for completeness and creative
> points for how interestingly assignment was done),
> dates (assigned, completed)
> - sub-assignments can be added to assignments to break
> it up into steps
> - each assignment will fit into a marking period
> category with two averages (grade average and creative
> average)
> - grade average is the percentage found by dividing
> points earned by total possible points

OK, And tisd is the second bit, I'd do this first.
Get it working as a command line program but make sure
you don't put print statements etc inside your functions
- that will make bolting on the GUI much easier later.

> - creature will have two statuses (hunger status, mood
> status)
> - hunger status effected by grade points and averages
> - mood status effected by creative points and averages
> - each time assignment completed, food appears in
> creature section and user may feed it or store it in a
> bin (food more nourishing for higher-point
> assignments)
> - increments of creative points (maybe for every 10?)
> add mini-games to play with creature

And this is therefore the 3rd chiunk which I'd do after
the assignents (which it kind of relies on) but before
the GUI.

One the first two bits are working reliably you can build the
GUI and link it to the functions you wrote for the command
line version and be confident the earlier code works, theefore
any problems will lie ion the GUI or its calling mechanisms.

If you get stuck on any of it ask the list! :-)

Start small and get some aspect working then build up from
there. Think about how to test and use it first, build that 
"scaffolding"
before writing the code - just use print statement initially....
Then plug the working functions into your scaffolding piece by piece.

HTH,

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


From rdm at rcblue.com  Fri Aug 18 23:23:50 2006
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 18 Aug 2006 14:23:50 -0700
Subject: [Tutor] puzzled again by decimal module
Message-ID: <7.0.1.0.2.20060818135328.0383fb98@rcblue.com>

As an exercise that I thought would help me understand the decimal 
module, I've been trying write a script (precisionFactorial.py) that 
uses a modified fact(n) to compute precise factorials using the 
decimal module. I''m getting nowhere fast, and don't understand why. 
Here's what I have so far:

def fact(n):
     """
     compute n!
     """
     product = 1
     while n > 1:
       product *= n
       n -= 1
     return product

========================================
# precisionFactorial.py

import decimal

def d(x):
     return decimal.Decimal(str(x))

def fact(n):
     product = 1
     while d(n) > 1:
         product *= n
         d(n) -= 1
     return product

n = 100
decimal.getcontext().prec = 200
print product
===================================

This gets me

"Syntax error
Theres an error in your program.
*** can't assign to function call
(precisionFactorial.py, line 11)"

line 11 is "d(n) -= 1".

Advice, please.

Dick Moores
rdm at rcblue.com

Win XP, Python 2.4






From bgailer at alum.rpi.edu  Fri Aug 18 23:41:42 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 18 Aug 2006 14:41:42 -0700
Subject: [Tutor] puzzled again by decimal module
In-Reply-To: <7.0.1.0.2.20060818135328.0383fb98@rcblue.com>
References: <7.0.1.0.2.20060818135328.0383fb98@rcblue.com>
Message-ID: <44E63416.90405@alum.rpi.edu>

Dick Moores wrote:
> As an exercise that I thought would help me understand the decimal 
> module, I've been trying write a script (precisionFactorial.py) that 
> uses a modified fact(n) to compute precise factorials 
What do you mean by "precise factorials"? Python's long integer should 
handle this just fine.
> [snip]
>   

> # precisionFactorial.py
>
> import decimal
>
> def d(x):
>      return decimal.Decimal(str(x))
>
> def fact(n):
>      product = 1
>      while d(n) > 1:
>          product *= n
>          d(n) -= 1 
>   
 d(n) -= 1 is shorthand for d(n) = d(n) - 1. This will fail, since d(n) 
is a function call, which is not valid as as assignment target. Instead 
you should should:

def fact(n):
     product = 1
     dec_n = d(n)
     while dec_n > 1:
         product *= n
         dec_n -= 1 
     return product


[snip]
But as I mentioned there is no value in using decimal here.

-- 
Bob Gailer
510-978-4454


From rdm at rcblue.com  Sat Aug 19 01:10:21 2006
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 18 Aug 2006 16:10:21 -0700
Subject: [Tutor] puzzled again by decimal module
Message-ID: <7.0.1.0.2.20060818160936.0678a678@rcblue.com>

At 02:41 PM 8/18/2006, Bob Gailer wrote:
>Dick Moores wrote:
>>As an exercise that I thought would help me understand the decimal 
>>module, I've been trying write a script (precisionFactorial.py) 
>>that uses a modified fact(n) to compute precise factorials
>What do you mean by "precise factorials"? Python's long integer 
>should handle this just fine.

Well, actually, my old fact(100) produces 
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Not exactly correct.

>>[snip]
>>
>
>># precisionFactorial.py
>>
>>import decimal
>>
>>def d(x):
>>      return decimal.Decimal(str(x))
>>
>>def fact(n):
>>      product = 1
>>      while d(n) > 1:
>>          product *= n
>>          d(n) -= 1
>d(n) -= 1 is shorthand for d(n) = d(n) - 1. This will fail, since 
>d(n) is a function call, which is not valid as as assignment target. 
>Instead you should should:
>
>def fact(n):
>     product = 1
>     dec_n = d(n)
>     while dec_n > 1:
>         product *= n
>         dec_n -= 1     return product

Ah, a notation problem. Thanks!

But here's the revised precisionFactorial.py:

========================
# 1precisionFactorial.py

import decimal

def d(x):
     return decimal.Decimal(str(x))

def fact(n):
     product = 1
     dec_n = d(n)
     while dec_n > 1:
         product *= dec_n
         dec_n -= 1
     return product

n = 100
decimal.getcontext().prec = 200
print fact(n)
================================================

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Still not exactly correct! I'm bewildered.

Dick


From rabidpoobear at gmail.com  Sat Aug 19 01:24:35 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 18 Aug 2006 18:24:35 -0500
Subject: [Tutor] puzzled again by decimal module
In-Reply-To: <7.0.1.0.2.20060818160936.0678a678@rcblue.com>
References: <7.0.1.0.2.20060818160936.0678a678@rcblue.com>
Message-ID: <44E64C33.90709@gmail.com>

Dick Moores wrote:
> At 02:41 PM 8/18/2006, Bob Gailer wrote:
>   
>> Dick Moores wrote:
>>     
>>> As an exercise that I thought would help me understand the decimal 
>>> module, I've been trying write a script (precisionFactorial.py) 
>>> that uses a modified fact(n) to compute precise factorials
>>>       
>> What do you mean by "precise factorials"? Python's long integer 
>> should handle this just fine.
>>     
>
> Well, actually, my old fact(100) produces 
> 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
> Not exactly correct.
>
>   
>>> [snip]
>>>
>>>       
>>> # precisionFactorial.py
>>>
>>> import decimal
>>>
>>> def d(x):
>>>      return decimal.Decimal(str(x))
>>>
>>> def fact(n):
>>>      product = 1
>>>      while d(n) > 1:
>>>          product *= n
>>>          d(n) -= 1
>>>       
>> d(n) -= 1 is shorthand for d(n) = d(n) - 1. This will fail, since 
>> d(n) is a function call, which is not valid as as assignment target. 
>> Instead you should should:
>>
>> def fact(n):
>>     product = 1
>>     dec_n = d(n)
>>     while dec_n > 1:
>>         product *= n
>>         dec_n -= 1     return product
>>     
>
> Ah, a notation problem. Thanks!
>
> But here's the revised precisionFactorial.py:
>
> ========================
> # 1precisionFactorial.py
>
> import decimal
>
> def d(x):
>      return decimal.Decimal(str(x))
>
> def fact(n):
>      product = 1
>      dec_n = d(n)
>      while dec_n > 1:
>          product *= dec_n
>          dec_n -= 1
>      return product
>
> n = 100
> decimal.getcontext().prec = 200
> print fact(n)
> ================================================
>
> 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
>
> Still not exactly correct! I'm bewildered.
>   
The results look the same to me
why do you think they're not correct?
what is the result supposed to be?
> Dick
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From rdm at rcblue.com  Sat Aug 19 01:37:18 2006
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 18 Aug 2006 16:37:18 -0700
Subject: [Tutor] puzzled again by decimal module
In-Reply-To: <44E64C33.90709@gmail.com>
References: <7.0.1.0.2.20060818160936.0678a678@rcblue.com>
	<44E64C33.90709@gmail.com>
Message-ID: <7.0.1.0.2.20060818163419.06794f50@rcblue.com>

At 04:24 PM 8/18/2006, Luke Paireepinart wrote:
>Dick Moores wrote:
> > But here's the revised precisionFactorial.py:
> >
> > ========================
> > # 1precisionFactorial.py
> >
> > import decimal
> >
> > def d(x):
> >      return decimal.Decimal(str(x))
> >
> > def fact(n):
> >      product = 1
> >      dec_n = d(n)
> >      while dec_n > 1:
> >          product *= dec_n
> >          dec_n -= 1
> >      return product
> >
> > n = 100
> > decimal.getcontext().prec = 200
> > print fact(n)
> > ================================================
> >
> > 
> 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
> >
> > Still not exactly correct! I'm bewildered.
> >
>The results look the same to me
>why do you think they're not correct?
>what is the result supposed to be?

An integer not ending in 26 zeroes?

Dick




From tschaboo at gmx.at  Sat Aug 19 01:50:03 2006
From: tschaboo at gmx.at (Christian Tschabuschnig)
Date: Sat, 19 Aug 2006 01:50:03 +0200
Subject: [Tutor] puzzled again by decimal module
In-Reply-To: <7.0.1.0.2.20060818163419.06794f50@rcblue.com>
References: <7.0.1.0.2.20060818160936.0678a678@rcblue.com>	<44E64C33.90709@gmail.com>
	<7.0.1.0.2.20060818163419.06794f50@rcblue.com>
Message-ID: <44E6522B.1060703@gmx.at>

>> 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
>>> Still not exactly correct! I'm bewildered.
>>>
>> The results look the same to me
>> why do you think they're not correct?
>> what is the result supposed to be?
> 
> An integer not ending in 26 zeroes?

The result is correct. I checked it with Mathematica.

Christian



From rdm at rcblue.com  Sat Aug 19 02:20:34 2006
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 18 Aug 2006 17:20:34 -0700
Subject: [Tutor] puzzled again by decimal module
In-Reply-To: <44E6522B.1060703@gmx.at>
References: <7.0.1.0.2.20060818160936.0678a678@rcblue.com>
	<44E64C33.90709@gmail.com>
	<7.0.1.0.2.20060818163419.06794f50@rcblue.com>
	<44E6522B.1060703@gmx.at>
Message-ID: <7.0.1.0.2.20060818171423.06867af0@rcblue.com>

At 04:50 PM 8/18/2006, Christian Tschabuschnig wrote:
> >> 
> 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
> >>> Still not exactly correct! I'm bewildered.
> >>>
> >> The results look the same to me
> >> why do you think they're not correct?
> >> what is the result supposed to be?
> >
> > An integer not ending in 26 zeroes?
>
>The result is correct. I checked it with Mathematica.

<BLUSH> Yes, I'm sure you are. I'd forgotten about all those factors 
of 100! that end in zero (10, 20, 30, ..., 100).

Thanks to all.

Dick




From tim.peters at gmail.com  Sat Aug 19 03:07:11 2006
From: tim.peters at gmail.com (Tim Peters)
Date: Fri, 18 Aug 2006 21:07:11 -0400
Subject: [Tutor] puzzled again by decimal module
In-Reply-To: <7.0.1.0.2.20060818171423.06867af0@rcblue.com>
References: <7.0.1.0.2.20060818160936.0678a678@rcblue.com>
	<44E64C33.90709@gmail.com>
	<7.0.1.0.2.20060818163419.06794f50@rcblue.com>
	<44E6522B.1060703@gmx.at>
	<7.0.1.0.2.20060818171423.06867af0@rcblue.com>
Message-ID: <1f7befae0608181807g4ea6c2e7j4fc637a92afb2c0d@mail.gmail.com>

[Dick Moores, computes 100 factorial as
 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

 but worries about all the trailing zeros]

> <BLUSH> Yes, I'm sure you are. I'd forgotten about all those factors
> of 100! that end in zero (10, 20, 30, ..., 100).

And others, like 2 and 5 whose product is 10, or 4 and 25 whose product is 100.

For a fun :-) exercise, prove that the number of trailing zeroes in n!
is the sum, from i = 1 to infinity, of n // 5**i (of course as soon as
you reach a value of i such that n < 5**i, the quotient is 0 at that i
and forever after).

In this case,

100 // 5 + 100 // 25 + 100 // 125 + ... =

20 + 4 + 0 + ... =

24

From tschaboo at gmx.at  Sat Aug 19 03:31:38 2006
From: tschaboo at gmx.at (Christian Tschabuschnig)
Date: Sat, 19 Aug 2006 03:31:38 +0200
Subject: [Tutor] puzzled again by decimal module
In-Reply-To: <1f7befae0608181807g4ea6c2e7j4fc637a92afb2c0d@mail.gmail.com>
References: <7.0.1.0.2.20060818160936.0678a678@rcblue.com>	<44E64C33.90709@gmail.com>	<7.0.1.0.2.20060818163419.06794f50@rcblue.com>	<44E6522B.1060703@gmx.at>	<7.0.1.0.2.20060818171423.06867af0@rcblue.com>
	<1f7befae0608181807g4ea6c2e7j4fc637a92afb2c0d@mail.gmail.com>
Message-ID: <44E669FA.6080106@gmx.at>

Tim Peters wrote:
> [Dick Moores, computes 100 factorial as
>  93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
> 
>  but worries about all the trailing zeros]
> 
>> <BLUSH> Yes, I'm sure you are. I'd forgotten about all those factors
>> of 100! that end in zero (10, 20, 30, ..., 100).
> 
> And others, like 2 and 5 whose product is 10, or 4 and 25 whose product is 100.
> 
> For a fun :-) exercise, prove that the number of trailing zeroes in n!
> is the sum, from i = 1 to infinity, of n // 5**i (of course as soon as
> you reach a value of i such that n < 5**i, the quotient is 0 at that i
> and forever after).
> 
> In this case,
> 
> 100 // 5 + 100 // 25 + 100 // 125 + ... =
> 
> 20 + 4 + 0 + ... =
> 
> 24

you should do that with floating-point, so that the quotient never get's
zero and the "i=1 to infinity" makes sense. This way you (might) get 25
which is correct; not 24.

but i'm just guessing - i have no way to prove it ;-)

From tim.peters at gmail.com  Sat Aug 19 03:51:00 2006
From: tim.peters at gmail.com (Tim Peters)
Date: Fri, 18 Aug 2006 21:51:00 -0400
Subject: [Tutor] puzzled again by decimal module
In-Reply-To: <44E669FA.6080106@gmx.at>
References: <7.0.1.0.2.20060818160936.0678a678@rcblue.com>
	<44E64C33.90709@gmail.com>
	<7.0.1.0.2.20060818163419.06794f50@rcblue.com>
	<44E6522B.1060703@gmx.at>
	<7.0.1.0.2.20060818171423.06867af0@rcblue.com>
	<1f7befae0608181807g4ea6c2e7j4fc637a92afb2c0d@mail.gmail.com>
	<44E669FA.6080106@gmx.at>
Message-ID: <1f7befae0608181851j1f3fdb50w9766e3822aacebeb@mail.gmail.com>

[Tim Peters]
>> For a fun :-) exercise, prove that the number of trailing zeroes in n!
>> is the sum, from i = 1 to infinity, of n // 5**i (of course as soon as
>> you reach a value of i such that n < 5**i, the quotient is 0 at that i
>> and forever after).
>>
>> In this case,
>>
>> 100 // 5 + 100 // 25 + 100 // 125 + ... =
>>
>> 20 + 4 + 0 + ... =
>>
>> 24

[Christian Tschabuschnig]
> you should do that with floating-point, so that the quotient never get's
> zero and the "i=1 to infinity" makes sense.

Definitely not.  You didn't do the exercise ;-)  Hint:  n // m is the
number of integers in 1 through n divisible by m.

> This way you (might) get 25

You would in this case, and that would be wrong.  In fp you'd get an
approximation to the exact n * (1./5 + 1./5**2 + ...)  == n/4. (use
the rule for the sum of an infinite geometric series).  For example,
that way you'd compute that 4! == 24 has 4/4 == 1 trailing zero,
instead of the correct 4 // 5 == 0 trailing zeroes, and that 9! ==
362880 has 9/4 == 2.25 trailing zeroes instead of the correct 9 // 5
== 1 trailing zero.

> which is correct; not 24.

Nope again.  Count the number of trailing zeros in 100! more carefully.

From tschaboo at gmx.at  Sat Aug 19 04:13:02 2006
From: tschaboo at gmx.at (Christian Tschabuschnig)
Date: Sat, 19 Aug 2006 04:13:02 +0200
Subject: [Tutor] puzzled again by decimal module
In-Reply-To: <1f7befae0608181851j1f3fdb50w9766e3822aacebeb@mail.gmail.com>
References: <7.0.1.0.2.20060818160936.0678a678@rcblue.com>	
	<44E64C33.90709@gmail.com>	
	<7.0.1.0.2.20060818163419.06794f50@rcblue.com>	
	<44E6522B.1060703@gmx.at>	
	<7.0.1.0.2.20060818171423.06867af0@rcblue.com>	
	<1f7befae0608181807g4ea6c2e7j4fc637a92afb2c0d@mail.gmail.com>	
	<44E669FA.6080106@gmx.at>
	<1f7befae0608181851j1f3fdb50w9766e3822aacebeb@mail.gmail.com>
Message-ID: <44E673AE.2090600@gmx.at>

[Tim Peters]
> You would in this case, and that would be wrong.  In fp you'd get an
> approximation to the exact n * (1./5 + 1./5**2 + ...)  == n/4. (use
> the rule for the sum of an infinite geometric series).  For example,
> that way you'd compute that 4! == 24 has 4/4 == 1 trailing zero,
> instead of the correct 4 // 5 == 0 trailing zeroes, and that 9! ==
> 362880 has 9/4 == 2.25 trailing zeroes instead of the correct 9 // 5
> == 1 trailing zero.

well ... you're right, of course.

> Nope again.  Count the number of trailing zeros in 100! more carefully.

since i'm not able to count further than to 10 past midnight, i used
echo -n "000000000000000000000000" | wc -c
to do the work. and because i'm a confused person i forgot the "-n" :-)

good night,
christian



From tim.peters at gmail.com  Sat Aug 19 04:31:58 2006
From: tim.peters at gmail.com (Tim Peters)
Date: Fri, 18 Aug 2006 22:31:58 -0400
Subject: [Tutor] puzzled again by decimal module
In-Reply-To: <44E673AE.2090600@gmx.at>
References: <7.0.1.0.2.20060818160936.0678a678@rcblue.com>
	<44E64C33.90709@gmail.com>
	<7.0.1.0.2.20060818163419.06794f50@rcblue.com>
	<44E6522B.1060703@gmx.at>
	<7.0.1.0.2.20060818171423.06867af0@rcblue.com>
	<1f7befae0608181807g4ea6c2e7j4fc637a92afb2c0d@mail.gmail.com>
	<44E669FA.6080106@gmx.at>
	<1f7befae0608181851j1f3fdb50w9766e3822aacebeb@mail.gmail.com>
	<44E673AE.2090600@gmx.at>
Message-ID: <1f7befae0608181931r52ee6889u245641ef18411ce2@mail.gmail.com>

[Tim Peters]
>> You would in this case, and that would be wrong.  In fp you'd get an
>> approximation to the exact n * (1./5 + 1./5**2 + ...)  == n/4. (use
>> the rule for the sum of an infinite geometric series).  For example,
>> that way you'd compute that 4! == 24 has 4/4 == 1 trailing zero,
>> instead of the correct 4 // 5 == 0 trailing zeroes, and that 9! ==
>> 362880 has 9/4 == 2.25 trailing zeroes instead of the correct 9 // 5
>> == 1 trailing zero.

[Christian Tschabuschnig]
> well ... you're right, of course.

Of course -- but you should still do the exercise ;-)

>> Nope again.  Count the number of trailing zeros in 100! more carefully.

> since i'm not able to count further than to 10 past midnight, i used
> echo -n "000000000000000000000000" | wc -c
> to do the work. and because i'm a confused person i forgot the "-n" :-)

This is a danger in trying to use tools other than Python -- never
touch them :-)

>>> prod = 1
>>> for i in xrange(2, 101):
...     prod *= i
>>> s = str(prod)
>>> s[-25:]
'4000000000000000000000000'
>>> s.endswith('0' * 25)
False
>>> s.endswith('0' * 24)
True

or the ever-popular :-):

>>> from itertools import groupby
>>> firstkey, firstgroup = groupby(reversed(s)).next()
>>> firstkey
'0'
>>> len(list(firstgroup))
24

From kermit at polaris.net  Sun Aug 20 02:42:07 2006
From: kermit at polaris.net (Kermit Rose)
Date: Sat, 19 Aug 2006 20:42:07 -0400
Subject: [Tutor] All of Kermit's E-Mails
In-Reply-To: <44E52839.1010500@cc.umanitoba.ca>
References: <44E40C99.3060901@gmail.com>	<44E48FE7.000001.03640@YOUR-4105E587B6>
	<Pine.LNX.4.64.0608170859450.4371@hkn.eecs.berkeley.edu>
	<44E4A957.8000703@cc.umanitoba.ca> <44E4B7C2.9070905@polaris.net>
	<44E52839.1010500@cc.umanitoba.ca>
Message-ID: <44E7AFDF.9080701@polaris.net>

Brian van den Broek wrote:
>
> Kermit Rose said unto the world upon 17/08/06 02:38 PM:
>
>> Now if I can only get Thunderbird to quit treating the up and down 
>> arrow as a page up or page down,
>> whenever it's at the top line or bottom line of what it thinks is a 
>> page.
>
>
> Hi Kermit,
>
> I'm glad you've given Thunderbird a try and that you seem to have 
> taken all of the advice in the right spirit.
>

Thank you.   I'm revising the factor34 module now, and will let you all 
know when I'm ready for you to look at it again.


> I'm not sure what you mean by a `page' in the context of email. Could 
> you describe the exhibited and expected behaviour in a bit more detail?
>
> For now, have you tried clicking in the message body and then using 
> the arrows? (That's all I've got.)
>

It's when I click in the message body and use the arrows that 
ThunderBird annoys me.

I use the up arrow to move up one line, and sometimes, it jumps up 
approximately 15 lines instead.

Or I use the down arrow to move down one line, and sometimes it jumps 
down  approximately15 lines instead.


I'm getting around the problem by either using the mouse cursor on the 
scroll bar,

or using the mouse cursor to click on the line where I want the type 
cursor to be.



> You might also what to try the mozilla support forums and knowledge base.
>
> Best,
>
> Brian
>


From josipl2000 at yahoo.com  Sun Aug 20 15:35:08 2006
From: josipl2000 at yahoo.com (josip)
Date: Sun, 20 Aug 2006 06:35:08 -0700 (PDT)
Subject: [Tutor] banners
In-Reply-To: <000501c6c29a$0d52f350$0201a8c0@XPpro>
Message-ID: <20060820133508.78881.qmail@web60825.mail.yahoo.com>

ok i get letter s and j, now i neetd them to be printed together
  
for i in range(3):
    print '*'*5
    if i in range(0,1):
        print '*'
    if i in range(1,2):
        print ' ' * 4 + '*'

        
*****
*
*****
    *
*****
for i in range(4):
    print ' ' * 3 + '*'
    if i in range(3,4):
        print '*  *'
        print '****'

        
      *
      *
        *
*     *
** * *



 		
---------------------------------
How low will we go? Check out Yahoo! Messenger?s low  PC-to-Phone call rates.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060820/d8d75250/attachment.html 

From josipl2000 at yahoo.com  Sun Aug 20 15:46:51 2006
From: josipl2000 at yahoo.com (josip)
Date: Sun, 20 Aug 2006 06:46:51 -0700 (PDT)
Subject: [Tutor] banners
In-Reply-To: <000501c6c29a$0d52f350$0201a8c0@XPpro>
Message-ID: <20060820134651.96543.qmail@web60820.mail.yahoo.com>

i did it.
  for i in range(3):
    print '*' * 5 + '\t  *' 
    if i in range(0,1):
        print '*'+' ' *4 + '\t  *'
    if i in range(1,2):
        print ' ' * 4 + '*  *  *'

  is this code ok?
  someone have better solution? 
  thx!

 			
---------------------------------
Do you Yahoo!?
 Everyone is raving about the  all-new Yahoo! Mail Beta.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060820/647fb070/attachment.htm 

From alan.gauld at btinternet.com  Sun Aug 20 19:52:57 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 20 Aug 2006 18:52:57 +0100
Subject: [Tutor] banners
References: <000501c6c29a$0d52f350$0201a8c0@XPpro>
	<20060820134651.96543.qmail@web60820.mail.yahoo.com>
Message-ID: <eca7hu$hus$1@sea.gmane.org>

"josip" <josipl2000 at yahoo.com> wrote 
>i did it.

Well done!

>  for i in range(3):
>    print '*' * 5 + '\t  *' 
>    if i in range(0,1):

range(0,1) is [0], so you could just do
if i == 0:

>        print '*'+' ' *4 + '\t  *'
>    if i in range(1,2):

similarly range(1,2) is [1] so
if i == 1:

>        print ' ' * 4 + '*  *  *'


>  is this code ok?

Inasmuch as it works, yes its OK
It can be improved as noted above.
There are various ways of tidying it up too, but at this stage 
they are probably too complex for you, we'll leave them for 
later.

There is one much simpler approach too - triple quotes...

But well done for getting it to work.


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


From dyoo at hkn.eecs.berkeley.edu  Sun Aug 20 20:02:13 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 20 Aug 2006 11:02:13 -0700 (PDT)
Subject: [Tutor] banners
In-Reply-To: <20060820134651.96543.qmail@web60820.mail.yahoo.com>
References: <20060820134651.96543.qmail@web60820.mail.yahoo.com>
Message-ID: <Pine.LNX.4.64.0608201053220.11538@hkn.eecs.berkeley.edu>

> i did it.

Cool; I'm glad to see that you could do it.


[code cut]

Yes, it's mostly an exercise for you to get comfortable using multiple 
statements.  Personally, I think your instructor should have made the 
first assignment something dealing with expressions rather than print 
statements, but oh well.


As a meta issue: in the future, please take care not to post homework 
solutions like this on the python-tutor mailing list.  The list is 
archived for convenience,

     http://mail.python.org/pipermail/tutor/

and Google is very effective in finding information.


Good luck to you.

From cappy2112 at gmail.com  Mon Aug 21 01:54:42 2006
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Sun, 20 Aug 2006 16:54:42 -0700
Subject: [Tutor] Making a better main() : Critique request
Message-ID: <8249c4ac0608201654l40b45915w5b730c87bab697d5@mail.gmail.com>

Some time ago, I had read an article on Guido's blog (I think) about ways to
improve the main() function
in a Python script. There were many replies, and I thought I would try to
implement some of these ideas.


I had found that in every python program I wrote I would

1. check the number of arguments as well as checking that each argument was
valid.
2. Provide an option for the user to display how long the program took to
run, for those programs which
    processed a lot of files.
3  If any input files were used, I would also check to make sure they
existed.
    Recently, I've implemented a browser dialogue from Jimmy Retzlaff's
EasyDialogs to make it easy to locate
    files outside of the current directory.
4. If the argument validation failed, a Usage() function would be called to
show all possible arguments
5. Provide a "help" option  to display all the possible arguments.


I could see that I was writing enough lines of code that main() was getting
cluttered, and not easy
to see what was happening at a glance. Sure, I could move all of this
outside of main(), but some function had to
initiate all of the processing. So, I've decided to put all of this
processing into a class.

I had thought about putting this class in a separate file, so the file
containing main() would only have a few imports, one line to instantiate the
class to validate the cmd line args, and one function call to actually
"start" the meat of the program, if all input args were valid.

I didn't like the idea of having to start with 2 files for every program. So
now the class definition for the input processing is in the main file, and
this file is now full of code, but at least main() is short & sweet.

Since I'm just getting back into using Python again, I would appreciate some
constructive comments on this processing, and if this version of "a better
main()" is really better or not.


So Now I'm trying to use more exception handling in the validating of the
input arguments, and have defined a few of my own exceptionclasses.

However, I'm getting the cart before the horse, and can't see the forest
through the trees.

I don't like the idea of defining classes within classes, but I'm havign a
problem geting the ProgramStartup class to
see the ArgumentError exception class.


Am Ion the right track to makign a better main by moving all the argument
validation to a class, or should I levae it to discrete functions in the
main file?

thanks

# system imports
from os import getcwd
import string
import sys
import types
import time
import getopt
from EasyDialogs import AskFileForOpen
from os.path import exists
from exceptions import Exception
# system imports

# user-defined imports
import tcpy
from tcpy import pause
from tcpy import cls


# user-defined imports

#/////////////////////////////////////////////////////////
# USER-DEFINED EXCEPTIONS

class UserExceptions(Exception):
    def __init__(self, args=None):
        self.args = args

class ArgumentError(UserExceptions):
    def __init__(self):
        #UserExceptions.__init__(self, args)
        #self.args = args
        pass


class ProgramExitError(UserExceptions):
    def __init__(self, args):
        UserExceptions.__init__(self, args)
        self.args = args


#/////////////////////////////////////////////////////////
# CLASS DEFINITIONS
#/////////////////////////////////////////////////////////

class ProgramStartup(object):
    "this class will handle all the details of checking/validating the
program arguments"

    def __init__(self, ProgramArgs):
        self.MinArgs = 1
        self.MaxArgs = 2 #input filename
        self.ShowTimer = False
        self.StartTime = 0
        self.EndTime = 0
        self.InputFilename = ""

        self.ProgramName = ""
        self.ProgramVersion = "0.1"
        self.BAD_ARG = True

        self.ArgsDict ={'-t':"Show program execution time",
                        '-v':"Show program version number",
                        '-b':"Browse for input file",
                        '-f <filename>':"File to be processed",
                        '-h':"Show this help screen"
        }

        self.ValidArgs ='tvbf:'


        try:
            self.ValidateArgs(ProgramArgs)
        except getopt.GetoptError, ArgumentError:
            self.Usage()

    def Usage(self):

        print"\nSyntax is: ",
        print"%s " % ProgramName,
        for key in self.ArgsDict.iterkeys():
            print"%s " % key,

        print"\n\nWhere"
        for key, item in self.ArgsDict.iteritems():
            print"\n%s=%s" %(key, item)
        print
        sys.exit()

    def ShowExecTime(self):

        if self.ShowTimer:
            print"\nTotal time = %6.2f seconds" % (
self.EndTime-self.StartTime)

        return None

    def ShowTitle(self):

        print"\n\n%s Version %s \n\n" %(self.ProgramName,
self.ProgramVersion)
        return None

    def ValidateArgs(self, args):
        global AskFileForOpen, getcwd, ArgumentError

        ArgValidationStatus = 0
        self.InputFilename = None

        ProgramDir = getcwd()

        if len(args) < self.MinArgs:
            raise ArgumentError

        try:
            (Opts, Args) = getopt.getopt(args, self.ValidArgs )
            for opt, arg, in Opts:
                if opt == '-v' :
                    print"\n%s ver %s " % (self.ProgramName,
self.ProgramVersion)
                    sys.exit()
                elif opt == '-t' :
                    ShowTimer = True
                elif opt == '-f':
                    if exists(Filename) != True:
                        print"\nFile %s does not exist, or could not be
opened for reading" % Filearg
                        pause()
                elif opt == '-b':
                    self.InputFilename =
AskFileForOpen(defaultLocation=ProgramDir, message="Select Phonebook to be
processed", windowTitle="File Open")
        except getopt.GetoptError:
            raise



    def StartProgram(self):

        self.ShowTitle()

        if self.InputFilename:
            self.StartTime = time.time()

           # CALL THE ACTUAL MEAT OF THE PROGRAM HERE

            self.EndTime=time.time()
            self.ShowExecTime()
        else:
            print"\nNo input filename was given.\n"

        return None


#/////////////////////////////////////////////////////////

def main(args):

    #try:
    program=ProgramStartup(args[1:])
    #except ArgumentError: # user-defined exception
    #raise # we need to return to main here

    program.StartProgram() # pass all arguments after the word Python

    return None

#/////////////////////////////////////////////////////////
# run the program
if __name__ == '__main__':
    cls()
    main(sys.argv)
    print"\n\n%sThe program has ended\n" % (' ' * 40)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060820/06274aad/attachment-0001.html 

From john at fouhy.net  Mon Aug 21 03:04:36 2006
From: john at fouhy.net (John Fouhy)
Date: Mon, 21 Aug 2006 13:04:36 +1200
Subject: [Tutor] Making a better main() : Critique request
In-Reply-To: <8249c4ac0608201654l40b45915w5b730c87bab697d5@mail.gmail.com>
References: <8249c4ac0608201654l40b45915w5b730c87bab697d5@mail.gmail.com>
Message-ID: <5e58f2e40608201804u17b8bdbcv91b6ecd63d298ff9@mail.gmail.com>

On 21/08/06, Tony Cappellini <cappy2112 at gmail.com> wrote:
> 1. check the number of arguments as well as checking that each argument was
> valid.
> 4. If the argument validation failed, a Usage() function would be called to
> show all possible arguments
> 5. Provide a "help" option  to display all the possible arguments.

Hi,

I haven't read your whole post, I'm afraid, but I did see that you
were using getopt.

If you use optparse instead, it will take care of all this for you.

Basically, you create a parser, and tell it what arguments you are
expecting, including:
 - short name
 - long name
 - help text
 - argument type (int / string / float / bool)
 - default value

If you give your script the -h or --help option, optparse will
generate usage text (which you can customise).  Likewise, if you give
it an unknown argument, or an argument of the wrong type.

I've only just started playing with it myself, but it looks pretty nifty :-)

-- 
John.

From pythontut at pusspaws.net  Mon Aug 21 11:59:01 2006
From: pythontut at pusspaws.net (dave s)
Date: Mon, 21 Aug 2006 09:59:01 +0000
Subject: [Tutor] A list in list problem
Message-ID: <200608210959.01834.pythontut@pusspaws.net>


Help :)

I have been playing with this for several hours & am totally stuck !

I am happy with the following ...

>>> a=[1,2,3]
>>> b=[5,6,7]
>>> a
[1, 2, 3]
>>> b
[5, 6, 7]
>>> g=[]
>>> g
[]
>>> g.append(a)
>>> g
[[1, 2, 3]]
>>> g.append(b)
>>> g
[[1, 2, 3], [5, 6, 7]]
>>>

So when I needed to make a list of a list in the following code I thought no 
problem ...


   def CSV_Lines(self, csv, from_, to):
        """Returns a list of cleaned up lines from csv 'from_' line 
number  'to' line number"""
        
        clean_line = clean_csv = []
        for string in range(from_, to):
            split_string = csv[string].split(',')
            split_string = split_string[1:-1]  # Strip the LHS column + 
the /n'
            if split_string[0] == '' : continue  # Skip empty lines
            print '##########################'
            print 'split_string ', split_string
            for string in split_string:
                if len(string) > 0: clean_line.append(string[1:-1])
            print 'clean_line ',clean_line
            clean_csv.append(clean_line)
            print 'clean_csv ',clean_csv
            clean_line = []

But I get clean_csv trouble  ...

ubuntu at ubuntu:~/python_develop/unison/PxQxAudit/main$ ./crosscheck.py
##########################
split_string  ['"temp1"', '"wow a variable"', '', '', '']
clean_line  ['temp1', 'wow a variable']
clean_csv  ['temp1', 'wow a variable', [...]]
##########################
split_string  ['"temp2"', '', '', '', '']
clean_line  ['temp2']
clean_csv  ['temp1', 'wow a variable', [...], ['temp2']]
ubuntu at ubuntu:~/python_develop/unison/PxQxAudit/main$

ie clean_csv ends up as ['temp1', 'wow a variable', [...], ['temp2']] instead 
of [[temp1, wow a variable], [temp2]]

Please help

Dave















From pythontut at pusspaws.net  Mon Aug 21 13:44:54 2006
From: pythontut at pusspaws.net (Dave S)
Date: Mon, 21 Aug 2006 12:44:54 +0100
Subject: [Tutor] A list in list problem
In-Reply-To: <200608210959.01834.pythontut@pusspaws.net>
References: <200608210959.01834.pythontut@pusspaws.net>
Message-ID: <200608211244.54800.pythontut@pusspaws.net>

On Monday 21 August 2006 10:59, dave s wrote:

Several hours +1 Sometimes it is usefull spelling out my problem in an email - 
seems to clarify it - maybe when I get to the 'im stuck' I should send an 
email to myself :)


clean_csv.append(clean_line) ... should by
clean_csv.append(clean_line[:])

But the real showstopper was 

clean_line = clean_csv = []

and then 
if len(string) > 0: clean_line.append(string[1:-1])
changes clean_csv as well, I guess because its an appens not a reassignment

Sorry for bothering you guys

Dave













> Help :)
>
> I have been playing with this for several hours & am totally stuck !
>
> I am happy with the following ...
>
> >>> a=[1,2,3]
> >>> b=[5,6,7]
> >>> a
>
> [1, 2, 3]
>
> >>> b
>
> [5, 6, 7]
>
> >>> g=[]
> >>> g
>
> []
>
> >>> g.append(a)
> >>> g
>
> [[1, 2, 3]]
>
> >>> g.append(b)
> >>> g
>
> [[1, 2, 3], [5, 6, 7]]
>
>
> So when I needed to make a list of a list in the following code I thought
> no problem ...
>
>
>    def CSV_Lines(self, csv, from_, to):
>         """Returns a list of cleaned up lines from csv 'from_' line
> number  'to' line number"""
>
>         clean_line = clean_csv = []
>         for string in range(from_, to):
>             split_string = csv[string].split(',')
>             split_string = split_string[1:-1]  # Strip the LHS column +
> the /n'
>             if split_string[0] == '' : continue  # Skip empty lines
>             print '##########################'
>             print 'split_string ', split_string
>             for string in split_string:
>                 if len(string) > 0: clean_line.append(string[1:-1])
>             print 'clean_line ',clean_line
>             clean_csv.append(clean_line)
>             print 'clean_csv ',clean_csv
>             clean_line = []
>
> But I get clean_csv trouble  ...
>
> ubuntu at ubuntu:~/python_develop/unison/PxQxAudit/main$ ./crosscheck.py
> ##########################
> split_string  ['"temp1"', '"wow a variable"', '', '', '']
> clean_line  ['temp1', 'wow a variable']
> clean_csv  ['temp1', 'wow a variable', [...]]
> ##########################
> split_string  ['"temp2"', '', '', '', '']
> clean_line  ['temp2']
> clean_csv  ['temp1', 'wow a variable', [...], ['temp2']]
> ubuntu at ubuntu:~/python_develop/unison/PxQxAudit/main$
>
> ie clean_csv ends up as ['temp1', 'wow a variable', [...], ['temp2']]
> instead of [[temp1, wow a variable], [temp2]]
>
> Please help
>
> Dave
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From alan.gauld at freenet.co.uk  Mon Aug 21 14:40:55 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 21 Aug 2006 13:40:55 +0100
Subject: [Tutor] A list in list problem
References: <200608210959.01834.pythontut@pusspaws.net>
Message-ID: <000901c6c51f$0c85ef40$0201a8c0@XPpro>

> So when I needed to make a list of a list in the following code I 
> thought no
> problem ...
>
>
>   def CSV_Lines(self, csv, from_, to):
>        """Returns a list of cleaned up lines from csv 'from_' line
> number  'to' line number"""
>
>        clean_line = clean_csv = []

So clean_line is a reference to clean_csv which is a reference
to a list. That is, both variables point to the same list?
I don't think thats what you wanted... Remember that Python
variables are references to objects, in this case they both
reference the same list object.

>            print 'clean_line ',clean_line
>            clean_csv.append(clean_line)

So the list has just appended itself to itself, that why python
shows the slightly wierd [...] because its a recursively defined list.

>            print 'clean_csv ',clean_csv
>            clean_line = []

And now you make clean_line point to a new empty list
So next time round the vcontents ofg the new clean line
will be appended to the old one.

Go back and initialise your lists as two separate lists and
you will get what you expect.

> clean_line  ['temp1', 'wow a variable']
> clean_csv  ['temp1', 'wow a variable', [...]]

The original with itself tagged on.

> clean_line  ['temp2']
> clean_csv  ['temp1', 'wow a variable', [...], ['temp2']]

The above list with the new list added

Just as expected :-)

HTH,

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


From janos.juhasz at VELUX.com  Mon Aug 21 14:58:50 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Mon, 21 Aug 2006 14:58:50 +0200
Subject: [Tutor] A list in list problem
In-Reply-To: <mailman.35.1156154423.22049.tutor@python.org>
Message-ID: <OF037C81FE.62A8E2CD-ONC12571D1.004344D0-C12571D1.00474DFC@velux.com>

Hi Dave,

> From: dave s <pythontut at pusspaws.net>
> Subject: [Tutor] A list in list problem
> To: python tutor <tutor at python.org>
> Message-ID: <200608210959.01834.pythontut at pusspaws.net>
> Content-Type: text/plain;  charset="us-ascii"

> def CSV_Lines(self, csv, from_, to):
> """Returns a list of cleaned up lines from csv 'from_' line
> number  'to' line number"""

>        clean_line = clean_csv = []
>        for string in range(from_, to):
>               split_string = csv[string].split(',')
>               split_string = split_string[1:-1]  # Strip the LHS column 
+ the /n'
>               if split_string[0] == '' : continue  # Skip empty lines
>               print '##########################'
>               print 'split_string ', split_string
>               for string in split_string:
>                       if len(string) > 0: 
clean_line.append(string[1:-1])
>               print 'clean_line ',clean_line
>               clean_csv.append(clean_line)
>               print 'clean_csv ',clean_csv
>               clean_line = []
> 
> But I get clean_csv trouble  ...

> ubuntu at ubuntu:~/python_develop/unison/PxQxAudit/main$ ./crosscheck.py
> ##########################
> split_string  ['"temp1"', '"wow a variable"', '', '', '']
> clean_line  ['temp1', 'wow a variable']
> clean_csv  ['temp1', 'wow a variable', [...]]
> ##########################
> split_string  ['"temp2"', '', '', '', '']
> clean_line  ['temp2']
> clean_csv  ['temp1', 'wow a variable', [...], ['temp2']]
> ubuntu at ubuntu:~/python_develop/unison/PxQxAudit/main$

> ie clean_csv ends up as ['temp1', 'wow a variable', [...], ['temp2']] 
instead
> of [[temp1, wow a variable], [temp2]]


You have used string as variable name two times, once as an integer and 
once as a field in the line.
It should be avoided.

I like list comprehension in this case.

def CSV_Lines2(csv, from_, to):
    csv = csv[from_ : to]                                       # We are 
interested just here
    csv = [line.split(',') for line in csv]     # Make a 2D array from the 
list
    return [LineItems[1:-1] for LineItems in csv if len(LineItems) > 2] 
                    # filter out first and last columns, and lines with 
too less items



csv = """Header1
Header2
temp1,12,20,1
temp2,22,22,2
temp3,33,44,3
temp4,34,64,4
Footer1
Footer2"""

csv = csv.split('\n')
print CSV_Lines2(csv, 2, 6)
>>>[['12', '20'], ['22', '22'], ['33', '44'], ['34', '64']]


Yours sincerely, 
______________________________
Janos Juhasz 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060821/bf941136/attachment.htm 

From zslevi at sch.bme.hu  Mon Aug 21 16:04:19 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Mon, 21 Aug 2006 16:04:19 +0200
Subject: [Tutor] self-modification
Message-ID: <44E9BD63.2040605@sch.bme.hu>

I'm a newbie to Python. I wanted to write a graphical interface which 
would show the built-in documentation (I mean dir() and __doc__ ) of 
Python. The code shows how far I got before realizing that I had to use 
some self-modification feature (converting a string to a function or to 
an object; i'm not sure you would call it self-modification in an 
interpreted language).

I was googling around, and searching in the maillist archives and found 
this:
http://mail.python.org/pipermail/tutor/2004-October/032388.html
Unanswered for two years. Not too promising :)

P.S.: I'm new to this mailing list, so I don't know whether it is 
allowed to send code as attachment. (I didn't found anything about your 
policy in the subscription site. )  If not, I'm sorry.

From zslevi at sch.bme.hu  Mon Aug 21 16:06:52 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Mon, 21 Aug 2006 16:06:52 +0200
Subject: [Tutor] [Fwd: self-modification]
Message-ID: <44E9BDFC.80907@sch.bme.hu>


I forgot the most important thing: the attachment.
-------- Original Message --------
Subject: 	self-modification
Date: 	Mon, 21 Aug 2006 16:04:19 +0200
From: 	Zsiros Levente <zslevi at sch.bme.hu>
To: 	python tutor <tutor at python.org>



I'm a newbie to Python. I wanted to write a graphical interface which 
would show the built-in documentation (I mean dir() and __doc__ ) of 
Python. The code shows how far I got before realizing that I had to use 
some self-modification feature (converting a string to a function or to 
an object; i'm not sure you would call it self-modification in an 
interpreted language).

I was googling around, and searching in the maillist archives and found 
this:
http://mail.python.org/pipermail/tutor/2004-October/032388.html
Unanswered for two years. Not too promising :)

P.S.: I'm new to this mailing list, so I don't know whether it is 
allowed to send code as attachment. (I didn't found anything about your 
policy in the subscription site. )  If not, I'm sorry.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: b1-motion.py
Type: text/x-python
Size: 1005 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060821/cc450952/attachment.py 

From kent37 at tds.net  Mon Aug 21 16:22:52 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 21 Aug 2006 10:22:52 -0400
Subject: [Tutor] self-modification
In-Reply-To: <44E9BD63.2040605@sch.bme.hu>
References: <44E9BD63.2040605@sch.bme.hu>
Message-ID: <44E9C1BC.30906@tds.net>

Zsiros Levente wrote:
> I'm a newbie to Python. I wanted to write a graphical interface which 
> would show the built-in documentation (I mean dir() and __doc__ ) of 
> Python. The code shows how far I got before realizing that I had to use 
> some self-modification feature (converting a string to a function or to 
> an object; i'm not sure you would call it self-modification in an 
> interpreted language).
>   
You can convert a string to a function or object using exec and eval but 
often it's better to use Python's introspection capabilities such as 
getattr() and setattr(). For example if you want to convert a string 
received from dir() to the value of the corresponding attribute, use 
getattr(). Can you say more about why you need to convert a string to an 
object?
> I was googling around, and searching in the maillist archives and found 
> this:
> http://mail.python.org/pipermail/tutor/2004-October/032388.html
> Unanswered for two years. Not too promising :)
>   
That post is pretty vague. I'm surprised that there was no followup 
asking for clarification but not surprised that there is no answer.

I don't know of a tutorial on exec and eval but you can find docs here:
http://docs.python.org/ref/exec.html
http://docs.python.org/lib/built-in-funcs.html#l2h-23
> P.S.: I'm new to this mailing list, so I don't know whether it is 
> allowed to send code as attachment. (I didn't found anything about your 
> policy in the subscription site. )  If not, I'm sorry.

Short code snippets such as yours can be sent as an attachment or inline 
in the email. Personally I prefer inline as it makes it easy to reply 
with comments interspersed with the code.

Kent


From zslevi at sch.bme.hu  Mon Aug 21 15:36:32 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Mon, 21 Aug 2006 15:36:32 +0200
Subject: [Tutor] tkinter events: <B1-Motion>
Message-ID: <44E9B6E0.3060305@sch.bme.hu>

 

/#!/usr/bin/python/

/# In this program I wanted to write the event <B1-Motion> on my own, combining <Button-1>, <Motion> and <ButtonRelease-1>,
# but unfortunetly it doesn't work. No syntax errors.

/ from Tkinter import *


*def* handler(event):
	*if* buttonpressed == 1 :
		/#if the mousebutton is pressed and moved, circles should appear, but they do not/
		can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, fill="orange")
	lab.config(text='buttonpressed=' + str(buttonpressed) )

*def* press(event):
	buttonpressed=1
	lab2.config(text=buttonpressed)
	
*def* release(event):
	buttonpressed=0
	lab2.config(text=buttonpressed)	


r=5
/#global buttonpressed/
buttonpressed=0

root = Tk()
root.geometry('600x500+200+200')

/# both labels are used to check the status of the variable buttonpressed/
lab = Label(root, text='cucc')
lab2 = Label(root, text='cucc2')

can = Canvas(root, width='500', height='400', bg='white')
can.bind("<Motion>",handler)
can.bind("<Button-1>",press)
can.bind("<ButtonRelease-1>",release)

lab.pack()
lab2.pack()
can.pack()

root.mainloop()

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060821/e5257b0c/attachment-0001.html 

From alan.gauld at freenet.co.uk  Mon Aug 21 17:33:29 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 21 Aug 2006 16:33:29 +0100
Subject: [Tutor] self-modification
References: <44E9BD63.2040605@sch.bme.hu>
Message-ID: <002001c6c537$2742f310$0201a8c0@XPpro>

> I'm a newbie to Python. I wanted to write a graphical interface 
> which would show the built-in documentation (I mean dir() and 
> __doc__ ) of Python. The code shows how far I got before realizing 
> that I had to use some self-modification feature (converting a 
> string to a function or to an object; i'm not sure you would call it 
> self-modification in an interpreted language).

Usually this (string to function/object) is best done in Python
by either using a dictionary or the getattr/setattr methods.

> I was googling around, and searching in the maillist archives and 
> found this:
> http://mail.python.org/pipermail/tutor/2004-October/032388.html
> Unanswered for two years. Not too promising :)

It wasn't answered because its a bit too open ended.
It asks for someone to give a "tutorial" on self modification
aimed at other language users... Thats a pretty broad brief.

> P.S.: I'm new to this mailing list, so I don't know whether it is 
> allowed to send code as attachment. (I didn't found anything about 
> your policy in the subscription site. )  If not, I'm sorry.

Short code snippets (<100 lines?) are OK, longer than
that and we prefer a URL link.

Can you give us some more specific examples of what you
are trying to do that requires "self modification"? For a help
browser I'd expect getattr to be sufficient in most cases.

HTH,

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


From zslevi at sch.bme.hu  Mon Aug 21 17:38:11 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Mon, 21 Aug 2006 17:38:11 +0200
Subject: [Tutor] [Fwd: [Fwd: self-modification]]
Message-ID: <44E9D363.7090108@sch.bme.hu>



Sorry, the source was for my tkinter question. I'm a bit disorganized 
today.

The problematic part is the 11. line, where I have to convert the item 
selected from the list to an object, or something like that. At the 
moment it only applies to a string object, but I want to call the 
function for the object, represented by the string. (If you run it, it 
will become more obvious what I mean.)


-------- Original Message --------
Subject: 	[Fwd: self-modification]
Date: 	Mon, 21 Aug 2006 16:06:52 +0200
From: 	Zsiros Levente <zslevi at sch.bme.hu>
To: 	python tutor <tutor at python.org>



I forgot the most important thing: the attachment.
-------- Original Message --------
Subject: 	self-modification
Date: 	Mon, 21 Aug 2006 16:04:19 +0200
From: 	Zsiros Levente <zslevi at sch.bme.hu>
To: 	python tutor <tutor at python.org>



I'm a newbie to Python. I wanted to write a graphical interface which 
would show the built-in documentation (I mean dir() and __doc__ ) of 
Python. The code shows how far I got before realizing that I had to use 
some self-modification feature (converting a string to a function or to 
an object; i'm not sure you would call it self-modification in an 
interpreted language).

I was googling around, and searching in the maillist archives and found 
this:
http://mail.python.org/pipermail/tutor/2004-October/032388.html
Unanswered for two years. Not too promising :)

P.S.: I'm new to this mailing list, so I don't know whether it is 
allowed to send code as attachment. (I didn't found anything about your 
policy in the subscription site. )  If not, I'm sorry.




-------------- next part --------------
A non-text attachment was scrubbed...
Name: self_doc.py
Type: text/x-python
Size: 678 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060821/771aa619/attachment.py 

From alan.gauld at freenet.co.uk  Mon Aug 21 17:47:31 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 21 Aug 2006 16:47:31 +0100
Subject: [Tutor] [Fwd: self-modification]
References: <44E9BDFC.80907@sch.bme.hu>
Message-ID: <002a01c6c539$2304c240$0201a8c0@XPpro>

> I forgot the most important thing: the attachment.

OK, Here is my annotated version. not sure if it
will solve your problem though...

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

#!/usr/bin/python

# In this program I wanted to write the event <B1-Motion>
> on my own, combining <Button-1>, <Motion> and <ButtonRelease-1>

from Tkinter import *

def handler(event):
  if buttonpressed == 1 :
     #if the mousebutton is pressed and moved, circles should appear
    can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, 
fill="orange")
  lab.config(text='buttonpressed=' + str(buttonpressed) )

[AG] First point, using global variables like this is considered
[AG] bad practice, better to pass the canvas and label as a
[AG] parameter - or better still make the GUI a class and refer
[AG] to the attributes.within the methods

[AG] Also you are using buttonpressed as a boolean flag,
[AG]  so why not use boolean values - True/False?
[AG] Then your test just becomes

[AG] if buttonpressed: ...


def press(event):
     buttonpressed=1
     lab2.config(text=buttonpressed)

[AG]  use True here instead of 1 and you will also need to
[AG] declare it as global, otherwise you are simply creating
[AG] a local variable inside the function which then gets
[AG] thrown away - that might be why the behaviour isn't
[AG] as expected, global buttonpressed is always zero!

[AG] pass a string to the ttext attribute - I assume you want to
[AG] display the string 'button pressed', rather
[AG] than the rather cryptic number 1?

def release(event):
   buttonpressed=0

buttonpressed = False here..

   lab2.config(text=buttonpressed)

[AG] As above.

r=5
#global buttonpressed
buttonpressed=0

root = Tk()
root.geometry('600x500+200+200')

[AG] Using a fixed geometry rather undermines
[AG] the operation of pack(). Its usually better to let
[AG] the Geometry Manager manage the geometry ;-)
[AG]  If the user resizes the window it will all go awry anyhow!

# both labels are used to check the status of the variable 
buttonpressed
lab = Label(root, text='cucc')
lab2 = Label(root, text='cucc2')

[AG] Not sure why you have two, and why you
[AG] change the values from cucc to a number later.

can = Canvas(root, width='500', height='400', bg='white')
can.bind("<Motion>",handler)
can.bind("<Button-1>",press)
can.bind("<ButtonRelease-1>",release)

lab.pack()
lab2.pack()
can.pack()

root.mainloop()

HTH,

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


From kent37 at tds.net  Mon Aug 21 17:53:00 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 21 Aug 2006 11:53:00 -0400
Subject: [Tutor] [Fwd: [Fwd: self-modification]]
In-Reply-To: <44E9D363.7090108@sch.bme.hu>
References: <44E9D363.7090108@sch.bme.hu>
Message-ID: <44E9D6DC.7050401@tds.net>

Zsiros Levente wrote:
> Sorry, the source was for my tkinter question. I'm a bit disorganized 
> today.
>
> The problematic part is the 11. line, where I have to convert the item 
> selected from the list to an object, or something like that. At the 
> moment it only applies to a string object, but I want to call the 
> function for the object, represented by the string. (If you run it, it 
> will become more obvious what I mean.)
>   
I think you want
  name = listbox.get(listbox.curselection()[0])
  obj = getattr(Tkinter, name)
  description.config( text=obj.__doc__ )

A couple more tips:
- Don't use 'list' as the name of a variable, that name is already used 
as the type of the built-in list.
- Please respond to the existing thread rather than starting a new 
thread for each email, it makes it easier to follow the discussion.

Kent
>
> -------- Original Message --------
> Subject: 	[Fwd: self-modification]
> Date: 	Mon, 21 Aug 2006 16:06:52 +0200
> From: 	Zsiros Levente <zslevi at sch.bme.hu>
> To: 	python tutor <tutor at python.org>
>
>
>
> I forgot the most important thing: the attachment.
> -------- Original Message --------
> Subject: 	self-modification
> Date: 	Mon, 21 Aug 2006 16:04:19 +0200
> From: 	Zsiros Levente <zslevi at sch.bme.hu>
> To: 	python tutor <tutor at python.org>
>
>
>
> I'm a newbie to Python. I wanted to write a graphical interface which 
> would show the built-in documentation (I mean dir() and __doc__ ) of 
> Python. The code shows how far I got before realizing that I had to use 
> some self-modification feature (converting a string to a function or to 
> an object; i'm not sure you would call it self-modification in an 
> interpreted language).
>
> I was googling around, and searching in the maillist archives and found 
> this:
> http://mail.python.org/pipermail/tutor/2004-October/032388.html
> Unanswered for two years. Not too promising :)
>
> P.S.: I'm new to this mailing list, so I don't know whether it is 
> allowed to send code as attachment. (I didn't found anything about your 
> policy in the subscription site. )  If not, I'm sorry.
>
>
>
>
>   
> ------------------------------------------------------------------------
>
> #!/usr/bin/python
>
> from Tkinter import *
> from os import *
> from string import *
> import os
> import string
> import Tkinter
>
> def list_click(event):
> 	description.config( text=listbox.get(listbox.curselection()[0]).__doc__ )
>
> list = dir(Tkinter)
> #print list
>
> root=Tk()
> root.geometry('+100+100')
>
> l_frame = Frame(root)
> r_frame = Frame(root)
>
> label = Label(l_frame)
> label.config(text='filename')
>
> description = Label(r_frame)
>
> listbox = Listbox(l_frame)
> listbox.bind('<Double-Button-1>',list_click)
>
> for item in list :
> 	listbox.insert(0,item)
>
>
> l_frame.pack(side=LEFT,fill=BOTH)
> label.pack()
> listbox.pack(expand=1,fill=BOTH)
>
> r_frame.pack(side=RIGHT)
> description.pack()
>
> root.mainloop()
>
>   
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



From pythontut at pusspaws.net  Mon Aug 21 18:19:35 2006
From: pythontut at pusspaws.net (Dave S)
Date: Mon, 21 Aug 2006 17:19:35 +0100
Subject: [Tutor] A list in list problem
In-Reply-To: <000901c6c51f$0c85ef40$0201a8c0@XPpro>
References: <200608210959.01834.pythontut@pusspaws.net>
	<000901c6c51f$0c85ef40$0201a8c0@XPpro>
Message-ID: <200608211719.35962.pythontut@pusspaws.net>

On Monday 21 August 2006 13:40, Alan Gauld wrote:
> > So when I needed to make a list of a list in the following code I
> > thought no
> > problem ...
> >
> >
> >   def CSV_Lines(self, csv, from_, to):
> >        """Returns a list of cleaned up lines from csv 'from_' line
> > number  'to' line number"""
> >
> >        clean_line = clean_csv = []
>
> So clean_line is a reference to clean_csv which is a reference
> to a list. That is, both variables point to the same list?
> I don't think thats what you wanted... Remember that Python
> variables are references to objects, in this case they both
> reference the same list object.

In the past I have assigned multiple variables by

var1 = var2 = 0

when one of the variables is assigned a different value, another object is 
created and var1 & var2 are separate. Without thinking I tried to do the same 
with the two lists.

>>>
>>> a=b=[]
>>> a
[]
>>> b
[]
>>> a=[1,2,3]
>>> a
[1, 2, 3]
>>> b
[]
>>>

Tinkering some more I think it is the append that did it.
>>>
>>> a=b=[]
>>> a
[]
>>> b
[]
>>> a.append([1,2,3])
>>> a
[[1, 2, 3]]
>>> b
[[1, 2, 3]]
>>>

It appended to the common object and did not create a separate one ?

I guess var1 = var2 = 0 is generally bad programming style ?. I keep trying to 
get my code more compact using list comprehension etc - in this case compact 
got me into trouble.

I have tried looking at some open source projects eg kdissert,sbackup to get 
into good codeing habits but they are a bit above me. So I am learning by 
trying. (1 x GUI app written, a more advanced one on the way)

Thanks for all your help

Dave

PS This is probably an impossible question but I always struggle to find names 
for variables - any hints ?

>
> >            print 'clean_line ',clean_line
> >            clean_csv.append(clean_line)
>
> So the list has just appended itself to itself, that why python
> shows the slightly wierd [...] because its a recursively defined list.

That sounds bad - and sure confused me !

>
> >            print 'clean_csv ',clean_csv
> >            clean_line = []
>
> And now you make clean_line point to a new empty list
> So next time round the vcontents ofg the new clean line
> will be appended to the old one.
>
> Go back and initialise your lists as two separate lists and
> you will get what you expect.
>
> > clean_line  ['temp1', 'wow a variable']
> > clean_csv  ['temp1', 'wow a variable', [...]]
>
> The original with itself tagged on.
>
> > clean_line  ['temp2']
> > clean_csv  ['temp1', 'wow a variable', [...], ['temp2']]
>
> The above list with the new list added
>
> Just as expected :-)
>
> HTH,
>
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld

From pythontut at pusspaws.net  Mon Aug 21 18:28:34 2006
From: pythontut at pusspaws.net (Dave S)
Date: Mon, 21 Aug 2006 17:28:34 +0100
Subject: [Tutor] A list in list problem
In-Reply-To: <OF037C81FE.62A8E2CD-ONC12571D1.004344D0-C12571D1.00474DFC@velux.com>
References: <OF037C81FE.62A8E2CD-ONC12571D1.004344D0-C12571D1.00474DFC@velux.com>
Message-ID: <200608211728.34390.pythontut@pusspaws.net>

On Monday 21 August 2006 13:58, J?nos Juh?sz wrote:
> Hi Dave,
>
> > From: dave s <pythontut at pusspaws.net>
> > Subject: [Tutor] A list in list problem
> > To: python tutor <tutor at python.org>
> > Message-ID: <200608210959.01834.pythontut at pusspaws.net>
> > Content-Type: text/plain;  charset="us-ascii"
> >
> > def CSV_Lines(self, csv, from_, to):
> > """Returns a list of cleaned up lines from csv 'from_' line
> > number  'to' line number"""
> >
> >        clean_line = clean_csv = []
> >        for string in range(from_, to):
> >               split_string = csv[string].split(',')
> >               split_string = split_string[1:-1]  # Strip the LHS column
>
> + the /n'

>
> >               if split_string[0] == '' : continue  # Skip empty lines
> >               print '##########################'
> >               print 'split_string ', split_string
> >               for string in split_string:
> >                       if len(string) > 0:
>
> clean_line.append(string[1:-1])
>
> >               print 'clean_line ',clean_line
> >               clean_csv.append(clean_line)
> >               print 'clean_csv ',clean_csv
> >               clean_line = []
> >
> > But I get clean_csv trouble  ...
> >
> > ubuntu at ubuntu:~/python_develop/unison/PxQxAudit/main$ ./crosscheck.py
> > ##########################
> > split_string  ['"temp1"', '"wow a variable"', '', '', '']
> > clean_line  ['temp1', 'wow a variable']
> > clean_csv  ['temp1', 'wow a variable', [...]]
> > ##########################
> > split_string  ['"temp2"', '', '', '', '']
> > clean_line  ['temp2']
> > clean_csv  ['temp1', 'wow a variable', [...], ['temp2']]
> > ubuntu at ubuntu:~/python_develop/unison/PxQxAudit/main$
> >
> > ie clean_csv ends up as ['temp1', 'wow a variable', [...], ['temp2']]
>
> instead
>
> > of [[temp1, wow a variable], [temp2]]
>
> You have used string as variable name two times, once as an integer and
> once as a field in the line.
> It should be avoided.
>
> I like list comprehension in this case.
>
> def CSV_Lines2(csv, from_, to):
>     csv = csv[from_ : to]                                       # We are
> interested just here
>     csv = [line.split(',') for line in csv]     # Make a 2D array from the
> list
>     return [LineItems[1:-1] for LineItems in csv if len(LineItems) > 2]
>                     # filter out first and last columns, and lines with
> too less items
>
That is so neat, and a lot more elegant than my code ! - It may well be ahem 
Incorporated into my app :) I always seem to see codeing from my particular 
angle - I would never have dreamt of doing it that way. Thank you

Dave

>
>
> csv = """Header1
> Header2
> temp1,12,20,1
> temp2,22,22,2
> temp3,33,44,3
> temp4,34,64,4
> Footer1
> Footer2"""
>
> csv = csv.split('\n')
> print CSV_Lines2(csv, 2, 6)
>
> >>>[['12', '20'], ['22', '22'], ['33', '44'], ['34', '64']]
>
> Yours sincerely,
> ______________________________
> Janos Juhasz

From alan.gauld at freenet.co.uk  Mon Aug 21 18:41:59 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 21 Aug 2006 17:41:59 +0100
Subject: [Tutor] A list in list problem
References: <200608210959.01834.pythontut@pusspaws.net>
	<000901c6c51f$0c85ef40$0201a8c0@XPpro>
	<200608211719.35962.pythontut@pusspaws.net>
Message-ID: <000501c6c540$cfe04c80$0201a8c0@XPpro>

>>>> a=b=[]
>>>> a
> []
>>>> b
> []

These are the same list.

>>>> a=[1,2,3]

But here you create a new list and assign it to a.

>>>> a
> [1, 2, 3]
>>>> b
> []

So a points to the new list and b to the original.

> Tinkering some more I think it is the append that did it.

Yes, the append adds the data to the original list.

>>>> a=b=[]
>>>> a
> []
>>>> b
> []
>>>> a.append([1,2,3])
>>>> a
> [[1, 2, 3]]
>>>> b
> [[1, 2, 3]]

Exactly so.

> It appended to the common object and did not create a separate one ?

Yes, the first assignment to 'a' created a new list and broke the
shared reference.

I almost never use the x=y=value style for this reason.
For the minimal amount of typing I prefer either

x = value1
y = value2

or tuple assignment:

x,y = v1,v2

Which for lists is:

x,y = [],[]

ie two separate empty lists.

> I guess var1 = var2 = 0 is generally bad programming style ?

Its fine if you're sure it's what you want, but what it looks like
isn't always what you get... as you discovered  :-)

> get my code more compact using list comprehension etc

Compact code is not always a virtue.
Tuple assignment seems to me a good compromise.
And FWIW I try to limit tuple assignment to 3 values max
just for clarity. Also I try to ensure the variables are linked
in some way - like x,y coordinates, or similar types of variable:
max_len, min_len etc

> PS This is probably an impossible question but I always struggle to 
> find names
> for variables - any hints ?

Write a description of what it is there for - what does it do in the 
program.
Abbreviate that to a couple of key words. That's your name... If you 
want
a more detailed view find a copy of Code Complete by McConnell, it
has a whole chapter on variable naming issues...
Your variable names looked ok to me FWIW.

Alan G


From pythontut at pusspaws.net  Mon Aug 21 19:05:08 2006
From: pythontut at pusspaws.net (Dave S)
Date: Mon, 21 Aug 2006 18:05:08 +0100
Subject: [Tutor] A list in list problem
In-Reply-To: <000501c6c540$cfe04c80$0201a8c0@XPpro>
References: <200608210959.01834.pythontut@pusspaws.net>
	<200608211719.35962.pythontut@pusspaws.net>
	<000501c6c540$cfe04c80$0201a8c0@XPpro>
Message-ID: <200608211805.08249.pythontut@pusspaws.net>

On Monday 21 August 2006 17:41, Alan Gauld wrote:
> >>>> a=b=[]
> >>>> a
> >
> > []
> >
> >>>> b
> >
> > []
>
> These are the same list.
>
> >>>> a=[1,2,3]
>
> But here you create a new list and assign it to a.
>
> >>>> a
> >
> > [1, 2, 3]
> >
> >>>> b
> >
> > []
>
> So a points to the new list and b to the original.
>
> > Tinkering some more I think it is the append that did it.
>
> Yes, the append adds the data to the original list.
>
> >>>> a=b=[]
> >>>> a
> >
> > []
> >
> >>>> b
> >
> > []
> >
> >>>> a.append([1,2,3])
> >>>> a
> >
> > [[1, 2, 3]]
> >
> >>>> b
> >
> > [[1, 2, 3]]
>
> Exactly so.
>
> > It appended to the common object and did not create a separate one ?
>
> Yes, the first assignment to 'a' created a new list and broke the
> shared reference.
>
> I almost never use the x=y=value style for this reason.
> For the minimal amount of typing I prefer either
>
> x = value1
> y = value2
>
> or tuple assignment:
>
> x,y = v1,v2
>
> Which for lists is:
>
> x,y = [],[]
>
> ie two separate empty lists.
>
> > I guess var1 = var2 = 0 is generally bad programming style ?
>
> Its fine if you're sure it's what you want, but what it looks like
> isn't always what you get... as you discovered  :-)
>
> > get my code more compact using list comprehension etc
>
> Compact code is not always a virtue.
> Tuple assignment seems to me a good compromise.
> And FWIW I try to limit tuple assignment to 3 values max
> just for clarity. Also I try to ensure the variables are linked
> in some way - like x,y coordinates, or similar types of variable:
> max_len, min_len etc
>

Tupples, hadn't thought of that - I like it :)

> > PS This is probably an impossible question but I always struggle to
> > find names
> > for variables - any hints ?
>
> Write a description of what it is there for - what does it do in the
> program.
> Abbreviate that to a couple of key words. That's your name... If you
> want
> a more detailed view find a copy of Code Complete by McConnell, it
> has a whole chapter on variable naming issues...
> Your variable names looked ok to me FWIW.

Ahh buts that's the 5th time I have changed them - you should have seen the 
previous trys :)

>
> Alan G

From marcusdean.adams at gmail.com  Mon Aug 21 19:19:54 2006
From: marcusdean.adams at gmail.com (Marcus Dean Adams)
Date: Mon, 21 Aug 2006 13:19:54 -0400
Subject: [Tutor] Limiting Characters
Message-ID: <44e9eb3e.2f318229.508c.ffffa815@mx.gmail.com>

I?m fairly new to python, I?ve been dabbling in it for school and I have a
question.  I?ve written a few programs using graphical windows with input
boxes such as a stopwatch, temperature converter, etc.  I?ve always found a
gui much prettier than command line.  Anyway, I have limited the size of the
input boxes to the number of digits I wanted, but you can still put more
digits than that in the box.  For example, the temperature converter input
box is only 3 digits wide, however I can enter a 20 digit number if I want,
it just only shows 3 digits at a time.  How can I actually limit the number
of characters a user can enter, and not just the size of the input box?


-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.1.405 / Virus Database: 268.11.3/423 - Release Date: 8/18/2006
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060821/e2b1eb5b/attachment.htm 

From rabidpoobear at gmail.com  Mon Aug 21 21:41:50 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 21 Aug 2006 14:41:50 -0500
Subject: [Tutor] tkinter events: <B1-Motion>
In-Reply-To: <44E9B6E0.3060305@sch.bme.hu>
References: <44E9B6E0.3060305@sch.bme.hu>
Message-ID: <44EA0C7E.1040505@gmail.com>

Zsiros Levente wrote:
> [snip code]
> *def* handler(event):
> 	*if* buttonpressed == 1 :
> 		/#if the mousebutton is pressed and moved, circles should appear, but they do not/
> 		can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, fill="orange")
> 	lab.config(text='buttonpressed=' + str(buttonpressed) )
>
> *def* press(event):
> 	buttonpressed=1
> 	lab2.config(text=buttonpressed)
> 	
> *def* release(event):
> 	buttonpressed=0
> 	lab2.config(text=buttonpressed)	
> [snip code]
> /#global buttonpressed/
> buttonpressed=0

I think you're misunderstanding what global variables are.

Take the following example:

#--- code
a = 0
def b():
    print a
b()

#--- output
0
#---
the function 'b' can see the variable 'a'. ok so far.

now take this example.

#--- code
a = 0
def b():
    a = 1
    print a
b()
print a

#--- output
1
0
#---
in this case, 'a' is assigned to, but it's a local variable called 'a' 
and not the one I think you expect it to assign to.
so after 'b' is done the value of the 'a' outside of the scope of the 
function is still 0.
in your press and release events you assign values to 'buttonpressed' 
before you use them,
and because of this, the same thing happens as in our second example: a 
local variable named
'buttonpressed' is created with the value 0 or 1 assigned to it 
(depending on the function you're in.)
that works fine, and it sets the label's text value accordingly.  But, 
since it's a local variable and the
functions aren't actually modifying the global 'buttonpressed', the 
'buttonpressed' that you're checking for
in your 'handler' function is always going to be 0.  That's why your 
oval code is never drawn.

Rather than messing with global variables, which are for the most part 
evil creatures,
as we've witnessed so far here, I'd recommend using a class.
I wrote the class I would use for you so you can see it.
It's commented, but if you need any more help than the comments feel 
free to write me back.
Just be sure to use the reply-all button so the whole list can see the 
response.
-Luke
(note: code attached)

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: test.py
Url: http://mail.python.org/pipermail/tutor/attachments/20060821/cbddba30/attachment.pot 

From rabidpoobear at gmail.com  Mon Aug 21 21:48:27 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 21 Aug 2006 14:48:27 -0500
Subject: [Tutor] Limiting Characters
In-Reply-To: <44e9eb3e.2f318229.508c.ffffa815@mx.gmail.com>
References: <44e9eb3e.2f318229.508c.ffffa815@mx.gmail.com>
Message-ID: <44EA0E0B.6080001@gmail.com>

Marcus Dean Adams wrote:
>
> I?m fairly new to python, I?ve been dabbling in it for school and I 
> have a question.  I?ve written a few programs using graphical windows 
> with input boxes such as a stopwatch, temperature converter, etc.  
> I?ve always found a gui much prettier than command line.  Anyway, I 
> have limited the size of the input boxes to the number of digits I 
> wanted, but you can still put more digits than that in the box.  For 
> example, the temperature converter input box is only 3 digits wide, 
> however I can enter a 20 digit number if I want, it just only shows 3 
> digits at a time.  How can I actually limit the number of characters a 
> user can enter, and not just the size of the input box?
>
>
you can bind a callback for every key event and only add the key to the 
input box only if the length of the text currently in the inputbox is 
less than your target length.
you didn't say what GUI you're using so can't be of more help than that.
Alternatively, you can just truncate the extra digits so you have only 
3, but that's called 'unexpected behavior' as far as the user is concerned.
Sort of how my last name is 12 characters long, but on some apps that 
only have a 12 character array (with the actual length being 11 because
of the null terminator)  the last letter of my name gets truncated.  
This doesn't happen anymore, but I used to have everyone calling me
'paireepinar' because that's what was in the computer so they believed 
it.  Stupid old programs :)
>
> --
> No virus found in this outgoing message.
> Checked by AVG Free Edition.
> Version: 7.1.405 / Virus Database: 268.11.3/423 - Release Date: 8/18/2006
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From magoldfish at gmail.com  Mon Aug 21 22:50:37 2006
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Mon, 21 Aug 2006 16:50:37 -0400
Subject: [Tutor] custom container subclassing list-- slices are lists!?
Message-ID: <5e183f3d0608211350w73241fa6n967e9c742ce8b5eb@mail.gmail.com>

Hi,

I'd like to sublcass the built-in list type to create my own container.  How
can I make slices of the list be of type myclass-- currently they are
lists.  Example:

>>> class MyFoo(list):
           def __init__(self, inlist):
                  self = inlist[:]
>>> me = MyFoo(range(10))
>>> type(me)
<class '__main__.MyFoo'>

>>> type(me[0:3])
<type 'list'>


All help appreciated!

Thanks,
Marcus
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060821/133696df/attachment.html 

From nephish at gmail.com  Mon Aug 21 22:50:31 2006
From: nephish at gmail.com (shawn bright)
Date: Mon, 21 Aug 2006 15:50:31 -0500
Subject: [Tutor] how to get an email attachment
Message-ID: <384c93600608211350q362e7343m82dfa9d17e41de79@mail.gmail.com>

lo there pythoneers !

i have a simple script to pull some emails from a pop server.
so far, its working. What i need to do is get an attachment. That attachment
is going to be encoded in base 64.
so, i am looking and i can't find how to get the attachment. I have some
info on the base64 module, so i shouldn't have a problem when i get it...

here is what i have so far....

#!/usr/bin/python

import poplib
import string
import time

server = poplib.POP3('mail.xit.net')
server.user('moulder')
server.pass_('trustno1')

# server.list returns message info from server in
# form of response, message_list, size where message_list
# is a list of messages in form of 'message_id size'
message_list = server.list()

i = 0
for message in message_list[1]:
    i += 1

    message_parts = string.split(message,' ')
    message_id = message_parts[0]
    print 'message id is %s\n' % message_id
    total_email_message = server.retr(message_id)[1]
    for line in total_email_message:
        print line
    print 'deleting message....'
    # not deleting for right now
    # server.dele(message_id)
    time.sleep(1)
    print 'done'

server.quit()

any ideas would be greatly appreciated.
if you have read this far down, thanks for your time.

sk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060821/f0d3c33f/attachment.htm 

From carroll at tjc.com  Mon Aug 21 22:52:45 2006
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 21 Aug 2006 13:52:45 -0700 (PDT)
Subject: [Tutor] Big wad of Python tutorials
Message-ID: <Pine.LNX.4.44.0608211349370.28794-100000@violet.rahul.net>


This page, consisting of links to a few hundred topically sorted Python
tutorials, was mentioned on Digg recently.  I thought I'd pass on the URL:

http://www.awaretek.com/tutorials.html

Many of the URLs will be familiar to some on this list, but many more are 
new, certainly at least to me.



From john at fouhy.net  Mon Aug 21 23:07:52 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 22 Aug 2006 09:07:52 +1200
Subject: [Tutor] custom container subclassing list-- slices are lists!?
In-Reply-To: <5e183f3d0608211350w73241fa6n967e9c742ce8b5eb@mail.gmail.com>
References: <5e183f3d0608211350w73241fa6n967e9c742ce8b5eb@mail.gmail.com>
Message-ID: <5e58f2e40608211407p2fcb9725o7a4bd9757d1a9a7e@mail.gmail.com>

On 22/08/06, Marcus Goldfish <magoldfish at gmail.com> wrote:
> >>> class MyFoo(list):
>            def __init__(self, inlist):
>                   self = inlist[:]

Um, I'm fairly sure this line is not doing what you think it is doing!

self is just a local variable.  When __init__ is called, self is bound
to the MyFoo instance.  But when you do 'self = inlist[:]', you just
rebind it to a copy of inlist.  You aren't changing self..

> >>> me = MyFoo(range(10))
> >>> type(me)
> <class '__main__.MyFoo'>
>
> >>> type(me[0:3])
> <type 'list'>

Have you tried implementing __getitem__ and __setitem__ for slice objects?
(see http://docs.python.org/ref/sequence-methods.html and
http://docs.python.org/ref/sequence-types.html#l2h-231)

-- 
John.

From magoldfish at gmail.com  Mon Aug 21 23:17:00 2006
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Mon, 21 Aug 2006 17:17:00 -0400
Subject: [Tutor] custom container subclassing list-- slices are lists!?
In-Reply-To: <5e183f3d0608211350w73241fa6n967e9c742ce8b5eb@mail.gmail.com>
References: <5e183f3d0608211350w73241fa6n967e9c742ce8b5eb@mail.gmail.com>
Message-ID: <5e183f3d0608211417i10bb5aa1s37422ff15c5e51c@mail.gmail.com>

On 8/21/06, Marcus Goldfish <magoldfish at gmail.com> wrote:

> I'd like to sublcass the built-in list type to create my own container.
> How can I make slices of the list be of type myclass-- currently they are
> lists.  Example:
>
> >>> class MyFoo(list):
>            def __init__(self, inlist):
>                   self = inlist[:]
> >>> me = MyFoo(range(10))
> >>> type(me)
> <class '__main__.MyFoo'>
>
> >>> type(me[0:3])
> <type 'list'>
>

First, a better example class:

class MyFoo(list):
   def __init__(self, inlist):
      list.__init__(self, inlist)

Second, I think I found a partial answer in the Feb 22, 2005 tutor thread
http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2502290.  To
preserve type, I need to override some special functions.  In the case of
slicing, I need to override with something like this:

def __getslice__(self, i, j):
   return MyFoo(list.__getslice__(self, i, j))

This seems straightforward, but raises other questions: what other functions
should I override, e.g., __add__, __radd__?  Is there a preferred pythonic
way to creating a custom list container?

Finally, should I slice-copy my input list, inlist, to prevent side effects,
or is this handled by list?

Thanks,
Marcus
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060821/80434ce3/attachment.html 

From john at fouhy.net  Mon Aug 21 23:52:41 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 22 Aug 2006 09:52:41 +1200
Subject: [Tutor] custom container subclassing list-- slices are lists!?
In-Reply-To: <5e183f3d0608211417i10bb5aa1s37422ff15c5e51c@mail.gmail.com>
References: <5e183f3d0608211350w73241fa6n967e9c742ce8b5eb@mail.gmail.com>
	<5e183f3d0608211417i10bb5aa1s37422ff15c5e51c@mail.gmail.com>
Message-ID: <5e58f2e40608211452i52838c55q7f714738c47161ad@mail.gmail.com>

On 22/08/06, Marcus Goldfish <magoldfish at gmail.com> wrote:
> Second, I think I found a partial answer in the Feb 22, 2005 tutor thread
> http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2502290.
>  To preserve type, I need to override some special functions.  In the case
> of slicing, I need to override with something like this:
>
> def __getslice__(self, i, j):
>    return MyFoo(list.__getslice__(self, i, j))

__getslice__ is apparantly deprecated these days; you should override
__getitem__ instead.
(see the links I posted in my last message)

> This seems straightforward, but raises other questions: what other functions
> should I override, e.g., __add__, __radd__?  Is there a preferred pythonic
> way to creating a custom list container?

Hmm, if you were talking about dicts, I would have said "Use
UserDict.DictMixin".  But there doesn't seem to be a
UserList.ListMixin.  There's a community one here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440656  that
might work for you, but I haven't used it myself.

> Finally, should I slice-copy my input list, inlist, to prevent side effects,
> or is this handled by list?

Should be handled by the list.  For instance if x is a list, then
list(x) is a copy of x (y=list(x) is equivalent to y=x[:]).  But you
should be able to test this easily enough..

-- 
John.

From alan.gauld at freenet.co.uk  Mon Aug 21 23:57:08 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 21 Aug 2006 22:57:08 +0100
Subject: [Tutor] how to get an email attachment
References: <384c93600608211350q362e7343m82dfa9d17e41de79@mail.gmail.com>
Message-ID: <003001c6c56c$bfa79a90$0201a8c0@XPpro>

I'm no expert here, but isn't there a Mime module for
handling mail attachments? Might be worth a look.

Alan G.

----- Original Message ----- 
From: "shawn bright" <nephish at gmail.com>
To: "tutor-python" <tutor at python.org>
Sent: Monday, August 21, 2006 9:50 PM
Subject: [Tutor] how to get an email attachment


> lo there pythoneers !
>
> i have a simple script to pull some emails from a pop server.
> so far, its working. What i need to do is get an attachment. That 
> attachment
> is going to be encoded in base 64.
> so, i am looking and i can't find how to get the attachment. I have 
> some
> info on the base64 module, so i shouldn't have a problem when i get 
> it...
>
> here is what i have so far....
>
> #!/usr/bin/python
>
> import poplib
> import string
> import time
>
> server = poplib.POP3('mail.xit.net')
> server.user('moulder')
> server.pass_('trustno1')
>
> # server.list returns message info from server in
> # form of response, message_list, size where message_list
> # is a list of messages in form of 'message_id size'
> message_list = server.list()
>
> i = 0
> for message in message_list[1]:
>    i += 1
>
>    message_parts = string.split(message,' ')
>    message_id = message_parts[0]
>    print 'message id is %s\n' % message_id
>    total_email_message = server.retr(message_id)[1]
>    for line in total_email_message:
>        print line
>    print 'deleting message....'
>    # not deleting for right now
>    # server.dele(message_id)
>    time.sleep(1)
>    print 'done'
>
> server.quit()
>
> any ideas would be greatly appreciated.
> if you have read this far down, thanks for your time.
>
> sk
> 


From Barry.Carroll at psc.com  Tue Aug 22 00:02:18 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Mon, 21 Aug 2006 15:02:18 -0700
Subject: [Tutor] Big wad of Python tutorials
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C370B@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> Date: Mon, 21 Aug 2006 13:52:45 -0700 (PDT)
> From: Terry Carroll <carroll at tjc.com>
> Subject: [Tutor] Big wad of Python tutorials
> To: tutor at python.org
> Message-ID:
> 	<Pine.LNX.4.44.0608211349370.28794-100000 at violet.rahul.net>
> Content-Type: TEXT/PLAIN; charset=US-ASCII
> 
> 
> This page, consisting of links to a few hundred topically sorted
Python
> tutorials, was mentioned on Digg recently.  I thought I'd pass on the
URL:
> 
> http://www.awaretek.com/tutorials.html
> 
> Many of the URLs will be familiar to some on this list, but many more
are
> new, certainly at least to me.
> 
Thanks, Terry.  That link looks like a great resource.  I think I'll
start with the GUI sections.  

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

-Quarry worker's creed



From nephish at gmail.com  Tue Aug 22 00:31:51 2006
From: nephish at gmail.com (shawn bright)
Date: Mon, 21 Aug 2006 17:31:51 -0500
Subject: [Tutor] Big wad of Python tutorials
In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C370B@eugsrv400.psc.pscnet.com>
References: <2BBAEE949D384D40A2B851287ADB6A432C370B@eugsrv400.psc.pscnet.com>
Message-ID: <384c93600608211531x6964432bx3033eea205922df7@mail.gmail.com>

way cool, thanks !
-sk

On 8/21/06, Carroll, Barry <Barry.Carroll at psc.com> wrote:
>
> > -----Original Message-----
> > Date: Mon, 21 Aug 2006 13:52:45 -0700 (PDT)
> > From: Terry Carroll <carroll at tjc.com>
> > Subject: [Tutor] Big wad of Python tutorials
> > To: tutor at python.org
> > Message-ID:
> >       <Pine.LNX.4.44.0608211349370.28794-100000 at violet.rahul.net>
> > Content-Type: TEXT/PLAIN; charset=US-ASCII
> >
> >
> > This page, consisting of links to a few hundred topically sorted
> Python
> > tutorials, was mentioned on Digg recently.  I thought I'd pass on the
> URL:
> >
> > http://www.awaretek.com/tutorials.html
> >
> > Many of the URLs will be familiar to some on this list, but many more
> are
> > new, certainly at least to me.
> >
> Thanks, Terry.  That link looks like a great resource.  I think I'll
> start with the GUI sections.
>
> Regards,
>
> Barry
> barry.carroll at psc.com
> 541-302-1107
> ________________________
> We who cut mere stones must always be envisioning cathedrals.
>
> -Quarry worker's creed
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060821/f3d29c1e/attachment.htm 

From nephish at gmail.com  Tue Aug 22 02:22:16 2006
From: nephish at gmail.com (shawn bright)
Date: Mon, 21 Aug 2006 19:22:16 -0500
Subject: [Tutor] how to get an email attachment
In-Reply-To: <003001c6c56c$bfa79a90$0201a8c0@XPpro>
References: <384c93600608211350q362e7343m82dfa9d17e41de79@mail.gmail.com>
	<003001c6c56c$bfa79a90$0201a8c0@XPpro>
Message-ID: <384c93600608211722l5bed43dbna3bf2922ab6eb56d@mail.gmail.com>

Yes, indeed. I found in the essential reference book. It looks like it works
in the email module also. I will try a few things out here and let you know
how it goes.
thanks.

shawn

On 8/21/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
> I'm no expert here, but isn't there a Mime module for
> handling mail attachments? Might be worth a look.
>
> Alan G.
>
> ----- Original Message -----
> From: "shawn bright" <nephish at gmail.com>
> To: "tutor-python" <tutor at python.org>
> Sent: Monday, August 21, 2006 9:50 PM
> Subject: [Tutor] how to get an email attachment
>
>
> > lo there pythoneers !
> >
> > i have a simple script to pull some emails from a pop server.
> > so far, its working. What i need to do is get an attachment. That
> > attachment
> > is going to be encoded in base 64.
> > so, i am looking and i can't find how to get the attachment. I have
> > some
> > info on the base64 module, so i shouldn't have a problem when i get
> > it...
> >
> > here is what i have so far....
> >
> > #!/usr/bin/python
> >
> > import poplib
> > import string
> > import time
> >
> > server = poplib.POP3('mail.xit.net')
> > server.user('moulder')
> > server.pass_('trustno1')
> >
> > # server.list returns message info from server in
> > # form of response, message_list, size where message_list
> > # is a list of messages in form of 'message_id size'
> > message_list = server.list()
> >
> > i = 0
> > for message in message_list[1]:
> >    i += 1
> >
> >    message_parts = string.split(message,' ')
> >    message_id = message_parts[0]
> >    print 'message id is %s\n' % message_id
> >    total_email_message = server.retr(message_id)[1]
> >    for line in total_email_message:
> >        print line
> >    print 'deleting message....'
> >    # not deleting for right now
> >    # server.dele(message_id)
> >    time.sleep(1)
> >    print 'done'
> >
> > server.quit()
> >
> > any ideas would be greatly appreciated.
> > if you have read this far down, thanks for your time.
> >
> > sk
> >
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060821/89874bd2/attachment.html 

From Barry.Carroll at psc.com  Tue Aug 22 02:49:43 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Mon, 21 Aug 2006 17:49:43 -0700
Subject: [Tutor] Tutor Digest, Vol 30, Issue 68
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C370D@eugsrv400.psc.pscnet.com>

Hello, Marcus

> Date: Mon, 21 Aug 2006 16:50:37 -0400
> From: "Marcus Goldfish" <magoldfish at gmail.com>
> Subject: [Tutor] custom container subclassing list-- slices are
> 	lists!?
> To: Tutor <tutor at python.org>
> Message-ID:
> 	<5e183f3d0608211350w73241fa6n967e9c742ce8b5eb at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> Hi,
> 
> I'd like to sublcass the built-in list type to create my own
container.
> How
> can I make slices of the list be of type myclass-- currently they are
> lists.  Example:
> 
> >>> class MyFoo(list):
>            def __init__(self, inlist):
>                   self = inlist[:]
> >>> me = MyFoo(range(10))

I'll start with a side question: did you check the contents of me?  When
I did this (using the IPython shell running on Python 2.3) I got the
following:

**********
@BCARROLL[Python]|1> class MyFoo(list):
                 |.>     def __init__(self, inlist):
                 |.>         self = inlist[:]
                 |.>
@BCARROLL[Python]|2> me = MyFoo(range(10))
@BCARROLL[Python]|3> me
                 <3> []
**********

The identifier me did not get the list you wanted
([0,1,2,3,4,5,6,7,8,9]).  I don't know why.  Perhaps one of the more
experienced people on the list knows.

> >>> type(me)
> <class '__main__.MyFoo'>

This worked okay: the empty list is of type class MyFoo

> 
> >>> type(me[0:3])
> <type 'list'>

So far, you have only defined one special method for your class:
__init__.  All the other operations available for instances of your
class come from the base class list.  And the slicing operator for the
list class returns ... you guessed it ... a list.  In order to return an
instance or your class, you must override the slicing operator in your
class definition.  

Doing this correctly is not simple.  The slicing operator is implemented
by three special methods (__getitem__, __setitem__ and __delitem__),
each of which takes a slice OBJECT as a parameter.  Overriding these
three methods is pretty advanced Python.  "Python in a Nutshell, 2nd
Edition" (my Python bible) says, 

	"... It's best to avoid this complication by simply not defining

	the slice-specific special methods in your classes; however, 
	you may need to override these methods if your class subclasses 
	list or tuple and you want to provide special functionality when

	an instance of your class is sliced with just one colon. ..."
	[Section 5.2.2.4, Container Slicing]

So, the question to ask yourself is, "Do I require special functionality
when slicing a MyFoo object?".  If not, then don't worry that the
slice's type is different than that of the original instance.

If the answer is yes, however, you can try subclassing UserList.  Module
UserList was written back when built-in types like list could not be
subclassed.  It uses the now deprecated special methods __getslice__,
__setslice__ and __delslice__, and it is no longer entirely complete or
correct.  But it still works pretty well.  And, it also overrides many
other operators that apply to lists.  (Read about it in "Python Library
Reference" Section 3.8 and UserList.py.)

Using this module, your code would look like this:

**********
@BCARROLL[Python]|1> from UserList import UserList
@BCARROLL[Python]|2> class MyFoo(UserList):
                 |.>     def __init__(self, inlist):
                 |.>         UserList.__init__(self, inlist)
                 |.>
@BCARROLL[Python]|3> me = MyFoo(range(10))
@BCARROLL[Python]|4> me
                 <4> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
**********

Note that this construction handles the range method correctly.

**********
@BCARROLL[Python]|5> type(me)
                 <5> <type 'instance'>
@BCARROLL[Python]|6> isinstance(me, MyFoo)
                 <6> True
**********

Note here that the type method doesn't show me to be an instance of
MyFoo, but that isinstance does.  

**********
@BCARROLL[Python]|7> me[0:3]
                 <7> [0, 1, 2]
@BCARROLL[Python]|8> type(me[0:3])
                 <8> <type 'instance'>
@BCARROLL[Python]|9> isinstance(me[0:3], MyFoo)
                 <9> True 
**********

And finally, the slice is in fact an instance of MyFoo.

> All help appreciated!

Sorry for being so long-winded.  I hope this helps.  
> 
> Thanks,
> Marcus

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

-Quarry worker's creed




From nimrodx at slingshot.co.nz  Tue Aug 22 13:59:43 2006
From: nimrodx at slingshot.co.nz (nimrodx)
Date: Tue, 22 Aug 2006 21:59:43 +1000
Subject: [Tutor] os.path.walk
Message-ID: <44EAF1AF.8080209@slingshot.co.nz>

Hi All,

I was wondering if anyone had used os.path.walk within a class or not, 
and what are the pitfalls...

What has got me worried is that the function called by os.path.walk  
must be a method of the class.
Now this means it will have something like this as a def:

def func_called_by_walk(self, arg, directory, names):

Will this work with os.path.walk with that definition?

Thanks,

Matt

From zslevi at sch.bme.hu  Tue Aug 22 11:58:21 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Tue, 22 Aug 2006 11:58:21 +0200
Subject: [Tutor] tkinter events: <B1-Motion>
In-Reply-To: <44EA0C7E.1040505@gmail.com>
References: <44E9B6E0.3060305@sch.bme.hu> <44EA0C7E.1040505@gmail.com>
Message-ID: <44EAD53D.90100@sch.bme.hu>

Luke Paireepinart wrote:

> Zsiros Levente wrote:
>
>> [snip code]
>> *def* handler(event):
>>     *if* buttonpressed == 1 :
>>         /#if the mousebutton is pressed and moved, circles should 
>> appear, but they do not/
>>         can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, 
>> fill="orange")
>>     lab.config(text='buttonpressed=' + str(buttonpressed) )
>>
>> *def* press(event):
>>     buttonpressed=1
>>     lab2.config(text=buttonpressed)
>>     
>> *def* release(event):
>>     buttonpressed=0
>>     lab2.config(text=buttonpressed)   
>> [snip code]
>> /#global buttonpressed/
>> buttonpressed=0
>
>
> I think you're misunderstanding what global variables are.
>
Yes, others already mentioned that.

> Take the following example:
>
> #--- code
> a = 0
> def b():
>    print a
> b()
>
> #--- output
> 0
> #---
> the function 'b' can see the variable 'a'. ok so far.
>
> now take this example.
>
> #--- code
> a = 0
> def b():
>    a = 1
>    print a
> b()
> print a
>
> #--- output
> 1
> 0
> #---
> in this case, 'a' is assigned to, but it's a local variable called 'a' 
> and not the one I think you expect it to assign to.
> so after 'b' is done the value of the 'a' outside of the scope of the 
> function is still 0.
> in your press and release events you assign values to 'buttonpressed' 
> before you use them,
> and because of this, the same thing happens as in our second example: 
> a local variable named
> 'buttonpressed' is created with the value 0 or 1 assigned to it 
> (depending on the function you're in.)
> that works fine, and it sets the label's text value accordingly.  But, 
> since it's a local variable and the
> functions aren't actually modifying the global 'buttonpressed', the 
> 'buttonpressed' that you're checking for
> in your 'handler' function is always going to be 0.  That's why your 
> oval code is never drawn.
>
> Rather than messing with global variables, which are for the most part 
> evil creatures,
> as we've witnessed so far here, I'd recommend using a class.
> I wrote the class I would use for you so you can see it.
> It's commented, but if you need any more help than the comments feel 
> free to write me back.
> Just be sure to use the reply-all button so the whole list can see the 
> response.
> -Luke
> (note: code attached)
>
>------------------------------------------------------------------------
>
>#!/usr/bin/python
>
># This program implements <B1-motion>.  it was originally written by
>#Zsiros Levente.  all rights of this modified version go to him :)
>
>from Tkinter import *
>
>class ButtonHandler(object):
>    def __init__(self):
>        #our self.mousedown variable is what we'll use to check the state
>        #of the button, since we're going to be passing a copy of 'self'
>        #around, we don't have to deal with scoping of the variables.
>        #I.E. self.mousedown is global to functions in the class
>        #that accept a 'self' argument.
>        self.mousedown = 0
>        
>        #we make the window normally. note all these are 'self' variables
>        #so we can change them easily elsewhere in the class.
>        self.root = Tk()
>        self.root.geometry('600x500+200+200')
>        self.label = Label(self.root, text=str(self.mousedown))
>        self.can = Canvas(self.root, width='500', height='400', bg='white')
>        #lambda is a way we can add extra arguments to a function.
>        #since the callback of bound events is only a single argument,
>        #we use 'lambda x' to get the 'event' instance, and pass it
>        #along with another string identifying which event it came from.
>        #this may or may not be necessary, but it's cool and it
>        #makes the handler function make more sense.
>        #also, we only need one handler function this way.
>        self.can.bind("<Motion>",lambda x:self.handler(x,'motion'))
>        self.can.bind("<Button-1>",lambda x:self.handler(x,'press'))
>        self.can.bind("<ButtonRelease-1>",lambda x:self.handler(x,'release'))
>        self.label.pack()
>        self.can.pack()
>        self.root.mainloop()
>        
>    def handler(self,event,x):
>        #the first two clauses of the if-elif branch implement your
>        #'press' and 'release' functions.
>        if x == 'press':
>            self.mousedown = 1
>        elif x == 'release':
>            self.mousedown = 0
>        elif x == 'motion':
>            if self.mousedown:
>                #you could do something really cool here, like store the time
>                #that the button was last pressed, and increase the radius of the circle
>                #depending on how long it's been since then.
>                r = 5
>                self.can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, fill="orange")
>	self.label.config(text=str(self.mousedown))
>        
>
>#we create an instance of the class which automatically
>#calls the '__init__' method.
>x = ButtonHandler()
>  
>


From klappnase at freenet.de  Tue Aug 22 12:01:52 2006
From: klappnase at freenet.de (Michael Lange)
Date: Tue, 22 Aug 2006 12:01:52 +0200
Subject: [Tutor] Limiting Characters
In-Reply-To: <44e9eb3e.2f318229.508c.ffffa815@mx.gmail.com>
References: <44e9eb3e.2f318229.508c.ffffa815@mx.gmail.com>
Message-ID: <20060822120152.23bf5b86.klappnase@freenet.de>

On Mon, 21 Aug 2006 13:19:54 -0400
"Marcus Dean Adams" <marcusdean.adams at gmail.com> wrote:

> I_m fairly new to python, I_ve been dabbling in it for school and I have a
> question.  I_ve written a few programs using graphical windows with input
> boxes such as a stopwatch, temperature converter, etc.  I_ve always found a
> gui much prettier than command line.  Anyway, I have limited the size of the
> input boxes to the number of digits I wanted, but you can still put more
> digits than that in the box.  For example, the temperature converter input
> box is only 3 digits wide, however I can enter a 20 digit number if I want,
> it just only shows 3 digits at a time.  How can I actually limit the number
> of characters a user can enter, and not just the size of the input box?
> 
> 

Hi Marcus,

this depends of course on the toolkit you use.
If it is Tkinter, you can use the Entry widget's validatecommand, see:

    http://mail.python.org/pipermail/tkinter-discuss/2006-August/000863.html

I hope this helps

Michael

From zslevi at sch.bme.hu  Tue Aug 22 12:05:30 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Tue, 22 Aug 2006 12:05:30 +0200
Subject: [Tutor] tkinter events: <B1-Motion>
In-Reply-To: <44EA0C7E.1040505@gmail.com>
References: <44E9B6E0.3060305@sch.bme.hu> <44EA0C7E.1040505@gmail.com>
Message-ID: <44EAD6EA.1000807@sch.bme.hu>

You're right, that I pressed reply instead of reply-to-all, so the list 
didn't see my response. But this way you got my mail twice. Isn't that 
annoying? Other maillist servers used to use the reply-to tag in the 
message header.

Luke Paireepinart wrote:

> Zsiros Levente wrote:
>
>> [snip code]
>> *def* handler(event):
>>     *if* buttonpressed == 1 :
>>         /#if the mousebutton is pressed and moved, circles should 
>> appear, but they do not/
>>         can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, 
>> fill="orange")
>>     lab.config(text='buttonpressed=' + str(buttonpressed) )
>>
>> *def* press(event):
>>     buttonpressed=1
>>     lab2.config(text=buttonpressed)
>>     
>> *def* release(event):
>>     buttonpressed=0
>>     lab2.config(text=buttonpressed)   
>> [snip code]
>> /#global buttonpressed/
>> buttonpressed=0
>
>
> I think you're misunderstanding what global variables are.
>
> Take the following example:
>
> #--- code
> a = 0
> def b():
>    print a
> b()
>
> #--- output
> 0
> #---
> the function 'b' can see the variable 'a'. ok so far.
>
> now take this example.
>
> #--- code
> a = 0
> def b():
>    a = 1
>    print a
> b()
> print a
>
> #--- output
> 1
> 0
> #---
> in this case, 'a' is assigned to, but it's a local variable called 'a' 
> and not the one I think you expect it to assign to.
> so after 'b' is done the value of the 'a' outside of the scope of the 
> function is still 0.
> in your press and release events you assign values to 'buttonpressed' 
> before you use them,
> and because of this, the same thing happens as in our second example: 
> a local variable named
> 'buttonpressed' is created with the value 0 or 1 assigned to it 
> (depending on the function you're in.)
> that works fine, and it sets the label's text value accordingly.  But, 
> since it's a local variable and the
> functions aren't actually modifying the global 'buttonpressed', the 
> 'buttonpressed' that you're checking for
> in your 'handler' function is always going to be 0.  That's why your 
> oval code is never drawn.
>
> Rather than messing with global variables, which are for the most part 
> evil creatures,
> as we've witnessed so far here, I'd recommend using a class.
> I wrote the class I would use for you so you can see it.
> It's commented, but if you need any more help than the comments feel 
> free to write me back.
> Just be sure to use the reply-all button so the whole list can see the 
> response.
> -Luke
> (note: code attached)
>
>------------------------------------------------------------------------
>
>#!/usr/bin/python
>
># This program implements <B1-motion>.  it was originally written by
>#Zsiros Levente.  all rights of this modified version go to him :)
>
>from Tkinter import *
>
>class ButtonHandler(object):
>    def __init__(self):
>        #our self.mousedown variable is what we'll use to check the state
>        #of the button, since we're going to be passing a copy of 'self'
>        #around, we don't have to deal with scoping of the variables.
>        #I.E. self.mousedown is global to functions in the class
>        #that accept a 'self' argument.
>        self.mousedown = 0
>        
>        #we make the window normally. note all these are 'self' variables
>        #so we can change them easily elsewhere in the class.
>        self.root = Tk()
>        self.root.geometry('600x500+200+200')
>        self.label = Label(self.root, text=str(self.mousedown))
>        self.can = Canvas(self.root, width='500', height='400', bg='white')
>        #lambda is a way we can add extra arguments to a function.
>        #since the callback of bound events is only a single argument,
>        #we use 'lambda x' to get the 'event' instance, and pass it
>        #along with another string identifying which event it came from.
>        #this may or may not be necessary, but it's cool and it
>        #makes the handler function make more sense.
>        #also, we only need one handler function this way.
>        self.can.bind("<Motion>",lambda x:self.handler(x,'motion'))
>        self.can.bind("<Button-1>",lambda x:self.handler(x,'press'))
>        self.can.bind("<ButtonRelease-1>",lambda x:self.handler(x,'release'))
>        self.label.pack()
>        self.can.pack()
>        self.root.mainloop()
>        
>    def handler(self,event,x):
>        #the first two clauses of the if-elif branch implement your
>        #'press' and 'release' functions.
>        if x == 'press':
>            self.mousedown = 1
>        elif x == 'release':
>            self.mousedown = 0
>        elif x == 'motion':
>            if self.mousedown:
>                #you could do something really cool here, like store the time
>                #that the button was last pressed, and increase the radius of the circle
>                #depending on how long it's been since then.
>                r = 5
>                self.can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, fill="orange")
>	self.label.config(text=str(self.mousedown))
>        
>
>#we create an instance of the class which automatically
>#calls the '__init__' method.
>x = ButtonHandler()
>  
>


From zslevi at sch.bme.hu  Tue Aug 22 12:16:22 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Tue, 22 Aug 2006 12:16:22 +0200
Subject: [Tutor] tkinter events: <B1-Motion>
In-Reply-To: <44EAD53D.90100@sch.bme.hu>
References: <44E9B6E0.3060305@sch.bme.hu> <44EA0C7E.1040505@gmail.com>
	<44EAD53D.90100@sch.bme.hu>
Message-ID: <44EAD976.2020806@sch.bme.hu>

Zsiros Levente wrote:

>Luke Paireepinart wrote:
>
>  
>
>>Zsiros Levente wrote:
>>
>>    
>>
>>>[snip code]
>>>*def* handler(event):
>>>    *if* buttonpressed == 1 :
>>>        /#if the mousebutton is pressed and moved, circles should 
>>>appear, but they do not/
>>>        can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, 
>>>fill="orange")
>>>    lab.config(text='buttonpressed=' + str(buttonpressed) )
>>>
>>>*def* press(event):
>>>    buttonpressed=1
>>>    lab2.config(text=buttonpressed)
>>>    
>>>*def* release(event):
>>>    buttonpressed=0
>>>    lab2.config(text=buttonpressed)   
>>>[snip code]
>>>/#global buttonpressed/
>>>buttonpressed=0
>>>      
>>>
>>I think you're misunderstanding what global variables are.
>>
>>    
>>
>Yes, others already mentioned that.
>  
>
You didn't notice that, because first I accidentally sent the code to 
other thread (self-modification; of which I have three already :-X )

>  
>
>>Take the following example:
>>
>>#--- code
>>a = 0
>>def b():
>>   print a
>>b()
>>
>>#--- output
>>0
>>#---
>>the function 'b' can see the variable 'a'. ok so far.
>>
>>now take this example.
>>
>>#--- code
>>a = 0
>>def b():
>>   a = 1
>>   print a
>>b()
>>print a
>>
>>#--- output
>>1
>>0
>>#---
>>in this case, 'a' is assigned to, but it's a local variable called 'a' 
>>and not the one I think you expect it to assign to.
>>so after 'b' is done the value of the 'a' outside of the scope of the 
>>function is still 0.
>>in your press and release events you assign values to 'buttonpressed' 
>>before you use them,
>>and because of this, the same thing happens as in our second example: 
>>a local variable named
>>'buttonpressed' is created with the value 0 or 1 assigned to it 
>>(depending on the function you're in.)
>>that works fine, and it sets the label's text value accordingly.  But, 
>>since it's a local variable and the
>>functions aren't actually modifying the global 'buttonpressed', the 
>>'buttonpressed' that you're checking for
>>in your 'handler' function is always going to be 0.  That's why your 
>>oval code is never drawn.
>>
>>Rather than messing with global variables, which are for the most part 
>>evil creatures,
>>as we've witnessed so far here, I'd recommend using a class.
>>I wrote the class I would use for you so you can see it.
>>It's commented, but if you need any more help than the comments feel 
>>free to write me back.
>>Just be sure to use the reply-all button so the whole list can see the 
>>response.
>>-Luke
>>(note: code attached)
>>
>>------------------------------------------------------------------------
>>
>>#!/usr/bin/python
>>
>># This program implements <B1-motion>.  it was originally written by
>>#Zsiros Levente.  all rights of this modified version go to him :)
>>
>>    
>>
>>from Tkinter import *
>  
>
>>class ButtonHandler(object):
>>   def __init__(self):
>>       #our self.mousedown variable is what we'll use to check the state
>>       #of the button, since we're going to be passing a copy of 'self'
>>       #around, we don't have to deal with scoping of the variables.
>>       #I.E. self.mousedown is global to functions in the class
>>       #that accept a 'self' argument.
>>       self.mousedown = 0
>>       
>>       #we make the window normally. note all these are 'self' variables
>>       #so we can change them easily elsewhere in the class.
>>       self.root = Tk()
>>       self.root.geometry('600x500+200+200')
>>       self.label = Label(self.root, text=str(self.mousedown))
>>       self.can = Canvas(self.root, width='500', height='400', bg='white')
>>       #lambda is a way we can add extra arguments to a function.
>>       #since the callback of bound events is only a single argument,
>>       #we use 'lambda x' to get the 'event' instance, and pass it
>>       #along with another string identifying which event it came from.
>>       #this may or may not be necessary, but it's cool and it
>>       #makes the handler function make more sense.
>>       #also, we only need one handler function this way.
>>       self.can.bind("<Motion>",lambda x:self.handler(x,'motion'))
>>       self.can.bind("<Button-1>",lambda x:self.handler(x,'press'))
>>       self.can.bind("<ButtonRelease-1>",lambda x:self.handler(x,'release'))
>>       self.label.pack()
>>       self.can.pack()
>>       self.root.mainloop()
>>       
>>   def handler(self,event,x):
>>       #the first two clauses of the if-elif branch implement your
>>       #'press' and 'release' functions.
>>       if x == 'press':
>>           self.mousedown = 1
>>       elif x == 'release':
>>           self.mousedown = 0
>>       elif x == 'motion':
>>           if self.mousedown:
>>               #you could do something really cool here, like store the time
>>               #that the button was last pressed, and increase the radius of the circle
>>               #depending on how long it's been since then.
>>               r = 5
>>               self.can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, fill="orange")
>>	self.label.config(text=str(self.mousedown))
>>       
>>
>>#we create an instance of the class which automatically
>>#calls the '__init__' method.
>>x = ButtonHandler()
>> 
>>
>>    
>>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>


From zslevi at sch.bme.hu  Tue Aug 22 12:28:53 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Tue, 22 Aug 2006 12:28:53 +0200
Subject: [Tutor] [Fwd: [Fwd: self-modification]]
In-Reply-To: <44E9D363.7090108@sch.bme.hu>
References: <44E9D363.7090108@sch.bme.hu>
Message-ID: <44EADC65.3040504@sch.bme.hu>

Why does the python shell says this:

>>> print exec.__doc__
  File "<stdin>", line 1
    print exec.__doc__
             ^
SyntaxError: invalid syntax


While it works with "eval".

Anyway, I'm quite impressed with the resposiveness of this list. Thanks 
a  lot.

Zsiros Levente wrote:

>
>
> Sorry, the source was for my tkinter question. I'm a bit disorganized 
> today.
>
> The problematic part is the 11. line, where I have to convert the item 
> selected from the list to an object, or something like that. At the 
> moment it only applies to a string object, but I want to call the 
> function for the object, represented by the string. (If you run it, it 
> will become more obvious what I mean.)
>
>
> -------- Original Message --------
> Subject:     [Fwd: self-modification]
> Date:     Mon, 21 Aug 2006 16:06:52 +0200
> From:     Zsiros Levente <zslevi at sch.bme.hu>
> To:     python tutor <tutor at python.org>
>
>
>
> I forgot the most important thing: the attachment.
> -------- Original Message --------
> Subject:     self-modification
> Date:     Mon, 21 Aug 2006 16:04:19 +0200
> From:     Zsiros Levente <zslevi at sch.bme.hu>
> To:     python tutor <tutor at python.org>
>
>
>
> I'm a newbie to Python. I wanted to write a graphical interface which 
> would show the built-in documentation (I mean dir() and __doc__ ) of 
> Python. The code shows how far I got before realizing that I had to 
> use some self-modification feature (converting a string to a function 
> or to an object; i'm not sure you would call it self-modification in 
> an interpreted language).
>
> I was googling around, and searching in the maillist archives and 
> found this:
> http://mail.python.org/pipermail/tutor/2004-October/032388.html
> Unanswered for two years. Not too promising :)
>
> P.S.: I'm new to this mailing list, so I don't know whether it is 
> allowed to send code as attachment. (I didn't found anything about 
> your policy in the subscription site. )  If not, I'm sorry.
>
>
>
>
>------------------------------------------------------------------------
>
>#!/usr/bin/python
>
>from Tkinter import *
>from os import *
>from string import *
>import os
>import string
>import Tkinter
>
>def list_click(event):
>	description.config( text=listbox.get(listbox.curselection()[0]).__doc__ )
>
>list = dir(Tkinter)
>#print list
>
>root=Tk()
>root.geometry('+100+100')
>
>l_frame = Frame(root)
>r_frame = Frame(root)
>
>label = Label(l_frame)
>label.config(text='filename')
>
>description = Label(r_frame)
>
>listbox = Listbox(l_frame)
>listbox.bind('<Double-Button-1>',list_click)
>
>for item in list :
>	listbox.insert(0,item)
>
>
>l_frame.pack(side=LEFT,fill=BOTH)
>label.pack()
>listbox.pack(expand=1,fill=BOTH)
>
>r_frame.pack(side=RIGHT)
>description.pack()
>
>root.mainloop()
>
>  
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>


From kent37 at tds.net  Tue Aug 22 13:19:48 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 22 Aug 2006 07:19:48 -0400
Subject: [Tutor] os.path.walk
In-Reply-To: <44EAF1AF.8080209@slingshot.co.nz>
References: <44EAF1AF.8080209@slingshot.co.nz>
Message-ID: <44EAE854.7020607@tds.net>

nimrodx wrote:
> Hi All,
>
> I was wondering if anyone had used os.path.walk within a class or not, 
> and what are the pitfalls...
>
> What has got me worried is that the function called by os.path.walk  
> must be a method of the class.
> Now this means it will have something like this as a def:
>
> def func_called_by_walk(self, arg, directory, names):
>
> Will this work with os.path.walk with that definition?

Yes, that is the right way to do it and it will work fine. Something like

class Walker(object):
  def walk(self, base):
    os.path.walk(base, self.callback, None)

  def callback(self, arg, dir, names):
    pass

What happens is, when Python looks up self.callback it converts the 
method to a "bound method". The bound method is a a callable that takes 
(in this case) only three arguments; the value of self is held by the 
bound method and passed to the original function object (which does take 
four arguments).

But, if you are using a recent version of Python (2.3 or greater) you 
should look at os.walk(), it is easier to use than os.path.walk().

Kent


From kent37 at tds.net  Tue Aug 22 13:22:09 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 22 Aug 2006 07:22:09 -0400
Subject: [Tutor] [Fwd: [Fwd: self-modification]]
In-Reply-To: <44EADC65.3040504@sch.bme.hu>
References: <44E9D363.7090108@sch.bme.hu> <44EADC65.3040504@sch.bme.hu>
Message-ID: <44EAE8E1.500@tds.net>

Zsiros Levente wrote:
> Why does the python shell says this:
>
>   
>>>> print exec.__doc__
>>>>         
>   File "<stdin>", line 1
>     print exec.__doc__
>              ^
> SyntaxError: invalid syntax
>
>
> While it works with "eval".

exec is a statement that is interpreted by the compiler and compiled to 
byte code. There is no 'exec' object. OTOH eval is a function in the 
built-in namespace, so there is an 'eval' object and you can look at its 
attributes, including its doc string.

Kent


From pythontut at pusspaws.net  Tue Aug 22 14:01:16 2006
From: pythontut at pusspaws.net (Dave S)
Date: Tue, 22 Aug 2006 13:01:16 +0100
Subject: [Tutor] Larger GUI design ?
Message-ID: <200608221301.17131.pythontut@pusspaws.net>

I have managed to write a small GUI app, it had a frm_app.py from eric3s QT 
designer & a dlg_app.py which defined a class that inherited the frm_app.py 
class ... all AOK

I am now on a more ambitious project. There will be a main app screen, some 
dialogue screens for more info etc and a backend script analysing a database 
which will take some time to run.

The backend script is almost there, just tons of auditing rules to write for 
it but the backend 'engine' is working.

How to fit the GUI around it ?

If I have my dlg_app.py  inhereting frm_app.py all is well until I need a 
poppup dialogue.

Would I define another module say dlg_info.py with its frm_info.py which I 
would import and call when needed generating its own QT object and window. 
And in that module code something like the following would make the window on 
the fly ?


	app = QApplication(sys.argv)
	win =  info()
	app.setMainWidget(win)
	win.show()
	QObject.connect(app, SIGNAL('lastWindowClosed()'),app, SLOT('quit()'))
	app.exec_loop()


Secondly my backend will take a while to run & I would like to display a 
status bar in the GUI. The only way i can see to do this is to either

(1) make my backend a class & inherit dlg_app.py so I can access the QT widget 
directly or 

(2) pass info from the backend via a socket (yep know about them now!) to a QT 
script running in timerEvent()

Which is the best method ? Or is there a better way ?

Dave

From andrew.arobert at gmail.com  Tue Aug 22 17:36:55 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Tue, 22 Aug 2006 11:36:55 -0400
Subject: [Tutor] [whitelist] Re:  regular expressions question
In-Reply-To: <44E44D5B.6000605@slingshot.co.nz>
References: <44DDC3AA.8010908@slingshot.co.nz>	<002a01c6bdf2$60c69480$0201a8c0@XPpro>	<44DDE5D1.1080101@slingshot.co.nz>	<001801c6be13$fb72d220$0201a8c0@XPpro>
	<44E44D5B.6000605@slingshot.co.nz>
Message-ID: <44EB2497.5060000@gmail.com>

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

Hi Nimrodx,

In case you haven't found a solution yet, I developed a program to
encode/decode stuff similar to this.

You may want to take a look at it at

 http://home.townisp.com/~arobert/python/file_encoder.py



nimrodx wrote:
> Hi Alan,
> 
> I found a pretty complicated way to do it (Alan's way is way more elegant).
> In case someone is searching the archive, maybe they will find something 
> in it that is useful.
> It uses the regular experessions module.
> 
> import re
> 
> def dehexlify_websites(fle):
>    # get binary data
>    inpt = open(fle,'rb')
>    dat = inpt.read()
>    inpt.close()
>    #strip out the hex "0"'s
>    pattern = r"\x00"
>    res = re.sub(pattern, "", dat)
>    #-----------------------------------------
>    #it seemed easier to do it in two passes
>    #create the pattern regular expression for the stuff we want to keep
>    web = re.compile(
>                     r"(?P<addr>[/a-zA-Z0-9\.\-:\_%\?&=]+)"
>                     )
>    #grab them all and put them in temp variable
>    res = re.findall(web,res)
>    tmp = ""
>    #oops need some new lines at the end of each one to mark end of
>     #web address,
>    #and need it all as one string
>    for i in res:
>        tmp = tmp + i+'\n'
>    #compile reg expr for everything between :// and the newline
>    web2 = re.compile(r":/(?P<address>[^\n]+)")
>    #find the websites
>    #make them into an object we can pass
>    res2 = re.findall(web2,tmp)
>    #return 'em
>    return res2
> 
> 
> Thanks Alan,
> 
> Matt
> 
> 
> Alan Gauld wrote:
>>> if you look carefully at the string below, you see
>>> that in amongst the "\x" stuff you have the text I want:
>>> z tfile://home/alpha
>> OK, those characters are obviously string data and it looks
>> like its using 16 bit characters, so yes some kind of
>> unicode string. In between and at the end ;lies the binary
>> data in whatever format it is.
>>
>>>>> Here is the first section of the file:
>>>>> '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l' 
>>>>>
>>
>>> In a hex editor it turns out to be readable and sensible url's with 
>>> spaces between each digit, and a bit of crud at the end of url's, 
>>> just as above.
>> Here's a fairly drastic approach:
>>
>>>>> s = 
>>>>> '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01 
>>>>>
>> \xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x 
>>
>> 00l'
>>>>> ''.join([c for c in s if c.isalnum() or c in '/: '])
>> 'ztfile:/home/al'
>> But it gets close...
>>
>> Alan g.
>>
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFE6ySXDvn/4H0LjDwRApntAJ0Wd0ecE/KFUSbbKQSRmrV72yyvfwCeOwAQ
Gjg5IK0WG0YT6keGlDw0q94=
=7QB2
-----END PGP SIGNATURE-----

From alan.gauld at freenet.co.uk  Tue Aug 22 18:00:23 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 22 Aug 2006 17:00:23 +0100
Subject: [Tutor] os.path.walk
References: <44EAF1AF.8080209@slingshot.co.nz>
Message-ID: <000e01c6c604$1900a7c0$0201a8c0@XPpro>

> What has got me worried is that the function called by os.path.walk 
> must be a method of the class.
> Now this means it will have something like this as a def:
>
> def func_called_by_walk(self, arg, directory, names):
>
> Will this work with os.path.walk with that definition?

No, but you can wrap it in a lambda that calls the method:

lambda x,y,z: self.func_called_by_walk(x,y,z)

But have you looked at os.walk?
It is a little easier to use for most things IMHO.
No need to pass a function in for a start.

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


From alan.gauld at freenet.co.uk  Tue Aug 22 18:04:42 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 22 Aug 2006 17:04:42 +0100
Subject: [Tutor] os.path.walk
References: <44EAF1AF.8080209@slingshot.co.nz> <44EAE854.7020607@tds.net>
Message-ID: <002301c6c604$ae229a70$0201a8c0@XPpro>

> Yes, that is the right way to do it and it will work fine. Something 
> like
>
> class Walker(object):
>  def walk(self, base):
>    os.path.walk(base, self.callback, None)

>
> What happens is, when Python looks up self.callback it converts the 
> method to a "bound method".

Aargh! I should have remembered that. No need for lambdas here.
Apologies...

> But, if you are using a recent version of Python (2.3 or greater) 
> you should look at os.walk(), it is easier to use than 
> os.path.walk().

But I did suggest that too :-)

Alan G.


From alan.gauld at freenet.co.uk  Tue Aug 22 18:10:40 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 22 Aug 2006 17:10:40 +0100
Subject: [Tutor] [Fwd: [Fwd: self-modification]]
References: <44E9D363.7090108@sch.bme.hu> <44EADC65.3040504@sch.bme.hu>
Message-ID: <002b01c6c605$83ceebb0$0201a8c0@XPpro>


> Why does the python shell says this:
> 
>>>> print exec.__doc__
>  File "<stdin>", line 1
>    print exec.__doc__
>             ^
> SyntaxError: invalid syntax

exec, like print, is a statement, or command, not a function.

You get the same response if you try

>>> print print.__doc__

or 

>>> help(print)

> While it works with "eval".

eval is a function so has a doc string attached.

Alan G.

From alan.gauld at freenet.co.uk  Tue Aug 22 18:15:26 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 22 Aug 2006 17:15:26 +0100
Subject: [Tutor] Larger GUI design ?
References: <200608221301.17131.pythontut@pusspaws.net>
Message-ID: <002f01c6c606$44f702a0$0201a8c0@XPpro>

> I am now on a more ambitious project. There will be a main app 
> screen, some
> dialogue screens for more info etc and a backend script analysing a 
> database
> which will take some time to run.
>
> How to fit the GUI around it ?
>
> If I have my dlg_app.py  inhereting frm_app.py all is well until I 
> need a
> poppup dialogue.

Its usually better to make popups inherit directly from TopLevel 
rather
than the parent form.

> Would I define another module say dlg_info.py with its frm_info.py

Its usually best to put each significant window/dialog in its own 
form.
It makes them easier to reuse in other projects for one thing!

> would import and call when needed generating its own QT
> object and window.

Not sure how QT works so can't comment on that.

> app = QApplication(sys.argv)

Are you sure there isn't a QDialog base class somewhere in QT?
Thats usually been the case in other GUI toolkits I've used.

> Secondly my backend will take a while to run & I would like to 
> display a
> status bar in the GUI. The only way i can see to do this is to 
> either

Sounds like a job for a thread...

> (2) pass info from the backend via a socket (yep know about them 
> now!) to a QT
> script running in timerEvent()

You can do this but threads are less resource greedy.

HTH,

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


From pythontut at pusspaws.net  Tue Aug 22 19:21:03 2006
From: pythontut at pusspaws.net (Dave S)
Date: Tue, 22 Aug 2006 18:21:03 +0100
Subject: [Tutor] Larger GUI design ?
In-Reply-To: <002f01c6c606$44f702a0$0201a8c0@XPpro>
References: <200608221301.17131.pythontut@pusspaws.net>
	<002f01c6c606$44f702a0$0201a8c0@XPpro>
Message-ID: <200608221821.03287.pythontut@pusspaws.net>

On Tuesday 22 August 2006 17:15, Alan Gauld wrote:
> > I am now on a more ambitious project. There will be a main app
> > screen, some
> > dialogue screens for more info etc and a backend script analysing a
> > database
> > which will take some time to run.
> >
> > How to fit the GUI around it ?
> >
> > If I have my dlg_app.py  inhereting frm_app.py all is well until I
> > need a
> > poppup dialogue.
>
> Its usually better to make popups inherit directly from TopLevel
> rather
> than the parent form

OK I will look into that

>
> > Would I define another module say dlg_info.py with its frm_info.py
>
> Its usually best to put each significant window/dialog in its own
> form.
> It makes them easier to reuse in other projects for one thing!
>

Code reuse is good

> > would import and call when needed generating its own QT
> > object and window.
>
> Not sure how QT works so can't comment on that.
>
> > app = QApplication(sys.argv)
>
> Are you sure there isn't a QDialog base class somewhere in QT?
> Thats usually been the case in other GUI toolkits I've used.

Base class ? OK you lost me - I will dig into the docs


>
> > Secondly my backend will take a while to run & I would like to
> > display a
> > status bar in the GUI. The only way i can see to do this is to
> > either
>
> Sounds like a job for a thread...
>
> > (2) pass info from the backend via a socket (yep know about them
> > now!) to a QT
> > script running in timerEvent()
>
> You can do this but threads are less resource greedy.

I had not thought of a thread - thats a cool solution

Thanks for your suggestions, Its probably obvious for you old hands but its a 
whole new world for us beginners :)

You have given me enough info to run with - I will give it a go & see what 
happens

Dave

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

From dyoo at hkn.eecs.berkeley.edu  Tue Aug 22 21:59:53 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 22 Aug 2006 12:59:53 -0700 (PDT)
Subject: [Tutor] tkinter events: <B1-Motion>
In-Reply-To: <44E9B6E0.3060305@sch.bme.hu>
References: <44E9B6E0.3060305@sch.bme.hu>
Message-ID: <Pine.LNX.4.64.0608221249580.27647@hkn.eecs.berkeley.edu>

> def handler(event):
> 	if buttonpressed == 1 :
> 		/#if the mousebutton is pressed and moved, circles should 
> appear, but they do not/
> 		can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, 
> fill="orange")
> 	lab.config(text='buttonpressed=' + str(buttonpressed) )


The variables of functions are normally independent of each other.  That 
is, if I have a function square():

##############
def square(x):
     y = x * x
     return y
##############

and if I have a function that uses square that itself has a 'y' variable, 
I should not see interference:

##############
def test():
     y = 17
     print "square of y is", square(y)
     print "y itself is", y
##############

This black-boxing is what allows us to write and reuse functions with 
reckless abandon: their innards are meant not to interact with one 
another.  This is a feature that you usually want to have.


But for your purposes, you want some controlled form of leakage.  Use 
'global' for this purpose by declaring the shared variable at the head of 
your functions.  Compare the results above to the ones below:

#####################################
def square(x):
      global y
      y = x * x
      return y

def test():
     global y
     y = 17
     print "square of y is", square(y)
     print "y itself is", y
#####################################

There's terse reference material here about global:

     http://www.python.org/doc/ref/global.html#l2h-558

It's idiomatic programming practice to limit the use of 'global' to 
situations where it's necessary; using it in an uncontrolled way leads to 
code that's difficult to read or reason with.  There are more sophsticated 
ways to share variables between functions.  That being said, though, the 
'global' mechanism will probably be simplest for your purposes.


Good luck to you!

From wescpy at gmail.com  Tue Aug 22 22:15:38 2006
From: wescpy at gmail.com (wesley chun)
Date: Tue, 22 Aug 2006 13:15:38 -0700
Subject: [Tutor] how to get an email attachment
In-Reply-To: <384c93600608211722l5bed43dbna3bf2922ab6eb56d@mail.gmail.com>
References: <384c93600608211350q362e7343m82dfa9d17e41de79@mail.gmail.com>
	<003001c6c56c$bfa79a90$0201a8c0@XPpro>
	<384c93600608211722l5bed43dbna3bf2922ab6eb56d@mail.gmail.com>
Message-ID: <78b3a9580608221315j763d3e1eg5339cbb1a2950a87@mail.gmail.com>

On 8/21/06, shawn bright <nephish at gmail.com> wrote:
> Yes, indeed. I found in the essential reference book. It looks like it works
> in the email module also. I will try a few things out here and let you know
> how it goes.
> thanks.
>
> shawn
>
>
>  On 8/21/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> > I'm no expert here, but isn't there a Mime module for
> > handling mail attachments? Might be worth a look.
> >
> > ----- Original Message -----
> > From: "shawn bright" < nephish at gmail.com>
> > Sent: Monday, August 21, 2006 9:50 PM
> >
> > What i need to do is get an attachment. That
> > > attachment
> > > is going to be encoded in base 64.
> > > so, i am looking and i can't find how to get the attachment.

shawn,

in particular, check out the email.Message submodule, esp. get_payload().

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

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

From wescpy at gmail.com  Wed Aug 23 02:58:58 2006
From: wescpy at gmail.com (wesley chun)
Date: Tue, 22 Aug 2006 17:58:58 -0700
Subject: [Tutor] Low level socket and threading code in python in
	HUGEwebsites -
In-Reply-To: <20060818082753.75918.qmail@web55907.mail.re3.yahoo.com>
References: <004101c6c23f$730fc7a0$0201a8c0@XPpro>
	<20060818082753.75918.qmail@web55907.mail.re3.yahoo.com>
Message-ID: <78b3a9580608221758m3e1e7765n8b4f7c961bbeb3ea@mail.gmail.com>

On 8/18/06, anil maran <anilmrn at yahoo.com> wrote:
> thanks alan it is very enlightening
> can one of you guys who have experience building sites
> such as yahoo mail and stuff, explain what parts of a
> webserver needs to be multithreaded
>
> > > Because of the low-level socket and threading code
> > we had to write,
> > >
> > > I would imagine that they aren't just using a
> > database.
> > > most of the "low level socket stuff" I've seen is
> > about setting
> > > timeouts and doing Async IO.


even way back then, yahoo!mail was created on a similar platform as
most web-based applications are now:  apache (w/appropriate modules)
and a pool of child threads that captured incoming HTTP requests and
serviced them in an async manner.

we had std socket communication but no database access at all; none of
the code was threaded either... just apache.  it sounds relatively
simple, and in our case, it was from this architectural point-of-view.

the complexity was all in the infrastructure, i.e., managing all of
the servers on all of the networks, load-balancing, arranging the
outgoing and incoming SMTP, refreshing DNS MX records, all of the
users (old and new), user registration, and of course, the hard disks
where everyone's mail is stored. again, these things aren't special...
save for the mail-only stuff.  it's just a web app! :-)

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

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

From broek at cc.umanitoba.ca  Wed Aug 23 04:16:05 2006
From: broek at cc.umanitoba.ca (Brian van den Broek)
Date: Tue, 22 Aug 2006 22:16:05 -0400
Subject: [Tutor] [OT] Re:  Limiting Characters
In-Reply-To: <44EA0E0B.6080001@gmail.com>
References: <44e9eb3e.2f318229.508c.ffffa815@mx.gmail.com>
	<44EA0E0B.6080001@gmail.com>
Message-ID: <44EBBA65.5050205@cc.umanitoba.ca>

Luke Paireepinart said unto the world upon 21/08/06 03:48 PM:

<snip>

> Sort of how my last name is 12 characters long, but on some apps that 
> only have a 12 character array (with the actual length being 11 because
> of the null terminator)  the last letter of my name gets truncated.  
> This doesn't happen anymore, but I used to have everyone calling me
> 'paireepinar' because that's what was in the computer so they believed 
> it.  Stupid old programs :)


Hi all,

I've noticed fewer programs stymied by length, though paper forms with
their boxes for each letter still suck.

There are, however, quite a few programs in the wild that, suffused
with Anglo-Saxon assumptions, refuse to admit that a surname might
just possibly commence with a lower case letter or contain spaces (the
horror!) Indeed, my current email address was auto assigned by
software that gives you your last name as your user name, except when
it doesn't ;-)

Brian van den Broek



From lavendula6654 at yahoo.com  Wed Aug 23 05:43:22 2006
From: lavendula6654 at yahoo.com (Elaine)
Date: Tue, 22 Aug 2006 20:43:22 -0700 (PDT)
Subject: [Tutor] How to teach Python
In-Reply-To: <44DE82A1.3000903@alum.rpi.edu>
Message-ID: <20060823034322.22616.qmail@web31710.mail.mud.yahoo.com>

Thanks to everyone for your helpful answers!

-Elaine

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

From emman_l at yahoo.com  Wed Aug 23 05:42:09 2006
From: emman_l at yahoo.com (emman uel)
Date: Tue, 22 Aug 2006 20:42:09 -0700 (PDT)
Subject: [Tutor] How to use
Message-ID: <20060823034209.9495.qmail@web55907.mail.re3.yahoo.com>

How to use this program?
 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060822/6077c8df/attachment.html 

From rdm at rcblue.com  Wed Aug 23 07:04:01 2006
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 22 Aug 2006 22:04:01 -0700
Subject: [Tutor] How to wrap this line of code?
Message-ID: <7.0.1.0.2.20060822215017.01f9ec80@rcblue.com>

I have this long print statement in a script:

print "Initial integer of first sequence with number of terms of %d 
or more was %s  (%d)" % (length, intCommas(n_for_max_c), n_for_max_c)

It's one line of code, and too long. How can I wrap it so that it is 
written in the code as 2 lines?

(I hope I've phrased the question correctly..)

Thanks,

Dick Moores
rdm at rcblue.com


From bgailer at alum.rpi.edu  Wed Aug 23 08:10:31 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 22 Aug 2006 23:10:31 -0700
Subject: [Tutor] How to wrap this line of code?
In-Reply-To: <7.0.1.0.2.20060822215017.01f9ec80@rcblue.com>
References: <7.0.1.0.2.20060822215017.01f9ec80@rcblue.com>
Message-ID: <44EBF157.6080309@alum.rpi.edu>

Dick Moores wrote:
> I have this long print statement in a script:
>
> print "Initial integer of first sequence with number of terms of %d 
> or more was %s  (%d)" % (length, intCommas(n_for_max_c), n_for_max_c)
>
> It's one line of code, and too long. How can I wrap it so that it is 
> written in the code as 2 lines?
>   
At least either of the following:

print "Initial integer of first sequence with number of terms of %d \
or more was %s  (%d)" % (length, intCommas(n_for_max_c), n_for_max_c)

print "Initial integer of first sequence with number of terms of %d",
print "or more was %s  (%d)" % (length, intCommas(n_for_max_c), n_for_max_c)


-- 
Bob Gailer
510-978-4454


From rdm at rcblue.com  Wed Aug 23 08:41:20 2006
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 22 Aug 2006 23:41:20 -0700
Subject: [Tutor] How to wrap this line of code?
In-Reply-To: <44EBF157.6080309@alum.rpi.edu>
References: <7.0.1.0.2.20060822215017.01f9ec80@rcblue.com>
	<44EBF157.6080309@alum.rpi.edu>
Message-ID: <7.0.1.0.2.20060822232914.020c6ad0@rcblue.com>

At 11:10 PM 8/22/2006, Bob Gailer wrote:
>Dick Moores wrote:
>>I have this long print statement in a script:
>>
>>print "Initial integer of first sequence with number of terms of %d 
>>or more was %s  (%d)" % (length, intCommas(n_for_max_c), n_for_max_c)
>>
>>It's one line of code, and too long. How can I wrap it so that it 
>>is written in the code as 2 lines?
>>
>At least either of the following:
>
>print "Initial integer of first sequence with number of terms of %d \
>or more was %s  (%d)" % (length, intCommas(n_for_max_c), n_for_max_c)

Thanks! That's the one I was trying to remember.

>print "Initial integer of first sequence with number of terms of %d",
>print "or more was %s  (%d)" % (length, intCommas(n_for_max_c), n_for_max_c)

That first line produces the error, "TypeError: int argument 
required". Maybe this is what you meant?:

print "Initial integer of first sequence with number of terms of",
print "%d or more was %s  (%d)" % (length, intCommas(n_for_max_c), n_for_max_c)

Thanks very much,

Dick Moores




From bgailer at alum.rpi.edu  Wed Aug 23 08:58:19 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 22 Aug 2006 23:58:19 -0700
Subject: [Tutor] How to wrap this line of code?
In-Reply-To: <7.0.1.0.2.20060822232914.020c6ad0@rcblue.com>
References: <7.0.1.0.2.20060822215017.01f9ec80@rcblue.com>	<44EBF157.6080309@alum.rpi.edu>
	<7.0.1.0.2.20060822232914.020c6ad0@rcblue.com>
Message-ID: <44EBFC8B.9080902@alum.rpi.edu>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060822/95bc0d15/attachment.html 

From alan.gauld at btinternet.com  Wed Aug 23 09:40:37 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 23 Aug 2006 08:40:37 +0100
Subject: [Tutor] How to use
References: <20060823034209.9495.qmail@web55907.mail.re3.yahoo.com>
Message-ID: <ech0pm$dvl$1@sea.gmane.org>

"emman uel" <emman_l at yahoo.com> wrote
>How to use this program?

Which program?
I assume since you wrote to the Pyhon tutor mailing list
you mean some aspect of Python?

Do you mean the installer that you download from the web site?
- just double click and it will run and install Python on your system.

Do you mean the Python interpreter that is installed after you run the 
installer?
- read any of the tutorials linked from the python page.
  I assume from your question that you are not already
  a programmer in another language so I'll suggest the
  non programmers tutorials found here:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Or do you mean something else?

When you post messages please be as specific as possible,
we try to help but we are not mind readers.

Regards,

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



From alan.gauld at btinternet.com  Wed Aug 23 09:48:47 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 23 Aug 2006 08:48:47 +0100
Subject: [Tutor] How to wrap this line of code?
References: <7.0.1.0.2.20060822215017.01f9ec80@rcblue.com>
Message-ID: <ech191$fer$1@sea.gmane.org>


"Dick Moores" <rdm at rcblue.com> wrote
>I have this long print statement in a script:
>
> print "Initial integer of first sequence with number of terms of %d
> or more was %s  (%d)" % (length, intCommas(n_for_max_c), 
> n_for_max_c)
>
> It's one line of code, and too long. How can I wrap it so that it is
> written in the code as 2 lines?

Bob has answered the specific but here's another thing to consider:

Since its too long for your code its probably too long for your
display too, so think about where you would like the line break
to be on the final print. Put in a newline character there and
put the line break there.

Alternatively use triple quoting to format the string nicely and
then use the variable in the print statement:

longstr = """
Initial integer of first sequence with
number of terms of %d or more was %s  (%d)
"""

print longstr % (length, intCommas(n_for_max_c), n_for_max_c)

HTH,


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



From nimrodx at slingshot.co.nz  Wed Aug 23 13:52:08 2006
From: nimrodx at slingshot.co.nz (nimrodx)
Date: Wed, 23 Aug 2006 21:52:08 +1000
Subject: [Tutor] [whitelist] Re:  os.path.walk
In-Reply-To: <002301c6c604$ae229a70$0201a8c0@XPpro>
References: <44EAF1AF.8080209@slingshot.co.nz> <44EAE854.7020607@tds.net>
	<002301c6c604$ae229a70$0201a8c0@XPpro>
Message-ID: <44EC4168.7070800@slingshot.co.nz>

Thanks guys,

I will have a go at both of the methods.

Matt
Alan Gauld wrote:
>> Yes, that is the right way to do it and it will work fine. Something 
>> like
>>
>> class Walker(object):
>>  def walk(self, base):
>>    os.path.walk(base, self.callback, None)
>>     
>
>   
>> What happens is, when Python looks up self.callback it converts the 
>> method to a "bound method".
>>     
>
> Aargh! I should have remembered that. No need for lambdas here.
> Apologies...
>
>   
>> But, if you are using a recent version of Python (2.3 or greater) 
>> you should look at os.walk(), it is easier to use than 
>> os.path.walk().
>>     
>
> But I did suggest that too :-)
>
> Alan G.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From rdm at rcblue.com  Wed Aug 23 11:16:34 2006
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 23 Aug 2006 02:16:34 -0700
Subject: [Tutor] How to wrap this line of code?
In-Reply-To: <ech191$fer$1@sea.gmane.org>
References: <7.0.1.0.2.20060822215017.01f9ec80@rcblue.com>
	<ech191$fer$1@sea.gmane.org>
Message-ID: <7.0.1.0.2.20060823021327.05bfd700@rcblue.com>

At 12:48 AM 8/23/2006, Alan Gauld wrote:
>  here's another thing to consider:
>
>Since its too long for your code its probably too long for your
>display too, so think about where you would like the line break
>to be on the final print. Put in a newline character there and
>put the line break there.
>
>Alternatively use triple quoting to format the string nicely and
>then use the variable in the print statement:
>
>longstr = """
>Initial integer of first sequence with
>number of terms of %d or more was %s  (%d)
>"""
>
>print longstr % (length, intCommas(n_for_max_c), n_for_max_c)

Thanks for both those great ideas!

Dick Moores




From juhasz.jani at freemail.hu  Wed Aug 23 08:05:13 2006
From: juhasz.jani at freemail.hu (=?ISO-8859-2?Q?Juh=E1sz_J=E1nos?=)
Date: Wed, 23 Aug 2006 08:05:13 +0200 (CEST)
Subject: [Tutor]  banners
Message-ID: <freemail.20060723080513.88121@fm13.freemail.hu>

Josip wrote:
>>Write a Python program that  spells out 
>>your name or nickname using special characters.


I just played about this exercise and it has to be about spelling and not 
about hardcoding, as It is more interestig to join banner characters into 
the same line.


DotMap = { 'P' : ('PPP   ','P  P  ','PPP   ','P     ','P     '),
           'Y' : ('Y   Y ',' Y Y  ','  Y   ','  Y   ','  Y   '),
           'T' : ('TTTTT ','  T   ','  T   ','  T   ','  T   '),
           'H' : ('H   H ','H   H ','HHHHH ','H   H ','H   H '),
           'O' : (' OOO  ','O   O ','O   O ','O   O ',' OOO  '),
           'N' : ('N   N ','NN  N ','N N N ','N  NN ','N   N '),
           ' ' : ('      ','      ','      ','      ','      ',)
           }

DotLineNum = 5

def PrintBanner(Banner):
    for i in range(DotLineNum):
        for Char in Banner:
            print DotMap[Char][i],
        print ''

def MakeBanner(Banner):
    return '\n'.join([  
             ' '.join([  
                 DotMap[c][i] # Horizontal segment of char
                 for c in Banner
             ]) # Connected as line
             for i in range(DotLineNum)
            ]) # Connected as string

print ''
ShowBanner('PYTHON')
print ''
print MakeBanner('HY PYTHON')


Janos Juhasz

?rje el az ?ll?skeres?ket munkaid?ben! http://allas.origo.hu



From bgailer at alum.rpi.edu  Wed Aug 23 19:28:59 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 23 Aug 2006 10:28:59 -0700
Subject: [Tutor] banners
In-Reply-To: <freemail.20060723080513.88121@fm13.freemail.hu>
References: <freemail.20060723080513.88121@fm13.freemail.hu>
Message-ID: <44EC905B.2060906@alum.rpi.edu>

Consider:

charmap = """
  A   BBB    CCC   DDDD   etc...
 A A  B  B  C   C  D   D
A   A BBB   C      D   D
AAAAA B  B  C   C  D   D
A   A BBB    CCC   DDDD
"""

Which lets you enter each letter the way you want it to look. No need to 
laboriously translate that by hand into tuples. Let the computer do that 
for you. So now the challenge is to write the Python program that does 
that translation for you.

Also consider what happens when the small letters that form the large 
letters are not the same as the letter they form:

SSSS  P   P AAAAA M   M  etc...
S   S  P P    A   M   M
SSSS    P     A   MMMMM
S       P     A   M   M
S       P     A   M   M

--  
Bob Gailer
510-978-4454


From bgailer at alum.rpi.edu  Wed Aug 23 19:31:17 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 23 Aug 2006 10:31:17 -0700
Subject: [Tutor] How to wrap this line of code?
In-Reply-To: <7.0.1.0.2.20060823021327.05bfd700@rcblue.com>
References: <7.0.1.0.2.20060822215017.01f9ec80@rcblue.com>	<ech191$fer$1@sea.gmane.org>
	<7.0.1.0.2.20060823021327.05bfd700@rcblue.com>
Message-ID: <44EC90E5.1030904@alum.rpi.edu>

Dick Moores wrote:
> At 12:48 AM 8/23/2006, Alan Gauld wrote:
>   
>>  here's another thing to consider:
>>
>> Since its too long for your code its probably too long for your
>> display too, so think about where you would like the line break
>> to be on the final print. Put in a newline character there and
>> put the line break there.
>>
>> Alternatively use triple quoting to format the string nicely and
>> then use the variable in the print statement:
>>
>> longstr = """
>> Initial integer of first sequence with
>> number of terms of %d or more was %s  (%d)
>> """
>>
>> print longstr % (length, intCommas(n_for_max_c), n_for_max_c)
>>     
And remember that triple quoted strings include newline characters.
>
> Thanks for both those great ideas!
>
> Dick Moores
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454


From flightofpenguins at gmail.com  Wed Aug 23 21:14:52 2006
From: flightofpenguins at gmail.com (travis mcgee)
Date: Wed, 23 Aug 2006 15:14:52 -0400
Subject: [Tutor] Adding the current working directory to the Windows path
Message-ID: <5371467f0608231214g6a4eb01cw91d53d81a776efd7@mail.gmail.com>

Is there a simple way to append the os.getcwd() to the windows path
statement?  I've tried variations of

def createDirectory(self):
        os.system('PATH %%PATH%%;%s;'%(here)) # here = os.getcwd()

but it doesn't seem to work.  I don't get an error in IDLE, but if I open a
command prompt, the path doesn't change.  I've googled around for a clue and
looked through the documentation, but alas, I've had no luck.

Can anyone save me from the pain of continuing to pound my head against the
keyboard?

Thanks,

Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060823/829fb38e/attachment.htm 

From carroll at tjc.com  Wed Aug 23 22:11:49 2006
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 23 Aug 2006 13:11:49 -0700 (PDT)
Subject: [Tutor] Adding the current working directory to the Windows path
In-Reply-To: <5371467f0608231214g6a4eb01cw91d53d81a776efd7@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0608231258100.11463-100000@violet.rahul.net>

On Wed, 23 Aug 2006, travis mcgee wrote:

> Is there a simple way to append the os.getcwd() to the windows path
> statement?  I've tried variations of
> 
> def createDirectory(self):
>         os.system('PATH %%PATH%%;%s;'%(here)) # here = os.getcwd()
> 
> but it doesn't seem to work.  I don't get an error in IDLE, but if I open a
> command prompt, the path doesn't change.  I've googled around for a clue and
> looked through the documentation, but alas, I've had no luck.

First, this is a little bit outside my expertise, so I might be talking 
out my sleeve here.

I believe that modifications to the PATH system variable only modify the 
variable in the process making the modification, and probably processes 
spawned by that process.  

You can demonstrate this by opening two DOS windows.  Enter the command
"PATH" in both, and note they're the same.  Now, in one, enter the command
"PATH C:\"; then in both, enter the command "PATH" again.  You'll see that
only one has changed; the change in one session did nothing to the path in
the other.

I believe that the path for a new process is taken from the registry, in 
particular from 
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path

If you'd like a new process to use a new path, that's what I think you 
need to change; but it would apply to all new processes created 
thereafter.


From john at fouhy.net  Wed Aug 23 23:15:23 2006
From: john at fouhy.net (John Fouhy)
Date: Thu, 24 Aug 2006 09:15:23 +1200
Subject: [Tutor] banners
In-Reply-To: <freemail.20060723080513.88121@fm13.freemail.hu>
References: <freemail.20060723080513.88121@fm13.freemail.hu>
Message-ID: <5e58f2e40608231415m3b682208ga22250ceb71bd394@mail.gmail.com>

On 23/08/06, Juh?sz J?nos <juhasz.jani at freemail.hu> wrote:
> I just played about this exercise and it has to be about spelling and not
> about hardcoding, as It is more interestig to join banner characters into
> the same line.

I had a brief think about that as well.  I think if I tried to code
it, my approach would be something like:

class Letter(object):
    def __init__(self, letter):
        # convert letter into rows of characters, somehow.
        # end up with something like:
        self.rows = ['#####', '  #  ', '  #  ', '# #  ', ' ##  ']

    def getWidth(self):
        return max(len(s) for s in self.rows)

    def getRow(self, i):
        return self.rows[i]

Then to print a string:

s = 'John Fouhy'
letters = [Letter(c) for c in s]

for i in range(HEIGHT):
    for letter in letters:
        print '%*s' % (letter.getWidth(), letter.getRow(i)),
    print

Undecided how to map from a character 'c' to a Letter, but Bob's idea
looks good.  If you drew each letter using the appropriate character
then you could automatically derive your dictionary keys, and still
replace the character by '*' if you wanted.  Letter height HEIGHT is a
constant.

And obviously, you would need to do a bit more work to handle word wrapping.

-- 
John.

From falcon3166 at hotmail.com  Thu Aug 24 00:19:25 2006
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Wed, 23 Aug 2006 16:19:25 -0600
Subject: [Tutor] What's the invalid syntax?
Message-ID: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>

What's the invalid syntax in the following code?

# Hurkle Hunt
# This program is a game where you have to find a hurkle that the computer hides in a grid.
# Originally in Computer World pg. 70

import random

print "Hunt the Hurkle"
print
while 1:
    ans = raw_input("Do you want to play a game? Type Y to play, any other letter to quit.")
    while ans == "y" | ans == "Y":
        E = random.choice(range(9))
        N = random.choice(range(9))
        k = 1
        while k <= 5:
            print "Guess ", %d1.0, "."(k)
            X = int(raw_input("East Guess: "))
            Y = int(raw_input("North Guess: "))
            if X > E & Y == N:
                print "Go West"
                k = k + 1
            elif X > E & Y > N:
                print "Go SouthWest"
                k = k + 1
            elif X > E & Y < N:
                print "Go NorthWest"
                k = k + 1
            elif X == E & Y > N:
                print "Go South"
                k = k + 1
            elif X == E & Y < N:
                print "Go North"
                k = k + 1
            elif X < E & Y == N:
                print "Go East"
                k = k + 1
            elif X < E & Y > N:
                print "Go SouthEast"
                k = k + 1
            elif X < E & Y < N:
                print "Go NorthEast"
                k = k + 1
            else:
                print "Congrats! You found the hurkle in", %d1.0, " guesses!" (k)
                break
        else:
            print "You didn't find the hurkle in 5 tries! It was at: ", E, ",", N
            break
    else:
        break
    print "Goodbye!"
    break

Thanks!
Nathan Pinno
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060823/05dc0395/attachment.html 

From john at fouhy.net  Thu Aug 24 00:38:10 2006
From: john at fouhy.net (John Fouhy)
Date: Thu, 24 Aug 2006 10:38:10 +1200
Subject: [Tutor] What's the invalid syntax?
In-Reply-To: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>
References: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>
Message-ID: <5e58f2e40608231538i371fbe43o107a1860d3af1d9d@mail.gmail.com>

What does the python interpreter tell you when you run the code?

-- 
John.

From alan.gauld at btinternet.com  Thu Aug 24 00:40:23 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 23 Aug 2006 23:40:23 +0100
Subject: [Tutor] Adding the current working directory to the Windows path
References: <5371467f0608231214g6a4eb01cw91d53d81a776efd7@mail.gmail.com>
Message-ID: <ecilgp$9ek$1@sea.gmane.org>

> Is there a simple way to append the os.getcwd() to the windows path
> statement?  I've tried variations of
> 
> def createDirectory(self):
>        os.system('PATH %%PATH%%;%s;'%(here)) # here = os.getcwd()
> 
> but it doesn't seem to work.  

PATH is an environment variable and therefore changing it only 
affects the current process environment. You need to change it 
at source which used to be in AUTOEXEC.BAT but I don't think 
that is the preferred place in Win2K/XP.

I'm sure there will be a registry setting somewhere and a hunt 
on MSDN will probably unearth it.

To write to the registry I usually use the WSH Shell object's
RegWrite() method. But there are raw API calls too.

Finally, ISTR that Windows actually changes the Environment 
globally via the os.putenv() call, it might be worth a try before 
messing with direct registry access!

Alan G.


From john at fouhy.net  Thu Aug 24 01:11:36 2006
From: john at fouhy.net (John Fouhy)
Date: Thu, 24 Aug 2006 11:11:36 +1200
Subject: [Tutor] Adding the current working directory to the Windows path
In-Reply-To: <ecilgp$9ek$1@sea.gmane.org>
References: <5371467f0608231214g6a4eb01cw91d53d81a776efd7@mail.gmail.com>
	<ecilgp$9ek$1@sea.gmane.org>
Message-ID: <5e58f2e40608231611x78e23ab5iafb6d3d2f2ebe2e3@mail.gmail.com>

On 24/08/06, Alan Gauld <alan.gauld at btinternet.com> wrote:
> PATH is an environment variable and therefore changing it only
> affects the current process environment. You need to change it
> at source which used to be in AUTOEXEC.BAT but I don't think
> that is the preferred place in Win2K/XP.

To change the path in modern Microsoft Windows:

Right-click on "My Computer" (on the desktop or in Explorer), and
select "Properties".  Click on the "Advanced" tab.  Click the
"Environment variables" button.  Find "Path" in the System variables
list control.  Click "Edit" and make the changes you want...

Remember the days when information like this was actually _documented_? :-)

-- 
John.

From bgailer at alum.rpi.edu  Thu Aug 24 02:20:51 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 23 Aug 2006 17:20:51 -0700
Subject: [Tutor] What's the invalid syntax?
In-Reply-To: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>
References: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>
Message-ID: <44ECF0E3.7040708@alum.rpi.edu>

Nathan Pinno wrote:
> What's the invalid syntax in the following code?
Is this a test? Do you want to see how smart we are? Or are you really 
trying to find and correct the problems? If the latter please OH please 
do as we have requested MANY TIMES - post the traceback.

I'm also concerned, considering the progress you've made in 
understanding Python, that this program should stump you. To my eye 
there are several syntax errors that stand out like a sore thumb.

Please look at the traceback, notice which line it complains about, then 
look at each piece of that line to see whether is is a valid Python element.

Aside from all of that I think this is a pretty poor example of 
programming. The use if bitwise operators instead of boolean is not 
wrong, but could be misleading or give incorrect results in other 
situations. There are no user input checks to reject nicely non-integer 
input. There are statements that can be factored out of the loop.
>  
> # Hurkle Hunt
> # This program is a game where you have to find a hurkle that the 
> computer hides in a grid.
> # Originally in Computer World pg. 70
>  
> import random
>  
> print "Hunt the Hurkle"
> print
> while 1:
>     ans = raw_input("Do you want to play a game? Type Y to play, any 
> other letter to quit.")
>     while ans == "y" | ans == "Y":
>         E = random.choice(range(9))
>         N = random.choice(range(9))
>         k = 1
>         while k <= 5:
>             print "Guess ", %d1.0, "."(k)
>             X = int(raw_input("East Guess: "))
>             Y = int(raw_input("North Guess: "))
>             if X > E & Y == N:
>                 print "Go West"
>                 k = k + 1
>             elif X > E & Y > N:
>                 print "Go SouthWest"
>                 k = k + 1
>             elif X > E & Y < N:
>                 print "Go NorthWest"
>                 k = k + 1
>             elif X == E & Y > N:
>                 print "Go South"
>                 k = k + 1
>             elif X == E & Y < N:
>                 print "Go North"
>                 k = k + 1
>             elif X < E & Y == N:
>                 print "Go East"
>                 k = k + 1
>             elif X < E & Y > N:
>                 print "Go SouthEast"
>                 k = k + 1
>             elif X < E & Y < N:
>                 print "Go NorthEast"
>                 k = k + 1
>             else:
>                 print "Congrats! You found the hurkle in", %d1.0, " 
> guesses!" (k)
>                 break
>         else:
>             print "You didn't find the hurkle in 5 tries! It was at: 
> ", E, ",", N
>             break
>     else:
>         break
>     print "Goodbye!"
>     break
> Thanks!
> Nathan Pinno
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


-- 
Bob Gailer
510-978-4454


From alan.gauld at freenet.co.uk  Thu Aug 24 06:10:43 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 24 Aug 2006 05:10:43 +0100
Subject: [Tutor] What's the invalid syntax?
References: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>
Message-ID: <002201c6c733$4509fda0$0201a8c0@XPpro>


> What's the invalid syntax in the following code?

Dunno, Where does Python think it is?
In other words what does the error message/IDE  say?
Give us a clue....

Alan G.


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


# Hurkle Hunt
# This program is a game where you have to find a hurkle that the 
computer hides in a grid.
# Originally in Computer World pg. 70

import random

print "Hunt the Hurkle"
print
while 1:
    ans = raw_input("Do you want to play a game? Type Y to play, any 
other letter to quit.")
    while ans == "y" | ans == "Y":
        E = random.choice(range(9))
        N = random.choice(range(9))
        k = 1
        while k <= 5:
            print "Guess ", %d1.0, "."(k)
            X = int(raw_input("East Guess: "))
            Y = int(raw_input("North Guess: "))
            if X > E & Y == N:
                print "Go West"
                k = k + 1
            elif X > E & Y > N:
                print "Go SouthWest"
                k = k + 1
            elif X > E & Y < N:
                print "Go NorthWest"
                k = k + 1
            elif X == E & Y > N:
                print "Go South"
                k = k + 1
            elif X == E & Y < N:
                print "Go North"
                k = k + 1
            elif X < E & Y == N:
                print "Go East"
                k = k + 1
            elif X < E & Y > N:
                print "Go SouthEast"
                k = k + 1
            elif X < E & Y < N:
                print "Go NorthEast"
                k = k + 1
            else:
                print "Congrats! You found the hurkle in", %d1.0, " 
guesses!" (k)
                break
        else:
            print "You didn't find the hurkle in 5 tries! It was at: 
", E, ",", N
            break
    else:
        break
    print "Goodbye!"
    break

Thanks!
Nathan Pinno 


From falcon3166 at hotmail.com  Thu Aug 24 06:27:13 2006
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Wed, 23 Aug 2006 22:27:13 -0600
Subject: [Tutor] What's the invalid syntax?
References: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>
	<002201c6c733$4509fda0$0201a8c0@XPpro>
Message-ID: <BAY106-DAV10E2062D236407B930ED88C4440@phx.gbl>

Sorry, but it only showed a text-box with the message "Invalid syntax!", 
then highlighted the %.

HTH,
Nathan Pinno
----- Original Message ----- 
From: "Alan Gauld" <alan.gauld at freenet.co.uk>
To: "Nathan Pinno" <falcon3166 at hotmail.com>; "Tutor mailing list" 
<tutor at python.org>
Sent: Wednesday, August 23, 2006 10:10 PM
Subject: Re: [Tutor] What's the invalid syntax?


>
>> What's the invalid syntax in the following code?
>
> Dunno, Where does Python think it is?
> In other words what does the error message/IDE  say?
> Give us a clue....
>
> Alan G.
>
>
> ########################
>
>
> # Hurkle Hunt
> # This program is a game where you have to find a hurkle that the computer 
> hides in a grid.
> # Originally in Computer World pg. 70
>
> import random
>
> print "Hunt the Hurkle"
> print
> while 1:
>    ans = raw_input("Do you want to play a game? Type Y to play, any other 
> letter to quit.")
>    while ans == "y" | ans == "Y":
>        E = random.choice(range(9))
>        N = random.choice(range(9))
>        k = 1
>        while k <= 5:
>            print "Guess ", %d1.0, "."(k)
>            X = int(raw_input("East Guess: "))
>            Y = int(raw_input("North Guess: "))
>            if X > E & Y == N:
>                print "Go West"
>                k = k + 1
>            elif X > E & Y > N:
>                print "Go SouthWest"
>                k = k + 1
>            elif X > E & Y < N:
>                print "Go NorthWest"
>                k = k + 1
>            elif X == E & Y > N:
>                print "Go South"
>                k = k + 1
>            elif X == E & Y < N:
>                print "Go North"
>                k = k + 1
>            elif X < E & Y == N:
>                print "Go East"
>                k = k + 1
>            elif X < E & Y > N:
>                print "Go SouthEast"
>                k = k + 1
>            elif X < E & Y < N:
>                print "Go NorthEast"
>                k = k + 1
>            else:
>                print "Congrats! You found the hurkle in", %d1.0, " 
> guesses!" (k)
>                break
>        else:
>            print "You didn't find the hurkle in 5 tries! It was at: ", E, 
> ",", N
>            break
>    else:
>        break
>    print "Goodbye!"
>    break
>
> Thanks!
> Nathan Pinno
> 


From john at fouhy.net  Thu Aug 24 06:50:49 2006
From: john at fouhy.net (John Fouhy)
Date: Thu, 24 Aug 2006 16:50:49 +1200
Subject: [Tutor] What's the invalid syntax?
In-Reply-To: <BAY106-DAV10E2062D236407B930ED88C4440@phx.gbl>
References: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>
	<002201c6c733$4509fda0$0201a8c0@XPpro>
	<BAY106-DAV10E2062D236407B930ED88C4440@phx.gbl>
Message-ID: <5e58f2e40608232150h7d1f29f1rf7f6294860c86970@mail.gmail.com>

On 24/08/06, Nathan Pinno <falcon3166 at hotmail.com> wrote:
> Sorry, but it only showed a text-box with the message "Invalid syntax!",
> then highlighted the %.

Ok, so that would be on this line, I guess?

    print "Guess ", %d1.0, "."(k)

Well, that's where the syntax error is, sure enough.  Your editor told
you; you didn't need to ask us.

In order to fix this bug, you need to figure out what you want to
achieve with this line of code, and then look at the documentation or
tutorials to figure out how to write the code correctly.

-- 
John.

From falcon3166 at hotmail.com  Thu Aug 24 07:22:46 2006
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Wed, 23 Aug 2006 23:22:46 -0600
Subject: [Tutor] How do I make Python read a string character by character?
Message-ID: <BAY106-DAV97504C61B5A98C8D7BBD8C4440@phx.gbl>

Hey all,

How do I make Python read a string character by character?

Thanks,
Nathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060823/01676cc5/attachment.htm 

From akashmahajan at gmail.com  Thu Aug 24 08:12:30 2006
From: akashmahajan at gmail.com (Akash)
Date: Thu, 24 Aug 2006 11:42:30 +0530
Subject: [Tutor] How do I make Python read a string character by
	character?
In-Reply-To: <BAY106-DAV97504C61B5A98C8D7BBD8C4440@phx.gbl>
References: <BAY106-DAV97504C61B5A98C8D7BBD8C4440@phx.gbl>
Message-ID: <868b524f0608232312y22dcd5b5y2b89c96099ac620c@mail.gmail.com>

On 8/24/06, Nathan Pinno <falcon3166 at hotmail.com> wrote:
> How do I make Python read a string character by character?

>>> str = 'string'
>>> for i in range(0, len(str)):
...     print str[i]
...
s
t
r
i
n
g


just take care about the indentation.

-- 
regards
akash

From alan.gauld at btinternet.com  Thu Aug 24 06:05:41 2006
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Thu, 24 Aug 2006 05:05:41 +0100 (BST)
Subject: [Tutor] Adding the current working directory to the Windows path
In-Reply-To: <5e58f2e40608231611x78e23ab5iafb6d3d2f2ebe2e3@mail.gmail.com>
Message-ID: <20060824040541.46670.qmail@web86109.mail.ird.yahoo.com>

Hi John,

The OP wants to do it from a Python program.
Thats why I suggested using the registry.

Alan G

John Fouhy <john at fouhy.net> wrote: On 24/08/06, Alan Gauld  wrote:
> PATH is an environment variable and therefore changing it only
> affects the current process environment. You need to change it
> at source which used to be in AUTOEXEC.BAT but I don't think
> that is the preferred place in Win2K/XP.

To change the path in modern Microsoft Windows:

Right-click on "My Computer" (on the desktop or in Explorer), and
select "Properties".  Click on the "Advanced" tab.  Click the
"Environment variables" button.  Find "Path" in the System variables
list control.  Click "Edit" and make the changes you want...

Remember the days when information like this was actually _documented_? :-)

-- 
John.


 		
---------------------------------
 Try the all-new Yahoo! Mail . "The New Version is radically easier to use" ? The Wall Street Journal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060824/76eac321/attachment.html 

From kylibine at gmail.com  Thu Aug 24 13:58:06 2006
From: kylibine at gmail.com (kulibin da-da!)
Date: Thu, 24 Aug 2006 14:58:06 +0300
Subject: [Tutor] how to set time limit before downloading file
Message-ID: <5e36bcda0608240458x432d52bfs3897084ca6a09c78@mail.gmail.com>

I had to download some files.

 Using the code below I could download almost all I had to download, but I
 have a problem with 'http://18wheels.wz.cz/csszengarden/back-con.jpg'

 This is my code for downloading
'http://18wheels.wz.cz/csszengarden/back-con.jpg'

# -*- coding: windows-1251 -*-
import re, os

import urllib


def download_file_using_urlopen (url, out_dir=''):
    data = []
    if not os.path.isdir(out_dir) and out_dir != '':
        os.mkdir(out_dir)

    filename = os.path.join(out_dir, os.path.basename(url))

    f = open(filename, "wb")
    print "%s -->" % filename
    r = urllib.urlopen(url)
    print 'info:\t', r.info()
    while 1:
        d = r.read(1024)
        if not d: break
        print '.',
        data.append(d)
    data = ''.join(data)
    f.write(data)
    f.close()


urls = ['http://18wheels.wz.cz/csszengarden/back-con.jpg']
for url in urls:
    out_dir= 'out'
    print url
    data = download_file_using_urlopen(url, out_dir)
    print '\n'*3



And the problem is that the script sleeps for some hours. And thats
all - no data is read.

 Can you show me what is wrong and
1. how to set time for file downloading after what it will ignore this
file and start working with next file.
2. how to set time for every "d = r.read(1024)" after what script will
ignore this file and start working with next file.


 Thanks in advance.

From vincent.gulinao at gmail.com  Thu Aug 24 14:55:08 2006
From: vincent.gulinao at gmail.com (Vincent Gulinao)
Date: Thu, 24 Aug 2006 20:55:08 +0800
Subject: [Tutor] Displaying in columnar / tabular form
Message-ID: <fcc3e6170608240555t51512cbcm462cf91e9568166a@mail.gmail.com>

Anyone knows a neat way of displaying output in columnar/tabular form?

Say you have a list with both dictionary and string members; you want to
print the data, dictionary being one element per line, and the string on the
next "column" aligned on the first element of the dictionary, or something
like that.


 TIA.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060824/e3976202/attachment.html 

From kent37 at tds.net  Thu Aug 24 14:58:01 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 24 Aug 2006 08:58:01 -0400
Subject: [Tutor] how to set time limit before downloading file
In-Reply-To: <5e36bcda0608240458x432d52bfs3897084ca6a09c78@mail.gmail.com>
References: <5e36bcda0608240458x432d52bfs3897084ca6a09c78@mail.gmail.com>
Message-ID: <44EDA259.7020205@tds.net>

kulibin da-da! wrote:
> I had to download some files.
>
>  Using the code below I could download almost all I had to download, but I
>  have a problem with 'http://18wheels.wz.cz/csszengarden/back-con.jpg'
>
> And the problem is that the script sleeps for some hours. And thats
> all - no data is read.
>
>  Can you show me what is wrong and
> 1. how to set time for file downloading after what it will ignore this
> file and start working with next file.
>   
In your loop you could keep track of the total download time and abort 
if it is too long. See time.time().
> 2. how to set time for every "d = r.read(1024)" after what script will
> ignore this file and start working with next file.
>   
Try calling socket.setdefaulttimeout() before any of your network 
operations start.

Kent


From kent37 at tds.net  Thu Aug 24 15:12:41 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 24 Aug 2006 09:12:41 -0400
Subject: [Tutor] Displaying in columnar / tabular form
In-Reply-To: <fcc3e6170608240555t51512cbcm462cf91e9568166a@mail.gmail.com>
References: <fcc3e6170608240555t51512cbcm462cf91e9568166a@mail.gmail.com>
Message-ID: <44EDA5C9.6090502@tds.net>

Vincent Gulinao wrote:
>
> Anyone knows a neat way of displaying output in columnar/tabular form?
>
> Say you have a list with both dictionary and string members; you want 
> to print the data, dictionary being one element per line, and the 
> string on the next "column" aligned on the first element of the 
> dictionary, or something like that.
>

You might like this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662

Another option is to write an HTML file containing a table.

Kent


From kylibine at gmail.com  Thu Aug 24 15:36:53 2006
From: kylibine at gmail.com (kulibin da-da!)
Date: Thu, 24 Aug 2006 16:36:53 +0300
Subject: [Tutor] how to set time limit before downloading file
In-Reply-To: <44EDA259.7020205@tds.net>
References: <5e36bcda0608240458x432d52bfs3897084ca6a09c78@mail.gmail.com>
	<44EDA259.7020205@tds.net>
Message-ID: <5e36bcda0608240636r54c7990bg27507d998bee65c8@mail.gmail.com>

Thanks for your help, Kent - everything is working now :)

> > I had to download some files.
> >
> >  Using the code below I could download almost all I had to download, but I
> >  have a problem with 'http://18wheels.wz.cz/csszengarden/back-con.jpg'
> >
> > And the problem is that the script sleeps for some hours. And thats
> > all - no data is read.
> >
> >  Can you show me what is wrong and
> > 1. how to set time for file downloading after what it will ignore this
> > file and start working with next file.
> >
> In your loop you could keep track of the total download time and abort
> if it is too long. See time.time().
> > 2. how to set time for every "d = r.read(1024)" after what script will
> > ignore this file and start working with next file.
> >
> Try calling socket.setdefaulttimeout() before any of your network
> operations start.

From j.gamman at gmail.com  Thu Aug 24 18:01:20 2006
From: j.gamman at gmail.com (Joe Gamman)
Date: Thu, 24 Aug 2006 17:01:20 +0100
Subject: [Tutor] Query to the tutor mailing list
Message-ID: <7c4cfdc0608240901h1bf7c193g1f0e1e5477ce12d@mail.gmail.com>

hi,
long time lurker, first time poster. i apologise in advance if this has come
up before and i haven't seen it.
i'm interested in learning python purely as an intellectual excercise -
writing small scripts in a 'crossword puzzle per day' kind of thing (i have
a long train commute ;-).
if i get to the point where i can actually do something useful, that would
be nice but would be an emergent property of the puzzles, not the aim
(although with enough 'puzzles', the distinction becomes moot).
i've been lurking and every time i see something that i can have a good
chance of doing, i have a go.  my problem is that with my limited
programming experience (<25 hours), i am quickly out of my depth and
defining my own questions at this level is often an excercise in futility.
Similar with the majority of the tutor issues.

my question is this: would the tutor FAQ have a use for a collection of
excercises/puzzles that could reasonably be expected to be completed in less
than say, 20 mins (a nice sized intellectual chunk for someone that doesn't
code for a day job) for someone with x hours programming experience?
i would suspect that at a certain point (>50 hours?), a newbie would have
the momentum to start teaching themselves via documentation and leveraging
the tutor mailing list.

it's probably hard for the tutors here to remember just how difficult it is
to get that critical mass needed to really start teaching yourself.  an
upside to creating a puzzle FAQ would allow concepts to flow naturally as
the complexity of the problem increases and newbies could share a common
experience curve.  i'm not trying to suggest a one-size-fits-all list, more
of a puzzle-soup where you can wander as your self-learning flows.  i would
imagine designing a nice discreet puzzle to illustrate or challenge a
programming concept might be an enjoyable pass time for some people.  a good
puzzle is one where you know you have a good chance of success - too big a
jump and frustration saps your motivation.

I heartily approve of the python challenge and perhaps more of these would
be a suitable way to do this.  I've tried the cookbook but most of the
problems are beyond me at this stage so i can't self study the code for
hints.
Anyway, would appreciate any comments on the idea.

cheers,
joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060824/5aee54c5/attachment.html 

From nephish at gmail.com  Thu Aug 24 18:21:04 2006
From: nephish at gmail.com (shawn bright)
Date: Thu, 24 Aug 2006 12:21:04 -0400
Subject: [Tutor] prob with 64 encoded email attachement
Message-ID: <384c93600608240921q7368187fx540bc8661a915d7@mail.gmail.com>

hello there,
i am having a bit o trouble being able to read a base64 encoded email
attachement.

here is the script.

import email
import poplib
import base64
import os

email_folder = 'emails/'
mime = "application/octet-stream"

def WriteAttachment(msg):
    for part in msg.walk():
        print part
        if part.get_content_type() == mime:
            name = part.get_filename()
            data = part.get_payload(decode=True)
            email_folder = 'emails/'
            f = file('%s%s'%(email_folder,name),'wb')
            f.write(data)
            f.close()

ms = poplib.POP3('my.mailserver.net')
ms.user('me')
ms.pass_('pass')

msgcount = len(ms.list()[1])
ii = 0
for i in range(msgcount):
    ii+=1
    if ii > 1: break
    response, msg_as_list, size = ms.retr(i+1)
    msg = email.message_from_string('\r\n'.join(msg_as_list))
    WriteAttachment(msg)

dumped_files = os.listdir(email_folder)
i = 0
for d_file in dumped_files:
    i+=1
    base64.decode(open("%s%s" % (email_folder,d_file)), open("out.txt",
"w"))

the issue is when it gets to the part of decoding. The traceback says
binascii.Error: Incorrect Padding.
but i am certain that the info as it is being sent is good.

anyone see where i may be missing it here ?

thanks.

-shawn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060824/6174c0ed/attachment-0001.htm 

From wescpy at gmail.com  Thu Aug 24 20:05:09 2006
From: wescpy at gmail.com (wesley chun)
Date: Thu, 24 Aug 2006 11:05:09 -0700
Subject: [Tutor] Displaying in columnar / tabular form
In-Reply-To: <44EDA5C9.6090502@tds.net>
References: <fcc3e6170608240555t51512cbcm462cf91e9568166a@mail.gmail.com>
	<44EDA5C9.6090502@tds.net>
Message-ID: <78b3a9580608241105s5f79cc9ap91d28d35faf35c9c@mail.gmail.com>

On 8/24/06, Kent Johnson <kent37 at tds.net> wrote:
> Vincent Gulinao wrote:
> >
> > Anyone knows a neat way of displaying output in columnar/tabular form?
>
> You might like this recipe:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662
>
> Another option is to write an HTML file containing a table.


the recipe that kent suggested seems really fully-featured.  for
simpler applications where i just want "to do it myself," i would use
the same string methods that the recipe's code uses: center(),
ljust(), and rjust().

another alternative for external columnar alighment, in addition to
kent's HTML suggestion is to just write it directly into an Excel
spreadsheet (via Win32 libraries) or alternatively, generate a CSV
file that Excel can import.

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

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

From wescpy at gmail.com  Thu Aug 24 20:18:59 2006
From: wescpy at gmail.com (wesley chun)
Date: Thu, 24 Aug 2006 11:18:59 -0700
Subject: [Tutor] how to set time limit before downloading file
In-Reply-To: <5e36bcda0608240458x432d52bfs3897084ca6a09c78@mail.gmail.com>
References: <5e36bcda0608240458x432d52bfs3897084ca6a09c78@mail.gmail.com>
Message-ID: <78b3a9580608241118u45f0d81foe1cfe6fc5ffe747e@mail.gmail.com>

On 8/24/06, kulibin da-da! <kylibine at gmail.com> wrote:
> I had to download some files.
>
>  Using the code below I could download almost all I had to download, but I
>  have a problem
>    :
> r = urllib.urlopen(url)
>    :
> And the problem is that the script sleeps for some hours. And thats
> all - no data is read.


is there a reason why you are using urlopen() instead of
urlretrieve(url, localFile)?  it will download the file for you so you
don't have to do it chunks at a time.  is it because you're working
with an unreliable server where a timeout is required? otherwise yes,
you will have to set a socket timeout to give up on a partial download
if the other side is hanging.

you may also want to consider multithreading this application (using
the threading module). if the individual downloads are not dependent
on each other.  I/O-bound applications are a great use case for Python
MT and will help improve performance. it will allow for multiple
"simultaneous" downloads in parallel and allow it to complete sooner.

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

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

From carroll at tjc.com  Thu Aug 24 20:46:56 2006
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 24 Aug 2006 11:46:56 -0700 (PDT)
Subject: [Tutor] Adding the current working directory to the Windows path
In-Reply-To: <Pine.LNX.4.44.0608231258100.11463-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0608241144520.1626-100000@violet.rahul.net>

On Wed, 23 Aug 2006, Terry Carroll wrote:

> I believe that the path for a new process is taken from the registry, in 
> particular from 
> HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path

More at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/416087


From bgailer at alum.rpi.edu  Thu Aug 24 20:56:13 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu, 24 Aug 2006 11:56:13 -0700
Subject: [Tutor] What's the invalid syntax?
In-Reply-To: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>
References: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>
Message-ID: <44EDF64D.5020500@alum.rpi.edu>

My apology to you, Nathan. When I requested a traceback I did not 
realize you were using an IDE.

But do realize that an IDE reporting a syntax error should point to (in 
some way) to the offending line of code. It's always a good idea to 
examine (as already suggested) that line to attempt to spot the problem.

Have you figured out why it is choking at the %?

-- 
Bob Gailer
510-978-4454


From kylibine at gmail.com  Thu Aug 24 20:56:08 2006
From: kylibine at gmail.com (kulibin da-da!)
Date: Thu, 24 Aug 2006 21:56:08 +0300
Subject: [Tutor] how to set time limit before downloading file
In-Reply-To: <78b3a9580608241118u45f0d81foe1cfe6fc5ffe747e@mail.gmail.com>
References: <5e36bcda0608240458x432d52bfs3897084ca6a09c78@mail.gmail.com>
	<78b3a9580608241118u45f0d81foe1cfe6fc5ffe747e@mail.gmail.com>
Message-ID: <5e36bcda0608241156q59659e0fn5ca961f62d01ebd7@mail.gmail.com>

> > I had to download some files.
> >
> >  Using the code below I could download almost all I had to download, but I
> >  have a problem
> >    :
> > r = urllib.urlopen(url)
> >    :
> > And the problem is that the script sleeps for some hours. And thats
> > all - no data is read.
>
>
> is there a reason why you are using urlopen() instead of
> urlretrieve(url, localFile)?  it will download the file for you so you
> don't have to do it chunks at a time.  is it because you're working
> with an unreliable server where a timeout is required? otherwise yes,
> you will have to set a socket timeout to give up on a partial download
> if the other side is hanging.

I don't use urlretrieve because I have to get more info about all the
files I'm downloading (I need regular downloading of file so if I want
to check the changes in file (reading headers) and after analyzing
changes I'll decide do I have to download that file again or not).
And I need timeout because some of the pages I'am checking often are
inaccessible.

>
> you may also want to consider multithreading this application (using
> the threading module). if the individual downloads are not dependent
> on each other.  I/O-bound applications are a great use case for Python
> MT and will help improve performance. it will allow for multiple
> "simultaneous" downloads in parallel and allow it to complete sooner.

Thanks for advice, multithreading will be in next version of my program :)

From zslevi at sch.bme.hu  Thu Aug 24 22:12:32 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Thu, 24 Aug 2006 22:12:32 +0200
Subject: [Tutor] [Fwd: [Fwd: self-modification]]
In-Reply-To: <002b01c6c605$83ceebb0$0201a8c0@XPpro>
References: <44E9D363.7090108@sch.bme.hu> <44EADC65.3040504@sch.bme.hu>
	<002b01c6c605$83ceebb0$0201a8c0@XPpro>
Message-ID: <44EE0830.8020502@sch.bme.hu>

Alan Gauld wrote:

>
>> Why does the python shell says this:
>>
>>>>> print exec.__doc__
>>>>
>>  File "<stdin>", line 1
>>    print exec.__doc__
>>             ^
>> SyntaxError: invalid syntax
>
>
> exec, like print, is a statement, or command, not a function.
>
> You get the same response if you try
>
>>>> print print.__doc__
>>>
>
> or
>
>>>> help(print)
>>>
>
>> While it works with "eval".
>
>
> eval is a function so has a doc string attached.
>
> Alan G.

Thanks.

From zslevi at sch.bme.hu  Thu Aug 24 22:21:13 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Thu, 24 Aug 2006 22:21:13 +0200
Subject: [Tutor] tkinter events: <B1-Motion>
In-Reply-To: <Pine.LNX.4.64.0608221249580.27647@hkn.eecs.berkeley.edu>
References: <44E9B6E0.3060305@sch.bme.hu>
	<Pine.LNX.4.64.0608221249580.27647@hkn.eecs.berkeley.edu>
Message-ID: <44EE0A39.3070708@sch.bme.hu>

If we're talking about data hiding, let me ask: why Python doesn't 
implement data hiding (I mean 'private' and 'protected')? I consider it 
a very important OOP feature, because that makes OOP different from 
structural programming.

Danny Yoo wrote:

>> def handler(event):
>>     if buttonpressed == 1 :
>>         /#if the mousebutton is pressed and moved, circles should 
>> appear, but they do not/
>>         can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, 
>> fill="orange")
>>     lab.config(text='buttonpressed=' + str(buttonpressed) )
>
>
>
> The variables of functions are normally independent of each other.  
> That is, if I have a function square():
>
> ##############
> def square(x):
>     y = x * x
>     return y
> ##############
>
> and if I have a function that uses square that itself has a 'y' 
> variable, I should not see interference:
>
> ##############
> def test():
>     y = 17
>     print "square of y is", square(y)
>     print "y itself is", y
> ##############
>
> This black-boxing is what allows us to write and reuse functions with 
> reckless abandon: their innards are meant not to interact with one 
> another.  This is a feature that you usually want to have.
>
>
> But for your purposes, you want some controlled form of leakage.  Use 
> 'global' for this purpose by declaring the shared variable at the head 
> of your functions.  Compare the results above to the ones below:
>
> #####################################
> def square(x):
>      global y
>      y = x * x
>      return y
>
> def test():
>     global y
>     y = 17
>     print "square of y is", square(y)
>     print "y itself is", y
> #####################################
>
> There's terse reference material here about global:
>
>     http://www.python.org/doc/ref/global.html#l2h-558
>
> It's idiomatic programming practice to limit the use of 'global' to 
> situations where it's necessary; using it in an uncontrolled way leads 
> to code that's difficult to read or reason with.  There are more 
> sophsticated ways to share variables between functions.  That being 
> said, though, the 'global' mechanism will probably be simplest for 
> your purposes.
>
>
> Good luck to you!



From Mike.Hansen at atmel.com  Thu Aug 24 22:28:39 2006
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 24 Aug 2006 14:28:39 -0600
Subject: [Tutor] tkinter events: <B1-Motion>
Message-ID: <57B026980605A64F9B23484C5659E32E25588D@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Zsiros Levente
> Sent: Thursday, August 24, 2006 2:21 PM
> To: Danny Yoo
> Cc: python tutor
> Subject: Re: [Tutor] tkinter events: <B1-Motion>
> 
> If we're talking about data hiding, let me ask: why Python doesn't 
> implement data hiding (I mean 'private' and 'protected')? I 
> consider it 
> a very important OOP feature, because that makes OOP different from 
> structural programming.
> 

This might explain...

http://pyfaq.infogami.com/tutor-how-do-i-make-public-and-private-attribu
tes-and-methods-in-my-classes

Mike
**********************************************************************************************
IMPORTANT: The contents of this email and any attachments are confidential. They are intended for the 
named recipient(s) only.
If you have received this email in error, please notify the system manager or the sender immediately and do 
not disclose the contents to anyone or make copies thereof.
*** eSafe scanned this email for viruses, vandals, and malicious content. ***
**********************************************************************************************


From john at fouhy.net  Thu Aug 24 23:22:10 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 25 Aug 2006 09:22:10 +1200
Subject: [Tutor] Displaying in columnar / tabular form
In-Reply-To: <fcc3e6170608240555t51512cbcm462cf91e9568166a@mail.gmail.com>
References: <fcc3e6170608240555t51512cbcm462cf91e9568166a@mail.gmail.com>
Message-ID: <5e58f2e40608241422r5ff11e79m4327b4f160c75c34@mail.gmail.com>

On 25/08/06, Vincent Gulinao <vincent.gulinao at gmail.com> wrote:
> Anyone knows a neat way of displaying output in columnar/tabular form?
>
> Say you have a list with both dictionary and string members; you want to
> print the data, dictionary being one element per line, and the string on the
> next "column" aligned on the first element of the dictionary, or something
> like that.

If you want to DIY, have a look at string formatting (ie: the % operator).

I don't quite understand your example, so here's an (untested) example
of my own -- printing a list of strings in a table of 3 columns:

input = [ ... ] # list of strings
WIDTH = 3  # columns in the table
# split input up into tuples, ie: first 3, then next 3, then next 3, etc.
rows = [input[WIDTH*i:WIDTH*i+WIDTH] for i in range(len(input)//WIDTH + 1)]
# get max width of each column
widths = [max([row[i] for row in rows]) for i in range(WIDTH)]

for row in rows:
    for i, s in enumerate(row):
        print '%*s' % (widths[i], s),
    print

The idea is to figure out what goes on each row of the table, then
calculate the maximum width of each column.  Then
    '%*s' % (w, s)
will be the string s, padded to width w.

(I always forget whether it gets padded on the left or on the right,
but you can always reverse it by adding a -: '%-*s'  )

-- 
John.

From john at fouhy.net  Thu Aug 24 23:32:24 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 25 Aug 2006 09:32:24 +1200
Subject: [Tutor] Query to the tutor mailing list
In-Reply-To: <7c4cfdc0608240901h1bf7c193g1f0e1e5477ce12d@mail.gmail.com>
References: <7c4cfdc0608240901h1bf7c193g1f0e1e5477ce12d@mail.gmail.com>
Message-ID: <5e58f2e40608241432p3377a0e4obee320d98cbe956b@mail.gmail.com>

On 25/08/06, Joe Gamman <j.gamman at gmail.com> wrote:
> Anyway, would appreciate any comments on the idea.

It seems like the sort of thing you find in textbooks or "learn to
program" books -- most books of this nature have suitable exercises at
the end of each chapter, or spread throughout each chapter.  Also,
creating good problems seems to me like it would be a difficult thing
to do, without plagiarising existing works.

Have you tried looking at programming books, or online tutorials (eg,
Alan Gauld's?  Or I think "How to think like a computer scientist"
uses python.)?

-- 
John.

From wescpy at gmail.com  Fri Aug 25 00:37:08 2006
From: wescpy at gmail.com (wesley chun)
Date: Thu, 24 Aug 2006 15:37:08 -0700
Subject: [Tutor] Query to the tutor mailing list
In-Reply-To: <5e58f2e40608241432p3377a0e4obee320d98cbe956b@mail.gmail.com>
References: <7c4cfdc0608240901h1bf7c193g1f0e1e5477ce12d@mail.gmail.com>
	<5e58f2e40608241432p3377a0e4obee320d98cbe956b@mail.gmail.com>
Message-ID: <78b3a9580608241537h6ffe4bbbl7d65413b58588236@mail.gmail.com>

On 8/24/06, John Fouhy <john at fouhy.net> wrote:
> On 25/08/06, Joe Gamman <j.gamman at gmail.com> wrote:
> > Anyway, would appreciate any comments on the idea.
>
> It seems like the sort of thing you find in textbooks or "learn to
> program" books -- most books of this nature have suitable exercises at
> the end of each chapter,

joe,

as john has suggested, exercises in Python books are another great way
to get in the "practice" that you desire.

i put a significant number of exercises in "Core Python," some which
take 20-minutes as you had mentioned, but others may take up to 20
hours.  they range from easy all the way to difficult, and some are
game-oriented while most are not.

there are about 260 exercises in the 1st ed., and the upcoming 2nd ed.
will have well over 300.  i believe this is more than any other Python
book out there. hope to be challenging you someday!

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

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

From ph34r_th3_d4rkn3s at hotmail.com  Fri Aug 25 00:50:26 2006
From: ph34r_th3_d4rkn3s at hotmail.com (mike viceano)
Date: Thu, 24 Aug 2006 16:50:26 -0600
Subject: [Tutor] help
Message-ID: <BAY121-F332E2C97E8B923320C3AFDEA440@phx.gbl>

hello i need a little help with a common multiple module i am haveing 
problems with the best i can get it is to show the least common multiple i 
think the problem is eather the and command ot the if command

   # finds common multiples
def nums(a,b): # assigns numbers to a and b
    print "enter range"
    c = input(">")
    both=[]
    e=-1
    f=-1
    kl=[]
    ll=[]
    while e<c:
        e=e+1
        k=a*e
        l=b*e
        print a,"X",e,"=",k,"   ",b,"X",e,"=",l
        kl.append(k)
        ll.append(l)
    while f<c:
        f=f+1
        if f in kl and f in ll:
            both.append(f)
    print both

any help would be great



^_^"  s33 y4

_________________________________________________________________
Call friends with PC-to-PC calling -- FREE   
http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline


From wescpy at gmail.com  Fri Aug 25 01:33:21 2006
From: wescpy at gmail.com (wesley chun)
Date: Thu, 24 Aug 2006 16:33:21 -0700
Subject: [Tutor] help
In-Reply-To: <BAY121-F332E2C97E8B923320C3AFDEA440@phx.gbl>
References: <BAY121-F332E2C97E8B923320C3AFDEA440@phx.gbl>
Message-ID: <78b3a9580608241633k2a56ad7bv21bd320c3997691@mail.gmail.com>

On 8/24/06, mike viceano <ph34r_th3_d4rkn3s at hotmail.com> wrote:
> hello i need a little help with a common multiple module i am haveing
> problems with the best i can get it is to show the least common multiple i
> think the problem is eather the and command ot the if command

some suggestions and reading:

1. post the driver app, e.g., the main part of your program, not just
the function
2. change all your varliable names to something more applicable to the
functionality of your code (a, b, c, e, f, k, ll, etc. just aren't
useful)
3. http://www.python.org/infogami-faq/tutor/tutor-what-is-the-policy-on-homework/
4. post the output, how you feel it's erroneous, what you think the
output should be, and where you think the problem may be *and* WHY
5. don't use input().  use raw_input() and int(), float(), etc.
6. don't cross-post to both the tutor and help mailing lists

From falcon3166 at hotmail.com  Fri Aug 25 01:36:49 2006
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Thu, 24 Aug 2006 17:36:49 -0600
Subject: [Tutor] What's the invalid syntax?
References: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>
	<44EDF64D.5020500@alum.rpi.edu>
Message-ID: <BAY106-DAV56B21863EE5A27B9DC896C4440@phx.gbl>

I sure did. It was choking because it was the wrong format.
----- Original Message ----- 
From: "Bob Gailer" <bgailer at alum.rpi.edu>
To: "Nathan Pinno" <falcon3166 at hotmail.com>
Cc: "Tutor mailing list" <tutor at python.org>
Sent: Thursday, August 24, 2006 12:56 PM
Subject: Re: [Tutor] What's the invalid syntax?


> My apology to you, Nathan. When I requested a traceback I did not 
> realize you were using an IDE.
> 
> But do realize that an IDE reporting a syntax error should point to (in 
> some way) to the offending line of code. It's always a good idea to 
> examine (as already suggested) that line to attempt to spot the problem.
> 
> Have you figured out why it is choking at the %?
> 
> -- 
> Bob Gailer
> 510-978-4454
> 
>

From wescpy at gmail.com  Fri Aug 25 01:39:46 2006
From: wescpy at gmail.com (wesley chun)
Date: Thu, 24 Aug 2006 16:39:46 -0700
Subject: [Tutor] editors
In-Reply-To: <20060818085653.38477.qmail@web55902.mail.re3.yahoo.com>
References: <20060818085653.38477.qmail@web55902.mail.re3.yahoo.com>
Message-ID: <78b3a9580608241639nceae32av82353ac95a18e7d0@mail.gmail.com>

On 8/18/06, anil maran <anilmrn at yahoo.com> wrote:
> what editors do you guys use?

your question crosses boundaries between text editors and IDEs.  you
list editors specifically. i believe that *emacs and *vim can do what
you ask, but IDEs can do even more.

popular IDEs include: IDLE, PythonWin, Komodo, Wing, SPE,
PyDev/Eclipse, IDEStudio, IPython.

a couple of related wiki pages to browse:
http://wiki.python.org/moin/PythonEditors
http://wiki.python.org/moin/IntegratedDevelopmentEnvironments

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

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

From amonroe at columbus.rr.com  Fri Aug 25 02:00:55 2006
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu, 24 Aug 2006 20:00:55 -0400
Subject: [Tutor] Query to the tutor mailing list
In-Reply-To: <78b3a9580608241537h6ffe4bbbl7d65413b58588236@mail.gmail.com>
References: <7c4cfdc0608240901h1bf7c193g1f0e1e5477ce12d@mail.gmail.com>
	<5e58f2e40608241432p3377a0e4obee320d98cbe956b@mail.gmail.com>
	<78b3a9580608241537h6ffe4bbbl7d65413b58588236@mail.gmail.com>
Message-ID: <192-2146972553.20060824200055@columbus.rr.com>

> On 8/24/06, John Fouhy <john at fouhy.net> wrote:
>> On 25/08/06, Joe Gamman <j.gamman at gmail.com> wrote:
>> > Anyway, would appreciate any comments on the idea.
>>
>> It seems like the sort of thing you find in textbooks or "learn to
>> program" books -- most books of this nature have suitable exercises at
>> the end of each chapter,

> joe,

> as john has suggested, exercises in Python books are another great way
> to get in the "practice" that you desire.

> i put a significant number of exercises in "Core Python," some which
> take 20-minutes as you had mentioned, but others may take up to 20
> hours.  they range from easy all the way to difficult, and some are
> game-oriented while most are not.

> there are about 260 exercises in the 1st ed., and the upcoming 2nd ed.
> will have well over 300.  i believe this is more than any other Python
> book out there. hope to be challenging you someday!

Sometimes you can find old books of very simplistic games written in
BASIC at your local library, and try converting them. Some of these
old books are archived at http://www.atariarchives.org/ .

Alan


From bgailer at alum.rpi.edu  Fri Aug 25 05:42:51 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu, 24 Aug 2006 20:42:51 -0700
Subject: [Tutor] help
In-Reply-To: <78b3a9580608241633k2a56ad7bv21bd320c3997691@mail.gmail.com>
References: <BAY121-F332E2C97E8B923320C3AFDEA440@phx.gbl>
	<78b3a9580608241633k2a56ad7bv21bd320c3997691@mail.gmail.com>
Message-ID: <44EE71BB.9090904@alum.rpi.edu>

wesley chun wrote:
> On 8/24/06, mike viceano <ph34r_th3_d4rkn3s at hotmail.com> wrote:
>   
>> hello i need a little help with a common multiple module i am haveing
>> problems with the best i can get it is to show the least common multiple i
>> think the problem is eather the and command ot the if command
>>     
>
> some suggestions and reading:
>
> 1. post the driver app, e.g., the main part of your program, not just
> the function
> 2. change all your varliable names to something more applicable to the
> functionality of your code (a, b, c, e, f, k, ll, etc. just aren't
> useful)
> 3. http://www.python.org/infogami-faq/tutor/tutor-what-is-the-policy-on-homework/
> 4. post the output, how you feel it's erroneous, what you think the
> output should be, and where you think the problem may be *and* WHY
> 5. don't use input().  use raw_input() and int(), float(), etc.
> 6. don't cross-post to both the tutor and help mailing lists
>   
and if that's not enough, please also use a more meaningful subject 
line, rather than "help".
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454


From sisson.j at gmail.com  Fri Aug 25 01:46:32 2006
From: sisson.j at gmail.com (Jonathon Sisson)
Date: Thu, 24 Aug 2006 18:46:32 -0500
Subject: [Tutor] help
In-Reply-To: <BAY121-F332E2C97E8B923320C3AFDEA440@phx.gbl>
References: <BAY121-F332E2C97E8B923320C3AFDEA440@phx.gbl>
Message-ID: <44EE3A58.2020009@gmail.com>

Hi Mike,

I'm not sure I'm understanding exactly what it is you're looking for
here, but from what I can tell you're looking for something such as:

num(220, 330) #for example
input a range of 10 # again, for example

which would result in an output of 0, 660, 1320 and 1980 (because
these four numbers are common to both kl and ll).

If this is indeed the case, then you need to replace the "while f<c"
statement block in your code.  Your code is looking for "f" (i.e. 0 -9
for the example numbers above), in kl and ll.  This explains why you
can get the least common multiple (0), but nothing more.  The solution
would be  to replace the entire "while f<c" block with this:

    while (indexK < c and indexL < c):
        if kl[indexK] < ll[indexL]:        # kl contains a smaller number
            indexK = indexK + 1
        elif ll[indexL] < kl[indexK]:     # ll contains a smaller number
            indexL = indexL + 1
        else:                                            # kl and ll
contain the same number here
            both.append(kl[indexK])
            if kl[indexK] < ll[indexL]: # this block is needed so we
don't enter an endless loop...
                indexK = indexK + 1
            else:
                indexL = indexL + 1

(make sure to declare indexK=indexL=0 somewhere before this block)
The following "print both" statement would then output:

[0, 660, 1320, 1980]

Is this what you were asking for?

Jonathon


mike viceano wrote:
> hello i need a little help with a common multiple module i am haveing
> problems with the best i can get it is to show the least common multiple i
> think the problem is eather the and command ot the if command
>
>    # finds common multiples
> def nums(a,b): # assigns numbers to a and b
>     print "enter range"
>     c = input(">")
>     both=[]
>     e=-1
>     f=-1
>     kl=[]
>     ll=[]
>     while e<c:
>         e=e+1
>         k=a*e
>         l=b*e
>         print a,"X",e,"=",k,"   ",b,"X",e,"=",l
>         kl.append(k)
>         ll.append(l)
>     while f<c:
>         f=f+1
>         if f in kl and f in ll:
>             both.append(f)
>     print both
>
> any help would be great
>
>
>
> ^_^"  s33 y4
>
> _________________________________________________________________
> Call friends with PC-to-PC calling -- FREE  
> http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From sisson.j at gmail.com  Fri Aug 25 02:14:04 2006
From: sisson.j at gmail.com (Jonathon Sisson)
Date: Thu, 24 Aug 2006 19:14:04 -0500
Subject: [Tutor]  help
Message-ID: <44EE40CC.2030306@gmail.com>

Gah!

Seems I sent that reply before stepping through my code a bit...
The last section of that code should be:

else:    # kl and ll contain the same number here
    both.append(kl[indexK])
    if indexK < indexL:     # this block is needed so we
        indexL = indexL + 1 # don't enter an endless loop...
    else:
        indexK = indexK + 1

The way I had it set up before (see below) always increments indexL.
Not a problem for this particular instance, but definitely shabby 
programming...oops...

Jonathon


Hi Mike,

I'm not sure I'm understanding exactly what it is you're looking for
here, but from what I can tell you're looking for something such as:

num(220, 330) #for example
input a range of 10 # again, for example

which would result in an output of 0, 660, 1320 and 1980 (because
these four numbers are common to both kl and ll).

If this is indeed the case, then you need to replace the "while f<c"
statement block in your code.  Your code is looking for "f" (i.e. 0 -9
for the example numbers above), in kl and ll.  This explains why you
can get the least common multiple (0), but nothing more.  The solution
would be  to replace the entire "while f<c" block with this:

    while (indexK < c and indexL < c):
        if kl[indexK] < ll[indexL]:        # kl contains a smaller number
            indexK = indexK + 1
        elif ll[indexL] < kl[indexK]:     # ll contains a smaller number
            indexL = indexL + 1
        else:    # kl and ll contain the same number here
            both.append(kl[indexK])
            if kl[indexK] < ll[indexL]: # this block is needed so we
                                        # don't enter an endless loop...
                indexK = indexK + 1
            else:
                indexL = indexL + 1

(make sure to declare indexK=indexL=0 somewhere before this block)
The following "print both" statement would then output:

[0, 660, 1320, 1980]

Is this what you were asking for?

Jonathon


mike viceano wrote:

> > hello i need a little help with a common multiple module i am haveing
> > problems with the best i can get it is to show the least common multiple i
> > think the problem is eather the and command ot the if command
> >
> >    # finds common multiples
> > def nums(a,b): # assigns numbers to a and b
> >     print "enter range"
> >     c = input(">")
> >     both=[]
> >     e=-1
> >     f=-1
> >     kl=[]
> >     ll=[]
> >     while e<c:
> >         e=e+1
> >         k=a*e
> >         l=b*e
> >         print a,"X",e,"=",k,"   ",b,"X",e,"=",l
> >         kl.append(k)
> >         ll.append(l)
> >     while f<c:
> >         f=f+1
> >         if f in kl and f in ll:
> >             both.append(f)
> >     print both
> >
> > any help would be great
> >
> >
> >
> > ^_^"  s33 y4
> >
> > _________________________________________________________________
> > Call friends with PC-to-PC calling -- FREE  
> > http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>   
-------------- next part --------------
An embedded message was scrubbed...
From: Jonathon Sisson <sisson.j at gmail.com>
Subject: Re: [Tutor] help
Date: Thu, 24 Aug 2006 18:46:32 -0500
Size: 3080
Url: http://mail.python.org/pipermail/tutor/attachments/20060824/b50e9427/attachment-0001.mht 

From anilmrn at yahoo.com  Fri Aug 25 09:57:26 2006
From: anilmrn at yahoo.com (anil maran)
Date: Fri, 25 Aug 2006 00:57:26 -0700 (PDT)
Subject: [Tutor] omnicomplete vim python
Message-ID: <20060825075726.36876.qmail@web55910.mail.re3.yahoo.com>

do u guys know how to enable omnicomplete using vim
for python thanks

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

From josipl2000 at yahoo.com  Fri Aug 25 18:17:50 2006
From: josipl2000 at yahoo.com (josip)
Date: Fri, 25 Aug 2006 09:17:50 -0700 (PDT)
Subject: [Tutor] function arg
Message-ID: <20060825161750.6397.qmail@web60821.mail.yahoo.com>

I have here few function from game tic-tac-toe from book python for absoulute beginners
   
  def first():
 """ Determine who goes first. Computer or Player.
 """
 gofirst = raw_input("Do You want to go first? (y/n): ")
   if gofirst == 'y':
  print "You start first"
  player = X
  computer = O
 else:
  print "Computer is first."
  player = O
  computer = X
 return computer, player
   
  def newTable():
 """ Create new table.
 """
 table = []
 for num in range(9):
  table.append('')
 return table
   
  def playerMove(table):   ##  <== here
 """ Get player moves
 """
 move = None
 while move not in legalMoves(table):
  move = int(raw_input("Enter Your position? (0-9): "))
  if move not in range(9):
   print '\nOnly numbers 0 - 9'
  elif move not in legalMoves(table):
   print "\nThat position is allready occupied. Choose another: "
 print "OK..."
 return move
   
  Why I have to put table in function playerMove and in some others functions?
  If I dont put it's not working.
   
  Thanks!

 		
---------------------------------
 All-new Yahoo! Mail - Fire up a more powerful email and get things done faster.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060825/5a7a348f/attachment.html 

From bgailer at alum.rpi.edu  Fri Aug 25 20:41:31 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 25 Aug 2006 11:41:31 -0700
Subject: [Tutor] Python programming activities
Message-ID: <44EF445B.7090108@alum.rpi.edu>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060825/0c7ceda1/attachment.html 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: moz-screenshot.jpg
Type: image/jpeg
Size: 10432 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060825/0c7ceda1/attachment.jpg 

From alberto.troiano at gmail.com  Fri Aug 25 21:14:49 2006
From: alberto.troiano at gmail.com (Alberto Troiano)
Date: Fri, 25 Aug 2006 15:14:49 -0400
Subject: [Tutor] Tkinter Icon Suse 10
Message-ID: <81a1194c0608251214p2c2b25b6lf46190a0b805c54a@mail.gmail.com>

Hi everyone

It's been a long time since I left Python for .NET 2003, but then again I
need it to make an app under Linux Suse 10 and I have a question
I'm trying to put an icon to my window...
Here is the code so far:

###Start Code###

import Tkinter
from Tkinter import *

root = Tk()
root.iconbitmap("Change.ico")
root.mainloop()

###End Code###

It works great under Windows but on an Suse 10 Machine it complains about
the file. Is this because the icon files are not the same as in Windows or
should I be using another sentence to make it work?
I know it's a dumb question but I'm out of practice and I couldn't find docs
on Google (maybe I didn't look where I supposed to)
Ups..I forgot, I'm using Python 2.4.1

Regards
-- 
Alberto
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060825/98a92ef4/attachment.html 

From alan.gauld at freenet.co.uk  Fri Aug 25 22:42:17 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 25 Aug 2006 21:42:17 +0100
Subject: [Tutor] What's the invalid syntax?
References: <BAY106-DAV193F535945F78AE3B88A19C4470@phx.gbl>
	<002201c6c733$4509fda0$0201a8c0@XPpro>
	<BAY106-DAV10E2062D236407B930ED88C4440@phx.gbl>
Message-ID: <000901c6c886$f4e68a00$0201a8c0@XPpro>

Nathan,

> Sorry, but it only showed a text-box with the message "Invalid 
> syntax!", then highlighted the %.

OK, But if you try it from a command prompt you will get a proper
error message. But even if you tell us which line it is highlighting,
there are several % signs in your code.

Generally when pythonindicates a syntax error it will be within a
few lines of where the error occurs, so iut saves us a lot of reading!

Alan G.



From amadeo.bellotti at gmail.com  Fri Aug 25 23:28:14 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Fri, 25 Aug 2006 17:28:14 -0400
Subject: [Tutor] A list of ints to a strings
Message-ID: <d7253a230608251428ma8c6260u1002846e2c8038d2@mail.gmail.com>

I need to convert a list of intgers to a string so for example

I have this
x = [1, 2, 3, 4, 5, 6]

I want this

x = "1 2 3 4 5 6"

I need this to write it to a .txt file does anyone know how to do this?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060825/7959df33/attachment.html 

From bgailer at alum.rpi.edu  Fri Aug 25 23:37:23 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 25 Aug 2006 14:37:23 -0700
Subject: [Tutor] Python programming activities
In-Reply-To: <44EF445B.7090108@alum.rpi.edu>
References: <44EF445B.7090108@alum.rpi.edu>
Message-ID: <44EF6D93.5020509@alum.rpi.edu>

Bob Gailer wrote:

I amend the previous e-mail:

) this is in response to j.gamman at gmail.com desire for some programming 
assignments to work while commuting.
) "I exclude these from the following rules" refers just to rules 1 and 4.
) rule 3 - the path is vertical or horizontal, not diagonal.
) rule 5 "there are at most 9 contiguous white squares" should read "any 
contiguous set of white squares has at most 9 squares."

-- 
Bob Gailer
510-978-4454


From amadeo.bellotti at gmail.com  Sat Aug 26 00:22:02 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Fri, 25 Aug 2006 18:22:02 -0400
Subject: [Tutor] A list of ints to a strings
In-Reply-To: <DB30DA681DB9544886EA69FE9082737C025210@csoexc02.intelliden.net>
References: <DB30DA681DB9544886EA69FE9082737C025210@csoexc02.intelliden.net>
Message-ID: <d7253a230608251522k2ea36003hd99154c7bccafda3@mail.gmail.com>

thank you and like wat if i wanna write one string on one line and another
string on another line ect.

On 8/25/06, David Heiser <David.Heiser at intelliden.com> wrote:
>
>  This will work
>
>
> x = [1, 2, 3, 4, 5, 6]
>
> x = str(x)[1:-1].replace(",", '')
>
> open("filename.txt", "w").write(x)
>
>
>  -----Original Message-----
> *From:* tutor-bounces at python.org [mailto:tutor-bounces at python.org] *On
> Behalf Of *Amadeo Bellotti
> *Sent:* Friday, August 25, 2006 3:28 PM
> *To:* Tutor
> *Subject:* [Tutor] A list of ints to a strings
>
> I need to convert a list of intgers to a string so for example
>
> I have this
> x = [1, 2, 3, 4, 5, 6]
>
> I want this
>
> x = "1 2 3 4 5 6"
>
> I need this to write it to a .txt file does anyone know how to do this?
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060825/8d02af3c/attachment.html 

From john at fouhy.net  Sat Aug 26 00:37:23 2006
From: john at fouhy.net (John Fouhy)
Date: Sat, 26 Aug 2006 10:37:23 +1200
Subject: [Tutor] A list of ints to a strings
In-Reply-To: <d7253a230608251428ma8c6260u1002846e2c8038d2@mail.gmail.com>
References: <d7253a230608251428ma8c6260u1002846e2c8038d2@mail.gmail.com>
Message-ID: <5e58f2e40608251537s5d41ee3dkf16c81ea9e24efb@mail.gmail.com>

On 26/08/06, Amadeo Bellotti <amadeo.bellotti at gmail.com> wrote:
> I need to convert a list of intgers to a string so for example
>
>  I have this
>  x = [1, 2, 3, 4, 5, 6]
>
>  I want this
>
>  x = "1 2 3 4 5 6"

Actually, I disagree with David's solution somewhat --- I think that
the pythonic way to do this is as follows:

Firstly, you can use a list comprehension to convert each integer into
a separate string.  If you don't know about list comprehensions, you
can read about them in any python tutorial.

>>> x = [1, 2, 3, 4, 5]
>>> y = [str(i) for i in x]
>>> y
['1', '2', '3', '4', '5']

Then you can use the .join() method of strings to join them into a
single line.  In this case, the separator is a space, ' ':

>>> z = ' '.join(y)
>>> z
'1 2 3 4 5'

If you want to put one number on each row, you can use the newline
character '\n' as a separator instead:

>>> '\n'.join(y)
'1\n2\n3\n4\n5'
>>> print '\n'.join(y)
1
2
3
4
5

HTH!

-- 
John.

From klappnase at freenet.de  Sat Aug 26 00:35:24 2006
From: klappnase at freenet.de (Michael Lange)
Date: Sat, 26 Aug 2006 00:35:24 +0200
Subject: [Tutor] Tkinter Icon Suse 10
In-Reply-To: <81a1194c0608251214p2c2b25b6lf46190a0b805c54a@mail.gmail.com>
References: <81a1194c0608251214p2c2b25b6lf46190a0b805c54a@mail.gmail.com>
Message-ID: <20060826003524.0e455ee6.klappnase@freenet.de>

On Fri, 25 Aug 2006 15:14:49 -0400
"Alberto Troiano" <alberto.troiano at gmail.com> wrote:

> Hi everyone
> 
> It's been a long time since I left Python for .NET 2003, but then again I
> need it to make an app under Linux Suse 10 and I have a question
> I'm trying to put an icon to my window...
> Here is the code so far:
> 
> ###Start Code###
> 
> import Tkinter
> from Tkinter import *
> 
> root = Tk()
> root.iconbitmap("Change.ico")
> root.mainloop()
> 
> ###End Code###
> 
> It works great under Windows but on an Suse 10 Machine it complains about
> the file. Is this because the icon files are not the same as in Windows or
> should I be using another sentence to make it work?
> I know it's a dumb question but I'm out of practice and I couldn't find docs
> on Google (maybe I didn't look where I supposed to)
> Ups..I forgot, I'm using Python 2.4.1
> 

Hi Alberto,

you will have to use an xbm bitmap file for the iconbitmap, like

    root.iconbitmap("@Change.xbm")

HTH

Michael

From amadeo.bellotti at gmail.com  Sat Aug 26 00:45:28 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Fri, 25 Aug 2006 18:45:28 -0400
Subject: [Tutor] A list of ints to a strings
In-Reply-To: <5e58f2e40608251537s5d41ee3dkf16c81ea9e24efb@mail.gmail.com>
References: <d7253a230608251428ma8c6260u1002846e2c8038d2@mail.gmail.com>
	<5e58f2e40608251537s5d41ee3dkf16c81ea9e24efb@mail.gmail.com>
Message-ID: <d7253a230608251545t4b48d9ccuab12938ff68d9ae6@mail.gmail.com>

HTH

wat i ment is like i have

x = [1, 2, 3, 4, 5]
y = [2, 3, 4, 5, 1]

and i want x and y as a string

and i want to write it to a file so its like

1 2 3 4 5
2 3 4 5 1

sorry about that misunderstanding

On 8/25/06, John Fouhy <john at fouhy.net> wrote:
>
> On 26/08/06, Amadeo Bellotti <amadeo.bellotti at gmail.com> wrote:
> > I need to convert a list of intgers to a string so for example
> >
> >  I have this
> >  x = [1, 2, 3, 4, 5, 6]
> >
> >  I want this
> >
> >  x = "1 2 3 4 5 6"
>
> Actually, I disagree with David's solution somewhat --- I think that
> the pythonic way to do this is as follows:
>
> Firstly, you can use a list comprehension to convert each integer into
> a separate string.  If you don't know about list comprehensions, you
> can read about them in any python tutorial.
>
> >>> x = [1, 2, 3, 4, 5]
> >>> y = [str(i) for i in x]
> >>> y
> ['1', '2', '3', '4', '5']
>
> Then you can use the .join() method of strings to join them into a
> single line.  In this case, the separator is a space, ' ':
>
> >>> z = ' '.join(y)
> >>> z
> '1 2 3 4 5'
>
> If you want to put one number on each row, you can use the newline
> character '\n' as a separator instead:
>
> >>> '\n'.join(y)
> '1\n2\n3\n4\n5'
> >>> print '\n'.join(y)
> 1
> 2
> 3
> 4
> 5
>
> HTH!
>
> --
> John.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060825/6d352aaa/attachment.htm 

From alan.gauld at btinternet.com  Sat Aug 26 00:51:44 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 25 Aug 2006 23:51:44 +0100
Subject: [Tutor] How do I make Python read a string character
	bycharacter?
References: <BAY106-DAV97504C61B5A98C8D7BBD8C4440@phx.gbl>
	<868b524f0608232312y22dcd5b5y2b89c96099ac620c@mail.gmail.com>
Message-ID: <ecnuu3$bks$1@sea.gmane.org>


"Akash" <akashmahajan at gmail.com> wrote 
>> How do I make Python read a string character by character?
> 
>>>> str = 'string'
>>>> for i in range(0, len(str)):
> ...     print str[i]
> ...

Or without indexing:

for c in "string":
  print c

> s
> t
> r
> i
> n
> g

However I'm not sure if thats what Nathan meant.

If you mean how do you read a string of characters 
from a file use read() with a size of 1.

If you mean from stdin then it depends on the platform. 
Use curses for Linux/MacOS or use msvcrt. 
In both cases the function is getch()

Alan G.


From alan.gauld at btinternet.com  Sat Aug 26 01:01:14 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 26 Aug 2006 00:01:14 +0100
Subject: [Tutor] Query to the tutor mailing list
References: <7c4cfdc0608240901h1bf7c193g1f0e1e5477ce12d@mail.gmail.com><5e58f2e40608241432p3377a0e4obee320d98cbe956b@mail.gmail.com>
	<78b3a9580608241537h6ffe4bbbl7d65413b58588236@mail.gmail.com>
Message-ID: <ecnvft$d48$1@sea.gmane.org>

> i put a significant number of exercises in "Core Python," some which
> ...
> there are about 260 exercises in the 1st ed., and the upcoming 2nd 
> ed.
> will have well over 300.  i believe this is more than any other 
> Python
> book out there.

Certainly more than mine Wes!
I got a lot of flack on amazon reviews for not putting exercises
at the end of each chapter - although in fact there are over 50
"challenges" throughout the text, but you have to read the text
to find them! ( That's because I don't like text book style
exercises personally...)

However one badly missed Python resource that used to help
a lot was the Useless Python web site. Alas it seems to have
dissappeared fromthe web. The author tried to do a revamp and
for some reason version 2 never quite got the support the original
site did. But it was a great resource of little mini-projects and
challenges for beginners.

And of course the Python Challenge game is still on the web,
but the challenge there tends to be in figuring out what to do,
once yopu get past that you can write the code in about
5 minutes flat! The other problem is you usually need to paste
the result back into a webn browser to assess the result!

Alan G. 



From alan.gauld at btinternet.com  Sat Aug 26 01:05:29 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 26 Aug 2006 00:05:29 +0100
Subject: [Tutor] omnicomplete vim python
References: <20060825075726.36876.qmail@web55910.mail.re3.yahoo.com>
Message-ID: <ecnvns$dni$1@sea.gmane.org>


"anil maran" <anilmrn at yahoo.com> wrote 
> do u guys know how to enable omnicomplete using vim
> for python thanks

Nope.
But what is omnicomplete and why would I want it?

Alan G,
A Python and vim user for 5 years but not (yet) an omnicompleteist


From kent37 at tds.net  Sat Aug 26 01:20:15 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 25 Aug 2006 19:20:15 -0400
Subject: [Tutor] Query to the tutor mailing list
In-Reply-To: <ecnvft$d48$1@sea.gmane.org>
References: <7c4cfdc0608240901h1bf7c193g1f0e1e5477ce12d@mail.gmail.com><5e58f2e40608241432p3377a0e4obee320d98cbe956b@mail.gmail.com>	<78b3a9580608241537h6ffe4bbbl7d65413b58588236@mail.gmail.com>
	<ecnvft$d48$1@sea.gmane.org>
Message-ID: <44EF85AF.4070805@tds.net>

Alan Gauld wrote:
> However one badly missed Python resource that used to help
> a lot was the Useless Python web site. Alas it seems to have
> dissappeared fromthe web. 

It's baaaaack!
http://www.uselesspython.com/

Kent


From nimrodx at slingshot.co.nz  Sat Aug 26 02:30:30 2006
From: nimrodx at slingshot.co.nz (nimrodx)
Date: Sat, 26 Aug 2006 12:30:30 +1200
Subject: [Tutor] Sending an attatchment with SMTP lib
Message-ID: <44EF9626.6060308@slingshot.co.nz>

Hi All,

How do I go about sending an attachment with SMTP lib?

Thanks,

Matt

From zslevi at sch.bme.hu  Sat Aug 26 07:37:27 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Sat, 26 Aug 2006 07:37:27 +0200
Subject: [Tutor] tkinter events: <B1-Motion>
In-Reply-To: <57B026980605A64F9B23484C5659E32E25588D@poccso.US.ad.atmel.com>
References: <57B026980605A64F9B23484C5659E32E25588D@poccso.US.ad.atmel.com>
Message-ID: <44EFDE17.8000308@sch.bme.hu>

The link is broken.

Mike Hansen wrote:

> 
>
>  
>
>>-----Original Message-----
>>From: tutor-bounces at python.org 
>>[mailto:tutor-bounces at python.org] On Behalf Of Zsiros Levente
>>Sent: Thursday, August 24, 2006 2:21 PM
>>To: Danny Yoo
>>Cc: python tutor
>>Subject: Re: [Tutor] tkinter events: <B1-Motion>
>>
>>If we're talking about data hiding, let me ask: why Python doesn't 
>>implement data hiding (I mean 'private' and 'protected')? I 
>>consider it 
>>a very important OOP feature, because that makes OOP different from 
>>structural programming.
>>
>>    
>>
>
>This might explain...
>
>http://pyfaq.infogami.com/tutor-how-do-i-make-public-and-private-attribu
>tes-and-methods-in-my-classes
>
>Mike
>**********************************************************************************************
>IMPORTANT: The contents of this email and any attachments are confidential. They are intended for the 
>named recipient(s) only.
>If you have received this email in error, please notify the system manager or the sender immediately and do 
>not disclose the contents to anyone or make copies thereof.
>*** eSafe scanned this email for viruses, vandals, and malicious content. ***
>**********************************************************************************************
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>


From zslevi at sch.bme.hu  Sat Aug 26 08:03:35 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Sat, 26 Aug 2006 08:03:35 +0200
Subject: [Tutor] tkinter events: <B1-Motion>
In-Reply-To: <44EA0C7E.1040505@gmail.com>
References: <44E9B6E0.3060305@sch.bme.hu> <44EA0C7E.1040505@gmail.com>
Message-ID: <44EFE437.7060306@sch.bme.hu>

So, in the following line

self.can.bind("<ButtonRelease-1>",lambda x:self.handler(x,'release'))

the event-handler will call handler(event, 'release') when the 
mousebutton is released, but the 'self' reference is automatically 
passed over, so the result will be the handler(self,event, 'release') call.

Correct me, if I'm wrong.

>------------------------------------------------------------------------
>
>#!/usr/bin/python
>
># This program implements <B1-motion>.  it was originally written by
>#Zsiros Levente.  all rights of this modified version go to him :)
>
>from Tkinter import *
>
>class ButtonHandler(object):
>    def __init__(self):
>        #our self.mousedown variable is what we'll use to check the state
>        #of the button, since we're going to be passing a copy of 'self'
>        #around, we don't have to deal with scoping of the variables.
>        #I.E. self.mousedown is global to functions in the class
>        #that accept a 'self' argument.
>        self.mousedown = 0
>        
>        #we make the window normally. note all these are 'self' variables
>        #so we can change them easily elsewhere in the class.
>        self.root = Tk()
>        self.root.geometry('600x500+200+200')
>        self.label = Label(self.root, text=str(self.mousedown))
>        self.can = Canvas(self.root, width='500', height='400', bg='white')
>        #lambda is a way we can add extra arguments to a function.
>        #since the callback of bound events is only a single argument,
>        #we use 'lambda x' to get the 'event' instance, and pass it
>        #along with another string identifying which event it came from.
>        #this may or may not be necessary, but it's cool and it
>        #makes the handler function make more sense.
>        #also, we only need one handler function this way.
>        self.can.bind("<Motion>",lambda x:self.handler(x,'motion'))
>        self.can.bind("<Button-1>",lambda x:self.handler(x,'press'))
>        self.can.bind("<ButtonRelease-1>",lambda x:self.handler(x,'release'))
>        self.label.pack()
>        self.can.pack()
>        self.root.mainloop()
>        
>    def handler(self,event,x):
>        #the first two clauses of the if-elif branch implement your
>        #'press' and 'release' functions.
>        if x == 'press':
>            self.mousedown = 1
>        elif x == 'release':
>            self.mousedown = 0
>        elif x == 'motion':
>            if self.mousedown:
>                #you could do something really cool here, like store the time
>                #that the button was last pressed, and increase the radius of the circle
>                #depending on how long it's been since then.
>                r = 5
>                self.can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, fill="orange")
>	self.label.config(text=str(self.mousedown))
>        
>
>#we create an instance of the class which automatically
>#calls the '__init__' method.
>x = ButtonHandler()
>  
>

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

From zslevi at sch.bme.hu  Sat Aug 26 08:06:10 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Sat, 26 Aug 2006 08:06:10 +0200
Subject: [Tutor] tkinter events: <B1-Motion>
In-Reply-To: <44EA0C7E.1040505@gmail.com>
References: <44E9B6E0.3060305@sch.bme.hu> <44EA0C7E.1040505@gmail.com>
Message-ID: <44EFE4D2.7070208@sch.bme.hu>

So, in the following line

self.can.bind("<ButtonRelease-1>",lambda x:self.handler(x,'release'))

the event-handler will call handler(event, 'release') when the 
mousebutton is released, but the 'self' reference is automatically 
passed over, so the result will be the handler(self,event, 'release') call.

Correct me, if I'm wrong.

>------------------------------------------------------------------------
>
>#!/usr/bin/python
>
># This program implements <B1-motion>.  it was originally written by
>#Zsiros Levente.  all rights of this modified version go to him :)
>
>from Tkinter import *
>
>class ButtonHandler(object):
>    def __init__(self):
>        #our self.mousedown variable is what we'll use to check the state
>        #of the button, since we're going to be passing a copy of 'self'
>        #around, we don't have to deal with scoping of the variables.
>        #I.E. self.mousedown is global to functions in the class
>        #that accept a 'self' argument.
>        self.mousedown = 0
>        
>        #we make the window normally. note all these are 'self' variables
>        #so we can change them easily elsewhere in the class.
>        self.root = Tk()
>        self.root.geometry('600x500+200+200')
>        self.label = Label(self.root, text=str(self.mousedown))
>        self.can = Canvas(self.root, width='500', height='400', bg='white')
>        #lambda is a way we can add extra arguments to a function.
>        #since the callback of bound events is only a single argument,
>        #we use 'lambda x' to get the 'event' instance, and pass it
>        #along with another string identifying which event it came from.
>        #this may or may not be necessary, but it's cool and it
>        #makes the handler function make more sense.
>        #also, we only need one handler function this way.
>        self.can.bind("<Motion>",lambda x:self.handler(x,'motion'))
>        self.can.bind("<Button-1>",lambda x:self.handler(x,'press'))
>        self.can.bind("<ButtonRelease-1>",lambda x:self.handler(x,'release'))
>        self.label.pack()
>        self.can.pack()
>        self.root.mainloop()
>        
>    def handler(self,event,x):
>        #the first two clauses of the if-elif branch implement your
>        #'press' and 'release' functions.
>        if x == 'press':
>            self.mousedown = 1
>        elif x == 'release':
>            self.mousedown = 0
>        elif x == 'motion':
>            if self.mousedown:
>                #you could do something really cool here, like store the time
>                #that the button was last pressed, and increase the radius of the circle
>                #depending on how long it's been since then.
>                r = 5
>                self.can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, fill="orange")
>	self.label.config(text=str(self.mousedown))
>        
>
>#we create an instance of the class which automatically
>#calls the '__init__' method.
>x = ButtonHandler()
>  
>

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

From zslevi at sch.bme.hu  Sat Aug 26 08:47:28 2006
From: zslevi at sch.bme.hu (Zsiros Levente)
Date: Sat, 26 Aug 2006 08:47:28 +0200
Subject: [Tutor] tkinter events: <B1-Motion>
In-Reply-To: <44EA0C7E.1040505@gmail.com>
References: <44E9B6E0.3060305@sch.bme.hu> <44EA0C7E.1040505@gmail.com>
Message-ID: <44EFEE80.2070001@sch.bme.hu>

So, in the following line

self.can.bind("<ButtonRelease-1>",lambda x:self.handler(x,'release'))

the event-handler will call handler(event, 'release') when the 
mousebutton is released, but the 'self' reference is automatically 
passed over, so the result will be the handler(self,event, 'release') call.

Correct me, if I'm wrong.

>------------------------------------------------------------------------
>
>#!/usr/bin/python
>
># This program implements <B1-motion>.  it was originally written by
>#Zsiros Levente.  all rights of this modified version go to him :)
>
>from Tkinter import *
>
>class ButtonHandler(object):
>    def __init__(self):
>        #our self.mousedown variable is what we'll use to check the state
>        #of the button, since we're going to be passing a copy of 'self'
>        #around, we don't have to deal with scoping of the variables.
>        #I.E. self.mousedown is global to functions in the class
>        #that accept a 'self' argument.
>        self.mousedown = 0
>        
>        #we make the window normally. note all these are 'self' variables
>        #so we can change them easily elsewhere in the class.
>        self.root = Tk()
>        self.root.geometry('600x500+200+200')
>        self.label = Label(self.root, text=str(self.mousedown))
>        self.can = Canvas(self.root, width='500', height='400', bg='white')
>        #lambda is a way we can add extra arguments to a function.
>        #since the callback of bound events is only a single argument,
>        #we use 'lambda x' to get the 'event' instance, and pass it
>        #along with another string identifying which event it came from.
>        #this may or may not be necessary, but it's cool and it
>        #makes the handler function make more sense.
>        #also, we only need one handler function this way.
>        self.can.bind("<Motion>",lambda x:self.handler(x,'motion'))
>        self.can.bind("<Button-1>",lambda x:self.handler(x,'press'))
>        self.can.bind("<ButtonRelease-1>",lambda x:self.handler(x,'release'))
>        self.label.pack()
>        self.can.pack()
>        self.root.mainloop()
>        
>    def handler(self,event,x):
>        #the first two clauses of the if-elif branch implement your
>        #'press' and 'release' functions.
>        if x == 'press':
>            self.mousedown = 1
>        elif x == 'release':
>            self.mousedown = 0
>        elif x == 'motion':
>            if self.mousedown:
>                #you could do something really cool here, like store the time
>                #that the button was last pressed, and increase the radius of the circle
>                #depending on how long it's been since then.
>                r = 5
>                self.can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, fill="orange")
>	self.label.config(text=str(self.mousedown))
>        
>
>#we create an instance of the class which automatically
>#calls the '__init__' method.
>x = ButtonHandler()
>  
>


From wescpy at gmail.com  Sat Aug 26 10:03:37 2006
From: wescpy at gmail.com (wesley chun)
Date: Sat, 26 Aug 2006 01:03:37 -0700
Subject: [Tutor] Query to the tutor mailing list
In-Reply-To: <ecnvft$d48$1@sea.gmane.org>
References: <7c4cfdc0608240901h1bf7c193g1f0e1e5477ce12d@mail.gmail.com>
	<5e58f2e40608241432p3377a0e4obee320d98cbe956b@mail.gmail.com>
	<78b3a9580608241537h6ffe4bbbl7d65413b58588236@mail.gmail.com>
	<ecnvft$d48$1@sea.gmane.org>
Message-ID: <78b3a9580608260103m48679d42pf798d879b9103424@mail.gmail.com>

On 8/25/06, Alan Gauld <alan.gauld at btinternet.com> wrote:
>> > i put a significant number of exercises in "Core Python," some which
>> > ...
>> > there are about 260 exercises in the 1st ed., and the upcoming 2nd
>> > ed. will have well over 300.  i believe this is more than any other
>> > Python book out there.
>
> Certainly more than mine Wes!

ah, but your book is target towards a different audience, the newbie.
'core python' is directed towards existing programmers new to python.
the fastest and most effective way to learn a new language is to
exercise the concepts and newfound knowledge. if i were to write a
newbie book, there certainly wouldn't be as many.  but speaking of
learn how to program... is there a 2nd edition coming soon?  :-)


>> I got a lot of flack on amazon reviews for not putting exercises
>> at the end of each chapter - although in fact there are over 50
>> "challenges" throughout the text, but you have to read the text
>> to find them! ( That's because I don't like text book style
>> exercises personally...)

i'm not a fan of dry textbooks, but i do believe in exercises.
sometimes i put what i call "mental challenges" in chapter reading,
but they are not phrased as problems to be solved, just something to
think about for the reader.

>> However one badly missed Python resource that used to help
>> a lot was the Useless Python web site. Alas it seems to have
>> dissappeared fromthe web.
>
> It's baaaaack!
> http://www.uselesspython.com/

this is great news.  i wish there were more sites like this and the
Challenge out there... they really make you think in "real-time."

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

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

From alan.gauld at freenet.co.uk  Sat Aug 26 10:27:33 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 26 Aug 2006 09:27:33 +0100
Subject: [Tutor] Query to the tutor mailing list
References: <7c4cfdc0608240901h1bf7c193g1f0e1e5477ce12d@mail.gmail.com><5e58f2e40608241432p3377a0e4obee320d98cbe956b@mail.gmail.com><78b3a9580608241537h6ffe4bbbl7d65413b58588236@mail.gmail.com><ecnvft$d48$1@sea.gmane.org>
	<78b3a9580608260103m48679d42pf798d879b9103424@mail.gmail.com>
Message-ID: <002e01c6c8e9$7b33b800$0201a8c0@XPpro>

> newbie book, there certainly wouldn't be as many.  but speaking of
> learn how to program... is there a 2nd edition coming soon?  :-)

Unlikely. The sales have been steady (surprisingly so given its age 
now)
but not exactly stellar so Addison Wesley aren't too excited about
it I suspect. To be honest I'm not overly excited myself, the real 
focus
has always been the web site, I only wrote the book because so many
folks emailed me and asked for a paper version.

If AW ask me to do a revision I wouldn't say no, but I'm not chasing
them to do so... Any 2nd edition would reflect the changes on the
web site: extra topics, expanded coverage, and language updates
since version 1.5.2.

>> It's baaaaack!
>> http://www.uselesspython.com/
>
> this is great news.  i wish there were more sites like this and the
> Challenge out there... they really make you think in "real-time."

I agree. Useless is a unique resource so far as I can tell.

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


From alan.gauld at btinternet.com  Sat Aug 26 14:28:19 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 26 Aug 2006 13:28:19 +0100
Subject: [Tutor] Sending an attatchment with SMTP lib
References: <44EF9626.6060308@slingshot.co.nz>
Message-ID: <ecpep5$csg$1@sea.gmane.org>

"nimrodx" <nimrodx at slingshot.co.nz> wrote in 
> 
> How do I go about sending an attachment with SMTP lib?

Can you explain first of all why you think you need to?

The new email module permits you to do most things with 
email messages, so what is it about your task that makes 
you want to use the more primitive modules like SMTPlib?

Is there something unique to your problem that makes 
the email module unsuitable? Have you encountered a 
problem with it?

Check the recent thread initiated by Shawn Briight for 
some more on this.

Alan G.


From hmm at woolgathering.cx  Sat Aug 26 14:27:12 2006
From: hmm at woolgathering.cx (William O'Higgins Witteman)
Date: Sat, 26 Aug 2006 08:27:12 -0400
Subject: [Tutor] Regex help
Message-ID: <20060826122712.GA26838@sillyrabbi.dyndns.org>

Hello all,

I've been looking for an example of the regex I need, and so far, I
haven't found anything.  Here's what I need:

I want a case-insensitive, verbose pattern.  I have a long-ish list of
match criteria (about a dozen distinct cases), which should be all "or",
so I won't need to be clever with precedence.  Any help you could
provide with the syntax of this pattern would be greatly appreciated.
Thanks.
-- 

yours,

William

From kent37 at tds.net  Sat Aug 26 15:45:04 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 26 Aug 2006 09:45:04 -0400
Subject: [Tutor] Regex help
In-Reply-To: <20060826122712.GA26838@sillyrabbi.dyndns.org>
References: <20060826122712.GA26838@sillyrabbi.dyndns.org>
Message-ID: <44F05060.90004@tds.net>

William O'Higgins Witteman wrote:
> Hello all,
>
> I've been looking for an example of the regex I need, and so far, I
> haven't found anything.  Here's what I need:
>
> I want a case-insensitive, verbose pattern.  I have a long-ish list of
> match criteria (about a dozen distinct cases), which should be all "or",
> so I won't need to be clever with precedence.

Vertical bar | is used to separate 'or' cases in a regex. To make it 
case-insensitive and verbose you can compile with the flags re.VERBOSE 
and re.IGNORECASE. Use the search method of the compiled regex to search 
your string. For example,

In [1]: import re

In [2]: rx = re.compile('foo|bar|baz', re.VERBOSE | re.IGNORECASE)

In [3]: rx.search('Foontastic')
Out[3]: <_sre.SRE_Match object at 0x00C40640>

In [4]: rx.search('raise the BAR')
Out[4]: <_sre.SRE_Match object at 0x00E901A8>

Kent


From alberto.troiano at gmail.com  Sat Aug 26 17:19:18 2006
From: alberto.troiano at gmail.com (Alberto Troiano)
Date: Sat, 26 Aug 2006 11:19:18 -0400
Subject: [Tutor] Tkinter Icon Suse 10
In-Reply-To: <81a1194c0608251214p2c2b25b6lf46190a0b805c54a@mail.gmail.com>
References: <81a1194c0608251214p2c2b25b6lf46190a0b805c54a@mail.gmail.com>
Message-ID: <81a1194c0608260819u3a2bb334r8a8067b79189f1c8@mail.gmail.com>

Hey..thanks for the reply

I found some XBM on the PC (Suse) but still no luck
The error says that the bitmap is not defined
Was the code OK or I have to change it?

Thanks

2006/8/25, Alberto Troiano <alberto.troiano at gmail.com>:
>
> Hi everyone
>
> It's been a long time since I left Python for .NET 2003, but then again I
> need it to make an app under Linux Suse 10 and I have a question
> I'm trying to put an icon to my window...
> Here is the code so far:
>
> ###Start Code###
>
> import Tkinter
> from Tkinter import *
>
> root = Tk()
> root.iconbitmap("Change.ico")
> root.mainloop()
>
> ###End Code###
>
> It works great under Windows but on an Suse 10 Machine it complains about
> the file. Is this because the icon files are not the same as in Windows or
> should I be using another sentence to make it work?
> I know it's a dumb question but I'm out of practice and I couldn't find
> docs on Google (maybe I didn't look where I supposed to)
> Ups..I forgot, I'm using Python 2.4.1
>
> Regards
> --
> Alberto
>



-- 
Alberto Troiano
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060826/47d6fb38/attachment.htm 

From alan.gauld at btinternet.com  Sat Aug 26 23:26:40 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 26 Aug 2006 22:26:40 +0100
Subject: [Tutor] Tkinter Icon Suse 10
References: <81a1194c0608251214p2c2b25b6lf46190a0b805c54a@mail.gmail.com>
	<81a1194c0608260819u3a2bb334r8a8067b79189f1c8@mail.gmail.com>
Message-ID: <ecqeaj$t11$1@sea.gmane.org>

> The error says that the bitmap is not defined
> Was the code OK or I have to change it?

You probably need to specify the full path.
At a guess...

Alan G.

>> root = Tk()
>> root.iconbitmap("Change.ico")
>> root.mainloop()



From juhasz.jani at freemail.hu  Sat Aug 26 22:04:47 2006
From: juhasz.jani at freemail.hu (=?ISO-8859-2?Q?Juh=E1sz_J=E1nos?=)
Date: Sat, 26 Aug 2006 22:04:47 +0200 (CEST)
Subject: [Tutor]  banners
Message-ID: <freemail.20060726220447.25533@fm08.freemail.hu>

I have continued to work on making banners:)

Here is a solution with PIL 
(http://www.pythonware.com/products/pil/index.htm):


import Image, ImageFont, ImageDraw

ShowText = 'Hi all'

font = ImageFont.load(r'c:\Python24\Lib\site-
packages\enthought\kiva\pil_fonts\courier-bold-10.pil')
size = font.getsize(ShowText)
image = Image.new('1', size, 1)
draw = ImageDraw.Draw(image)
draw.text((0, 0), ShowText, font=font)
for rownum in range(size[1]):
    for colnum in range(size[0]):
        if image.getpixel((colnum, rownum)): print " ",
        else: print "#",
    print ''

If your pil font file is in a different directory, you have to change it.

It produces the next output for me anyway:

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


                                                           
Janos Juhasz

______________________________________________________________________
Ad?megtakar?t?s augusztusban? Ne dobja ki p?nz?t feleslegesen!
http://www.klikkbank.hu/befektetes/index.html


From kayrivertree at yahoo.com  Sun Aug 27 17:19:40 2006
From: kayrivertree at yahoo.com (Kay White)
Date: Sun, 27 Aug 2006 08:19:40 -0700 (PDT)
Subject: [Tutor] program that 'waits' for file?
Message-ID: <20060827151940.91694.qmail@web56115.mail.re3.yahoo.com>

Hello, 
  
  I'm trying to make a program that will wait for a specific file to be  made by another program, and when that happens it opens and modifies  that file. The other program is a commercial game that allows the  player to take screenshots. It saves the screenshots in a particular  directory, naming each one "screenshot#.bmp". The # is a number that  increases with each new file. 
  
  Here's a rough plan of my program:
  
  1. input for user to enter highest numbered screenshot, to determine next "screenshot#.bmp"
  
  2. function that waits for "screenshot#.bmp" to be created and opens it
  
  3. function that performs image manipulations
  
  4. function that saves new image to another directory
  
  5. close program
  
  I want my program to run "behind the scenes" so to speak. The user will  start it, enter the highest numbered screenshot they have, and then  start the game. When they take a new screenshot ingame, the resulting  file will be made into a texture on a 3d model that will appear in the  game world.
  
  I think I can handle the image processing and file writing functions  using PIL, and the ingame model is no problem. But I don't know how to  make my program "wait" for the file to be created. Is this possible,  and if so, can someone show me how to do it?
  
  
  
 			
---------------------------------
Get your own web address for just $1.99/1st yr. We'll help. Yahoo! Small Business.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060827/8e3eaa2c/attachment.html 

From alberto.troiano at gmail.com  Sun Aug 27 18:16:21 2006
From: alberto.troiano at gmail.com (Alberto Troiano)
Date: Sun, 27 Aug 2006 12:16:21 -0400
Subject: [Tutor] Tkinter Icon Suse 10
In-Reply-To: <81a1194c0608251214p2c2b25b6lf46190a0b805c54a@mail.gmail.com>
References: <81a1194c0608251214p2c2b25b6lf46190a0b805c54a@mail.gmail.com>
Message-ID: <81a1194c0608270916v5924329pe1794f543f7e3e6b@mail.gmail.com>

I tried that but still the same error. Any other idea?

Rgds,

Alberto

2006/8/25, Alberto Troiano <alberto.troiano at gmail.com>:
>
> Hi everyone
>
> It's been a long time since I left Python for .NET 2003, but then again I
> need it to make an app under Linux Suse 10 and I have a question
> I'm trying to put an icon to my window...
> Here is the code so far:
>
> ###Start Code###
>
> import Tkinter
> from Tkinter import *
>
> root = Tk()
> root.iconbitmap("Change.ico")
> root.mainloop()
>
> ###End Code###
>
> It works great under Windows but on an Suse 10 Machine it complains about
> the file. Is this because the icon files are not the same as in Windows or
> should I be using another sentence to make it work?
> I know it's a dumb question but I'm out of practice and I couldn't find
> docs on Google (maybe I didn't look where I supposed to)
> Ups..I forgot, I'm using Python 2.4.1
>
> Regards
> --
> Alberto
>



-- 
Alberto Troiano
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060827/9236e78c/attachment.html 

From rdm at rcblue.com  Sun Aug 27 18:30:51 2006
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 27 Aug 2006 09:30:51 -0700
Subject: [Tutor] How to use getch()?
Message-ID: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com>

I'm trying to figure out how to change what a script does while it is 
running, by pressing a key, such as "k". Can getch() be used for 
this? As a first test:

==================
c = 0
while True:
     c += 1
     if getch() == "k":
         break
print c
===================

This produces "NameError: name 'getch' is not defined".

Am I on the wrong track?

Thanks,

Dick Moores
Win XP, Python 2.43




From kent37 at tds.net  Sun Aug 27 18:39:46 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 27 Aug 2006 12:39:46 -0400
Subject: [Tutor] program that 'waits' for file?
In-Reply-To: <20060827151940.91694.qmail@web56115.mail.re3.yahoo.com>
References: <20060827151940.91694.qmail@web56115.mail.re3.yahoo.com>
Message-ID: <44F1CAD2.6080701@tds.net>

Kay White wrote:
> Hello,
>
> I'm trying to make a program that will wait for a specific file to be 
> made by another program, and when that happens it opens and modifies 
> that file.
>
> I want my program to run "behind the scenes" so to speak. The user 
> will start it, enter the highest numbered screenshot they have, and 
> then start the game. When they take a new screenshot ingame, the 
> resulting file will be made into a texture on a 3d model that will 
> appear in the game world.
>
> I think I can handle the image processing and file writing functions 
> using PIL, and the ingame model is no problem. But I don't know how to 
> make my program "wait" for the file to be created. Is this possible, 
> and if so, can someone show me how to do it?
>
It might be enough to have a loop that calls time.sleep() to delay. For 
example,

import time
while True:
  if new_image_available():
    process_image()
  time.sleep(1)

The best timeout is a balance between responsiveness (shorter timeout is 
more responsive) and CPU usage (longer timeout uses less CPU polling for 
files).

This will work if you can either program an exit to the loop (e.g. after 
processing some number of images) or it's OK to kill the program 
externally (e.g. from Windows Task Manager). If you want to be able to 
kill the program from inside the same program it is harder, you need 
some kind of threading.

Kent
>
> ------------------------------------------------------------------------
> Get your own web address for just $1.99/1st yr 
> <%20http://us.rd.yahoo.com/evt=43290/*http://smallbusiness.yahoo.com/domains>. 
> We'll help. Yahoo! Small Business 
> <http://us.rd.yahoo.com/evt=41244/*http://smallbusiness.yahoo.com/>.
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



From kent37 at tds.net  Sun Aug 27 18:51:35 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 27 Aug 2006 12:51:35 -0400
Subject: [Tutor] How to use getch()?
In-Reply-To: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com>
References: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com>
Message-ID: <44F1CD97.1050007@tds.net>

Dick Moores wrote:
> I'm trying to figure out how to change what a script does while it is 
> running, by pressing a key, such as "k". Can getch() be used for 
> this? 
Google 'python getch' or see this recipe by our very own Danny Yoo:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892

Kent


From rdm at rcblue.com  Sun Aug 27 19:11:44 2006
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 27 Aug 2006 10:11:44 -0700
Subject: [Tutor] How to use getch()?
In-Reply-To: <44F1CD97.1050007@tds.net>
References: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com>
	<44F1CD97.1050007@tds.net>
Message-ID: <7.0.1.0.2.20060827100814.01fb9ae8@rcblue.com>

At 09:51 AM 8/27/2006, Kent Johnson wrote:
>Dick Moores wrote:
> > I'm trying to figure out how to change what a script does while it is
> > running, by pressing a key, such as "k". Can getch() be used for
> > this?
>Google 'python getch' or see this recipe by our very own Danny Yoo:

So now I have, thanks to Danny Yoo:

=====================================
class _Getch:
     """Gets a single character from standard input.  Does not echo to the
screen."""
     def __init__(self):
         try:
             self.impl = _GetchWindows()
         except ImportError:
             self.impl = _GetchUnix()

     def __call__(self): return self.impl()

class _GetchWindows:
     def __init__(self):
         import msvcrt

     def __call__(self):
         import msvcrt
         return msvcrt.getch()

c = 0
getch = _Getch()
while True:
     c += 1
     if getch == "k":
         break
print c
================================================

No more errors, but it doesn't do what I wanted. More help, please.

Dick Moores


From h.finucane at gmail.com  Sun Aug 27 19:40:33 2006
From: h.finucane at gmail.com (Henry Finucane)
Date: Sun, 27 Aug 2006 10:40:33 -0700
Subject: [Tutor] Tkinter Icon Suse 10
In-Reply-To: <81a1194c0608270916v5924329pe1794f543f7e3e6b@mail.gmail.com>
References: <81a1194c0608251214p2c2b25b6lf46190a0b805c54a@mail.gmail.com>
	<81a1194c0608270916v5924329pe1794f543f7e3e6b@mail.gmail.com>
Message-ID: <f24e65d60608271040x7f4a54c7s5bd728d1c294366f@mail.gmail.com>

I found this mailing list message to be enlightening:
http://mail.python.org/pipermail/python-list/2005-March/273123.html
On 8/27/06, Alberto Troiano <alberto.troiano at gmail.com> wrote:
> I tried that but still the same error. Any other idea?
>
> Rgds,
>
> Alberto
>
>
> 2006/8/25, Alberto Troiano <alberto.troiano at gmail.com >:
> >
>
> Hi everyone
>
> It's been a long time since I left Python for .NET 2003, but then again I
> need it to make an app under Linux Suse 10 and I have a question
> I'm trying to put an icon to my window...
> Here is the code so far:
>
> ###Start Code###
>
> import Tkinter
> from Tkinter import *
>
> root = Tk()
> root.iconbitmap("Change.ico")
> root.mainloop()
>
> ###End Code###
>
> It works great under Windows but on an Suse 10 Machine it complains about
> the file. Is this because the icon files are not the same as in Windows or
> should I be using another sentence to make it work?
> I know it's a dumb question but I'm out of practice and I couldn't find docs
> on Google (maybe I didn't look where I supposed to)
> Ups..I forgot, I'm using Python 2.4.1
>
> Regards
> --
>  Alberto
>
>
>
> --
> Alberto Troiano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
--H.F.
My penguin is bigger than yours, mister...

From kent37 at tds.net  Sun Aug 27 19:55:01 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 27 Aug 2006 13:55:01 -0400
Subject: [Tutor] How to use getch()?
In-Reply-To: <7.0.1.0.2.20060827100814.01fb9ae8@rcblue.com>
References: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com>	<44F1CD97.1050007@tds.net>
	<7.0.1.0.2.20060827100814.01fb9ae8@rcblue.com>
Message-ID: <44F1DC75.3040100@tds.net>

Dick Moores wrote:
> At 09:51 AM 8/27/2006, Kent Johnson wrote:
>   
>> Dick Moores wrote:
>>     
>>> I'm trying to figure out how to change what a script does while it is
>>> running, by pressing a key, such as "k". Can getch() be used for
>>> this?
>>>       
>> Google 'python getch' or see this recipe by our very own Danny Yoo:
>>     
>
> So now I have, thanks to Danny Yoo:
>
> =====================================
> class _Getch:
>      """Gets a single character from standard input.  Does not echo to the
> screen."""
>      def __init__(self):
>          try:
>              self.impl = _GetchWindows()
>          except ImportError:
>              self.impl = _GetchUnix()
>
>      def __call__(self): return self.impl()
>
> class _GetchWindows:
>      def __init__(self):
>          import msvcrt
>
>      def __call__(self):
>          import msvcrt
>          return msvcrt.getch()
>
> c = 0
> getch = _Getch()
> while True:
>      c += 1
>      if getch == "k":
>   
This should be
  if getch() == "k":

getch is a callable object (it implements __call__()) and is used like a 
function.

If you only want to run on Windows, as your code suggests, just call 
msvcrt.getch() directly. This is a blocking call - it won't return until 
a key is pressed. If you don't want to block, use msvcrt.kbhit() to 
check whether a key is available before calling getch().


>          break
> print c
> ================================================
>
> No more errors, but it doesn't do what I wanted. More help, please.
>
> Dick Moores
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   



From rdm at rcblue.com  Sun Aug 27 20:32:09 2006
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 27 Aug 2006 11:32:09 -0700
Subject: [Tutor] How to use getch()?
In-Reply-To: <44F1DC75.3040100@tds.net>
References: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com>
	<44F1CD97.1050007@tds.net>
	<7.0.1.0.2.20060827100814.01fb9ae8@rcblue.com>
	<44F1DC75.3040100@tds.net>
Message-ID: <7.0.1.0.2.20060827111325.052d5658@rcblue.com>

At 10:55 AM 8/27/2006, Kent Johnson wrote:
>getch is a callable object (it implements __call__()) and is used like a
>function.
>
>If you only want to run on Windows, as your code suggests, just call
>msvcrt.getch() directly. This is a blocking call - it won't return until
>a key is pressed. If you don't want to block, use msvcrt.kbhit() to
>check whether a key is available before calling getch().

Thanks, Kent, but I'm afraid I don't know what a blocking call is.

Yes, I only want to run on Windows.

================
import msvcrt
c = 0
while True:
     c += 1
     (What goes here?) #  Not 'if msvcrt.getch() == "k":', it seems.
         break
print c
================

What I want to do is start the loop spinning, then hit "k" at some 
point, and see what c is.

Dick




From kent37 at tds.net  Sun Aug 27 20:48:11 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 27 Aug 2006 14:48:11 -0400
Subject: [Tutor] How to use getch()?
In-Reply-To: <7.0.1.0.2.20060827111325.052d5658@rcblue.com>
References: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com>	<44F1CD97.1050007@tds.net>	<7.0.1.0.2.20060827100814.01fb9ae8@rcblue.com>	<44F1DC75.3040100@tds.net>
	<7.0.1.0.2.20060827111325.052d5658@rcblue.com>
Message-ID: <44F1E8EB.6030103@tds.net>

Dick Moores wrote:
> At 10:55 AM 8/27/2006, Kent Johnson wrote:
>   
>> getch is a callable object (it implements __call__()) and is used like a
>> function.
>>
>> If you only want to run on Windows, as your code suggests, just call
>> msvcrt.getch() directly. This is a blocking call - it won't return until
>> a key is pressed. If you don't want to block, use msvcrt.kbhit() to
>> check whether a key is available before calling getch().
>>     
>
> Thanks, Kent, but I'm afraid I don't know what a blocking call is.
>   
Blocking I/O is an I/O operation that doesn't return to the caller until 
it completes. In the case of blocking input, the input call (getch() in 
this case) won't return until some data is available. This is not what 
you want - you don't want to press a key each time through the loop, you 
want the loop to free-run until you press 'k', then exit. A non-blocking 
getch() would be perfect - a call that returns a character if one is 
available, but returns some kind of non-character marker if there is no 
character.

I think this will work, using None as the marker for no character available:
def getch_nonblocking():
  if msvcrt.kbhit():
    return msvcrt.getch()
  return None

Then substitute getch_nonblocking() for getch() in your loop below.

Kent
> Yes, I only want to run on Windows.
>
> ================
> import msvcrt
> c = 0
> while True:
>      c += 1
>      (What goes here?) #  Not 'if msvcrt.getch() == "k":', it seems.
>          break
> print c
> ================
>
> What I want to do is start the loop spinning, then hit "k" at some 
> point, and see what c is.
>
> Dick
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   



From janos.juhasz at VELUX.com  Sun Aug 27 21:32:35 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Sun, 27 Aug 2006 21:32:35 +0200
Subject: [Tutor]  Banner
In-Reply-To: <mailman.35293.1156170927.27774.tutor@python.org>
Message-ID: <OF48A5E3B5.128A311B-ONC12571D7.0042C955-C12571D7.006B58C8@velux.com>

Hi all,

I just profiled a little my banner.py.

# PIL_Banner

import Image, ImageFont, ImageDraw

ShowText = 'Python :)'

font = ImageFont.load(r'courier-bold-12.pil')
size = font.getsize(ShowText)
image = Image.new('1', size, 1)
draw = ImageDraw.Draw(image)
draw.text((0, 0), ShowText, font=font)
for rownum in range(size[1]):
    line = []
    for colnum in range(size[0]):
        if image.getpixel((colnum, rownum)): line.append(' '),
        else: line.append('#'),
    print ''.join(line)
 
#image.show()

I have just recognized that, the pil font files are missing from the PIL 
distribution, so I have atteched a pil font, that has to be placed beside 
the script.



So, it will create the next response:

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


Yours sincerely, 
Janos Juhasz 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060827/e146663a/attachment.htm 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: courier-bold-12.png
Type: application/octet-stream
Size: 1370 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060827/e146663a/attachment.obj 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: courier-bold-12.pil
Type: application/octet-stream
Size: 5143 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060827/e146663a/attachment-0001.obj 

From rdm at rcblue.com  Sun Aug 27 21:51:37 2006
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 27 Aug 2006 12:51:37 -0700
Subject: [Tutor] How to use getch()?
In-Reply-To: <44F1E8EB.6030103@tds.net>
References: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com>
	<44F1CD97.1050007@tds.net>
	<7.0.1.0.2.20060827100814.01fb9ae8@rcblue.com>
	<44F1DC75.3040100@tds.net>
	<7.0.1.0.2.20060827111325.052d5658@rcblue.com>
	<44F1E8EB.6030103@tds.net>
Message-ID: <7.0.1.0.2.20060827124324.055a3760@rcblue.com>

At 11:48 AM 8/27/2006, Kent Johnson wrote:
>Blocking I/O is an I/O operation that doesn't return to the caller until
>it completes. In the case of blocking input, the input call (getch() in
>this case) won't return until some data is available. This is not what
>you want - you don't want to press a key each time through the loop, you
>want the loop to free-run until you press 'k', then exit. A non-blocking
>getch() would be perfect - a call that returns a character if one is
>available, but returns some kind of non-character marker if there is no
>character.
>
>I think this will work, using None as the marker for no character available:
>def getch_nonblocking():
>   if msvcrt.kbhit():
>     return msvcrt.getch()
>   return None
>
>Then substitute getch_nonblocking() for getch() in your loop below.
>
>Kent
> > Yes, I only want to run on Windows.
> >
> > ================
> > import msvcrt
> > c = 0
> > while True:
> >      c += 1
> >      (What goes here?) #  Not 'if msvcrt.getch() == "k":', it seems.
> >          break
> > print c
> > ================
> >
> > What I want to do is start the loop spinning, then hit "k" at some
> > point, and see what c is.

============================
import msvcrt

def getch_nonblocking():
     if msvcrt.kbhit():
         return msvcrt.getch()
     return None

c = 0
while True:
     c += 1
     if getch_nonblocking() == "k":
print c
============================

When I run this, wait a bit, then press "k", "k" is printed. In fact, 
whatever I type gets printed.  No break, no c.

Dick


From pythontut at pusspaws.net  Sun Aug 27 22:30:53 2006
From: pythontut at pusspaws.net (Dave S)
Date: Sun, 27 Aug 2006 21:30:53 +0100
Subject: [Tutor] Package problem
Message-ID: <200608272130.53231.pythontut@pusspaws.net>

I am having a problem with packaging. I have setup the PYTHONPATH to the core 
dir with __init__.py in the sub directories. It all worked as expected - then 
I hit a problem :(

I have a module scanDBFs in dir main with a def of getDbfData
The module I am executing is DocViewDoc in QT

DocViewDoc can import with ...
from main.scanDBFs import getDbfDir
and execute it with ...
a = getDbfData(dbf)

So I know it works ... however I prefer to
import main.scanDBFs 
and execute it with  ...
a = scanDBFs.getDbfData(dbf)
So I can see which module it comes from

However when i try the latter I get ...
  File "./DocViewDoc.py", line 80, in AuditEngine
    a = scanDBFs.getDbfData(dbf)
NameError: global name 'scanDBFs' is not defined
ubuntu at ubuntu:~/python_develop/unison/PxQxAudit/QT$

I am stuck ! - The only other thing Is that this is executed within a class, 
but that should not cause a problem.

I have tried a = main.scanDBFs.getDbfData(dbf) but keep hitting the same 
problem.

Any ideas ?

Dave

From rdm at rcblue.com  Mon Aug 28 01:07:42 2006
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 27 Aug 2006 16:07:42 -0700
Subject: [Tutor] How to use getch()?
In-Reply-To: <44F1E8EB.6030103@tds.net>
References: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com>
	<44F1CD97.1050007@tds.net>
	<7.0.1.0.2.20060827100814.01fb9ae8@rcblue.com>
	<44F1DC75.3040100@tds.net>
	<7.0.1.0.2.20060827111325.052d5658@rcblue.com>
	<44F1E8EB.6030103@tds.net>
Message-ID: <7.0.1.0.2.20060827160124.05bad178@rcblue.com>

Alan Gauld has also been trying to help me by direct email. But his suggested

=========================
import msvcrt
c = 0
while True:
     c += 1
     if msvcrt.kbhit():
        if msvcrt.getch() == 'k':
            break
     else: continue
print c
====================

didn't work for me either. I was just about to tell him so, when I 
remembered to try to run it not using IDLE, i.e., by just clicking on 
the script icon (to use the console--is that the term?)  I knew I'd 
have to add a line something like

raw_input("\n\nPress the enter key to exit.")

and when I did the script ran just as I'd hoped!

My thanks to Kent and Alan.

Dick Moores


From rdm at rcblue.com  Mon Aug 28 06:30:29 2006
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 27 Aug 2006 21:30:29 -0700
Subject: [Tutor] How to use getch()?
In-Reply-To: <7.0.1.0.2.20060827160124.05bad178@rcblue.com>
References: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com>
	<44F1CD97.1050007@tds.net>
	<7.0.1.0.2.20060827100814.01fb9ae8@rcblue.com>
	<44F1DC75.3040100@tds.net>
	<7.0.1.0.2.20060827111325.052d5658@rcblue.com>
	<44F1E8EB.6030103@tds.net>
	<7.0.1.0.2.20060827160124.05bad178@rcblue.com>
Message-ID: <7.0.1.0.2.20060827205218.05dd8698@rcblue.com>

So now I have keyPress-b.py. It works well, except that I have to ^C 
to quit it.

======================================
#keyPress-b.py
import msvcrt, time
print \
"""
After pressing Enter to start,
press Space to get first and subsequent measurements of spin.
Use Ctrl+C to quit.
"""
answer = raw_input("Press Enter to start ")
while answer == "":
     c = 0
     timeStart = time.time()
     while True:
         c += 1
         if msvcrt.kbhit():
            if msvcrt.getch() == ' ':
                break
            else:
                continue

     timeEnd = time.time()
     print
     print c, "spins"
     print "Time was %.4g seconds" % (timeEnd - timeStart)
     print "Spin rate was %.f per second" % (c/(timeEnd - timeStart))
print "Bye."
time.sleep(1)
========end of keyPress-b.py=================

I've tried revising in all sorts of ways, but none are satisfactory.
Here's keyPress-b3.py, into which I've added ways to get "Hello" by a 
key press, and also a way to quit by pressing "q".

It's flaky. I usually have to hit Space, "h" or "q" several times (or 
hold them down) before they will work.

========================================
#keyPress-b3.py
import msvcrt, time
print \
"""
After pressing Enter to start,
press Space to get first and subsequent measurements.
Press h to print "Hello".
Press and hold down q to quit.
"""
answer = raw_input("Press Enter to start ")
while answer == "":
     c = 0
     timeStart = time.time()
     while True:
         c += 1
         if msvcrt.kbhit():
            if msvcrt.getch() == ' ':
                break
         if msvcrt.kbhit():
            if msvcrt.getch() == 'h':
                print "Hello"
         if msvcrt.kbhit():
            if msvcrt.getch() == 'q':
                answer = "quit"

     timeEnd = time.time()
     print
     print c, "spins"
     print "Time was %.4g seconds" % (timeEnd - timeStart)
     print "Spin rate was %.f per second" % (c/(timeEnd - timeStart))
print "Bye."
time.sleep(5)
========end of keyPress-b3.py====================

Advice, please, on how to correct the flakiness.

Also, I can't figure out why the FIRST spin measurement of 
spins/second is usually almost double the subsequent measurements. E.g.,

26536 spins
Time was 0.765 seconds
Spin rate was 34688 per second

27632 spins
Time was 1.547 seconds
Spin rate was 17862 per second

Dick Moores
Windows XP, Python 2.43


From dyoo at hkn.eecs.berkeley.edu  Mon Aug 28 07:38:50 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 27 Aug 2006 22:38:50 -0700 (PDT)
Subject: [Tutor] common multiples question
In-Reply-To: <BAY121-F332E2C97E8B923320C3AFDEA440@phx.gbl>
References: <BAY121-F332E2C97E8B923320C3AFDEA440@phx.gbl>
Message-ID: <Pine.LNX.4.64.0608272229230.32738@hkn.eecs.berkeley.edu>



On Thu, 24 Aug 2006, mike viceano wrote:

> hello i need a little help with a common multiple module i am haveing
> problems with the best i can get it is to show the least common multiple i
> think the problem is eather the and command ot the if command

[question cut]

Mike, you asked this question already, a few days ago.

     http://mail.python.org/pipermail/tutor/2006-August/048850.html

You haven't been ignored, and people have responded to you:

     http://mail.python.org/pipermail/tutor/2006-August/048851.html
     http://mail.python.org/pipermail/tutor/2006-August/048855.html
     http://mail.python.org/pipermail/tutor/2006-August/048856.html
     http://mail.python.org/pipermail/tutor/2006-August/048857.html

Did you get their replies yet?  If so, did you understand what they were 
asking?

If you weren't understanding the replies, the right thing to do is to ask 
for clarification on the confusing parts.  I just want to make sure we 
avoid infinite-looping behavior here.

From alan.gauld at btinternet.com  Mon Aug 28 10:57:36 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Aug 2006 09:57:36 +0100
Subject: [Tutor] How to use getch()?
References: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com><44F1CD97.1050007@tds.net><7.0.1.0.2.20060827100814.01fb9ae8@rcblue.com><44F1DC75.3040100@tds.net><7.0.1.0.2.20060827111325.052d5658@rcblue.com><44F1E8EB.6030103@tds.net><7.0.1.0.2.20060827160124.05bad178@rcblue.com>
	<7.0.1.0.2.20060827205218.05dd8698@rcblue.com>
Message-ID: <ecub63$sis$1@sea.gmane.org>

Hi Dick,

I'll move my replies back into the public discussion...

> while answer == "":
>     c = 0
>     timeStart = time.time()
>     while True:
>         c += 1
>         if msvcrt.kbhit():
>            if msvcrt.getch() == ' ':
>                break
>         if msvcrt.kbhit():
>            if msvcrt.getch() == 'h':
>                print "Hello"
>         if msvcrt.kbhit():
>            if msvcrt.getch() == 'q':
>                answer = "quit"

You only need one kbhit to tell you if any key has been hit at all.
Then you can use getch to fetch that key and store it in a variable.
Then the code above turns into:

while True:
   if kbhit(): key = getch()
   if key == ' ': break
   elif key == 'h': print 'hello'
   elif key == 'q': answer = 'quit'

Does that make sense?

Alan G.


From mi.janssen at gmail.com  Mon Aug 28 11:50:55 2006
From: mi.janssen at gmail.com (Michael Janssen)
Date: Mon, 28 Aug 2006 11:50:55 +0200
Subject: [Tutor] Regex help
In-Reply-To: <20060826122712.GA26838@sillyrabbi.dyndns.org>
References: <20060826122712.GA26838@sillyrabbi.dyndns.org>
Message-ID: <1ff2dfbf0608280250x59388d99k40538eb2cc03c531@mail.gmail.com>

On 8/26/06, William O'Higgins Witteman <hmm at woolgathering.cx> wrote:

> I want a case-insensitive, verbose pattern.  I have a long-ish list of
> match criteria (about a dozen distinct cases), which should be all "or",
> so I won't need to be clever with precedence.

BTW I find it easier not to use re.VERBOSE which ignores any
whitespace. Instead I use the silent-string-continuation feature to
put my comments in the right place:

regexp_str = ('one' # matches one
                    '|two' # matches two
                    '|three' # matches three
                    )

there must be no commas: I don't want a tuple but rather the strings
to be concatenated within the brackets. But then:

regexp_tuple = ('one', 'two', 'three')
regexp_str = '|'.join(regexp_tuple)

This way you do not need to manually sets the "|" specialchars.

The python modul /usr/lib/python2.4/tokenize.py comes with lots of
examples, especially with OR'ed pattterns.

regards
Michael

From rdm at rcblue.com  Mon Aug 28 12:18:55 2006
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 28 Aug 2006 03:18:55 -0700
Subject: [Tutor] How to use getch()?
In-Reply-To: <ecub63$sis$1@sea.gmane.org>
References: <7.0.1.0.2.20060827092435.03c31a60@rcblue.com>
	<44F1CD97.1050007@tds.net>
	<7.0.1.0.2.20060827100814.01fb9ae8@rcblue.com>
	<44F1DC75.3040100@tds.net>
	<7.0.1.0.2.20060827111325.052d5658@rcblue.com>
	<44F1E8EB.6030103@tds.net>
	<7.0.1.0.2.20060827160124.05bad178@rcblue.com>
	<7.0.1.0.2.20060827205218.05dd8698@rcblue.com>
	<ecub63$sis$1@sea.gmane.org>
Message-ID: <7.0.1.0.2.20060828031335.059ddc10@rcblue.com>

At 01:57 AM 8/28/2006, Alan Gauld wrote:
> > while answer == "":
> >     c = 0
> >     timeStart = time.time()
> >     while True:
> >         c += 1
> >         if msvcrt.kbhit():
> >            if msvcrt.getch() == ' ':
> >                break
> >         if msvcrt.kbhit():
> >            if msvcrt.getch() == 'h':
> >                print "Hello"
> >         if msvcrt.kbhit():
> >            if msvcrt.getch() == 'q':
> >                answer = "quit"
>
>You only need one kbhit to tell you if any key has been hit at all.
>Then you can use getch to fetch that key and store it in a variable.
>Then the code above turns into:
>
>while True:
>    if kbhit(): key = getch()
>    if key == ' ': break
>    elif key == 'h': print 'hello'
>    elif key == 'q': answer = 'quit'
>
>Does that make sense?

Yes! Now my script runs perfectly. And I can add other keys for doing 
other things on the fly, as it were. That's what I was after.

Thanks, Alan.

Dick




From tiagosaboga at terra.com.br  Mon Aug 28 15:26:00 2006
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Mon, 28 Aug 2006 10:26:00 -0300
Subject: [Tutor] re syntax
Message-ID: <200608281026.00659.tiagosaboga@terra.com.br>

A couple of weeks ago I asked about a way to parse man pages, and Danny and 
Alan answered me with some tips (thanks). I've tryed doclifter, which I 
already knew, but could not yet master it; in fact, it just doesn't work with 
many of the man-pages I tried in my debian system. Anyway, I'm refreshing my 
mind about regular expressions in python, and while trying to document my 
steps, I found a weird syntax problem. The problem is: why the hell do I need 
to escape special caracters when in verbose mode? And why isn't it made clear 
on the re module doc page ( http://docs.python.org/lib/module-re.html ).

I'll just paste below (or above? I never know how to say this in english) my 
ipython's session, you'll see what I mean.

But before that, an extra question to tutors: do you have some advice for 
people like me who like to program but can't spend enough time doing it?

...it's a joke...

In [18]: re.compile("ab").match("abc").group()
Out[18]: 'ab'

In [19]: re.compile("ab", re.X).match("abc").group()
Out[19]: 'ab'

In [20]: re.compile("a\tb").match("a\tbc").group()
Out[20]: 'a\tb'

In [21]: re.compile("a\tb", re.X).match("a\tbc").group()
---------------------------------------------------------------------------
exceptions.AttributeError                            Traceback (most recent 
call last)

/home/tiago/<ipython console>

AttributeError: 'NoneType' object has no attribute 'group'

In [22]: re.compile("a\tb", re.X).match(r"a\tbc").group()
---------------------------------------------------------------------------
exceptions.AttributeError                            Traceback (most recent 
call last)

/home/tiago/<ipython console>

AttributeError: 'NoneType' object has no attribute 'group'

In [23]: re.compile(r"a\tb", re.X).match("a\tbc").group()
Out[23]: 'a\tb'

In [24]: re.compile("a\\tb", re.X).match("a\tbc").group()
Out[24]: 'a\tb'

From kent37 at tds.net  Mon Aug 28 16:12:34 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 28 Aug 2006 10:12:34 -0400
Subject: [Tutor] re syntax
In-Reply-To: <200608281026.00659.tiagosaboga@terra.com.br>
References: <200608281026.00659.tiagosaboga@terra.com.br>
Message-ID: <44F2F9D2.2070904@tds.net>

Tiago Saboga wrote:
> The problem is: why the hell do I need 
> to escape special caracters when in verbose mode? And why isn't it made clear 
> on the re module doc page ( http://docs.python.org/lib/module-re.html ).
>
> I'll just paste below (or above? I never know how to say this in english) my 
> ipython's session, you'll see what I mean.
>   
Below is correct.
> But before that, an extra question to tutors: do you have some advice for 
> people like me who like to program but can't spend enough time doing it?
>
> ...it's a joke...
>   
Hire a personal trainer :-)
> In [18]: re.compile("ab").match("abc").group()
> Out[18]: 'ab'
>
> In [19]: re.compile("ab", re.X).match("abc").group()
> Out[19]: 'ab'
>
> In [20]: re.compile("a\tb").match("a\tbc").group()
> Out[20]: 'a\tb'
>
> In [21]: re.compile("a\tb", re.X).match("a\tbc").group()
> ---------------------------------------------------------------------------
> exceptions.AttributeError                            Traceback (most recent 
> call last)
>
>   
Ahem. Which part of "Whitespace within the pattern is ignored" do you 
not understand? :-)
Your pattern is <character a><character TAB><character b>. Last I 
checked TAB is considered to be whitespace ;)

OK, I know it's a bit more subtle than that, but when you swear at the 
docs I get a little defensive...

In a non-raw string, backslash escapes are interpreted by the Python 
compiler (or parser...). The actual string object seen by your program 
does not contain a backslash. So when you pass a regex of "a\tb", 
re.compile() sees a TAB just as if you typed it in directly. If you 
don't specify re.X, the tab is considered part of the regex and matched. 
If you do specify re.X, the tab is whitespace and ignored as requested.

My recommendation is to *always* use raw strings to specify regexes. In 
a raw string, backslash escapes are not interpreted by the compiler, 
they become part of the actual string. If you use r"a\tb", there is no 
TAB in the string, it is a literal backslash followed by a character 
't'. The regex engine knows how to interpret the standard backslash 
escapes so they will work as you expect, even with the verbose flag.

Kent
> /home/tiago/<ipython console>
>
> AttributeError: 'NoneType' object has no attribute 'group'
>
> In [22]: re.compile("a\tb", re.X).match(r"a\tbc").group()
> ---------------------------------------------------------------------------
> exceptions.AttributeError                            Traceback (most recent 
> call last)
>
> /home/tiago/<ipython console>
>
> AttributeError: 'NoneType' object has no attribute 'group'
>
> In [23]: re.compile(r"a\tb", re.X).match("a\tbc").group()
> Out[23]: 'a\tb'
>
> In [24]: re.compile("a\\tb", re.X).match("a\tbc").group()
> Out[24]: 'a\tb'
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   



From hmm at woolgathering.cx  Mon Aug 28 17:04:24 2006
From: hmm at woolgathering.cx (William O'Higgins Witteman)
Date: Mon, 28 Aug 2006 11:04:24 -0400
Subject: [Tutor] Regex help
In-Reply-To: <44F05060.90004@tds.net>
References: <20060826122712.GA26838@sillyrabbi.dyndns.org>
	<44F05060.90004@tds.net>
Message-ID: <20060828150424.GA6494@sillyrabbi.dyndns.org>

On Sat, Aug 26, 2006 at 09:45:04AM -0400, Kent Johnson wrote:
>William O'Higgins Witteman wrote:
>> I want a case-insensitive, verbose pattern.  I have a long-ish list of
>> match criteria (about a dozen distinct cases), which should be all "or",
>> so I won't need to be clever with precedence.
>
>Vertical bar | is used to separate 'or' cases in a regex. To make it 
>case-insensitive and verbose you can compile with the flags re.VERBOSE 
>and re.IGNORECASE. Use the search method of the compiled regex to search 
>your string. For example,
>
>In [1]: import re
>
>In [2]: rx = re.compile('foo|bar|baz', re.VERBOSE | re.IGNORECASE)
>
>In [3]: rx.search('Foontastic')
>Out[3]: <_sre.SRE_Match object at 0x00C40640>
>
>In [4]: rx.search('raise the BAR')
>Out[4]: <_sre.SRE_Match object at 0x00E901A8>

Thank you for this.  The problem is apparently not my syntax, but
something else.  Here is a pared-down snippet of what I'm doing:

In [1]: import re
    
In [2]: pat = re.compile('''
        ...:copy of
        ...:|
        ...:admin
        ...:''', re.IGNORECASE | re.VERBOSE)

In [3]: pat.search('''\\some\unc\path\Copy of somedarnfilename.exn''')

In [4]:

I don't get my match, and I really think I should.  Can anyone tell me
what I'm missing?  Thanks.
--
yours,

William

From kent37 at tds.net  Mon Aug 28 17:36:18 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 28 Aug 2006 11:36:18 -0400
Subject: [Tutor] Regex help
In-Reply-To: <20060828150424.GA6494@sillyrabbi.dyndns.org>
References: <20060826122712.GA26838@sillyrabbi.dyndns.org>	<44F05060.90004@tds.net>
	<20060828150424.GA6494@sillyrabbi.dyndns.org>
Message-ID: <44F30D72.2050804@tds.net>

William O'Higgins Witteman wrote:
> Thank you for this. The problem is apparently not my syntax, but
> something else.  Here is a pared-down snippet of what I'm doing:
>
> In [1]: import re
>     
> In [2]: pat = re.compile('''
>         ...:copy of
>         ...:|
>         ...:admin
>         ...:''', re.IGNORECASE | re.VERBOSE)
>
> In [3]: pat.search('''\\some\unc\path\Copy of somedarnfilename.exn''')
>
> In [4]:
>
> I don't get my match, and I really think I should.  Can anyone tell me
> what I'm missing?  Thanks.
There are several problems here.

First, when re.VERBOSE claims to ignore whitespace, it isn't kidding. 
Space, tab and newline are all whitespace, so your re is equivalent to

  pat = re.compile('''...:copyof...:|...:admin...:''', re.IGNORECASE)

To get the space between 'copy' and 'of' to be included, you have to escape it, e.g. 'copy\ of'.

But even if you do escape the space, I'm not sure what you expect to match. Colon is not special to regexes (except in non-grouping parentheses (?:...) ), so your regex expects literal colons in the string, which you don't have.

Finally, in your test string you use backslash characters which you mean to be literal backslashes, not character escapes. You should use a raw string for this:
  pat.search(r'''\\some\unc\path\Copy of somedarnfilename.exn''')

Kent


From hugonz-lists at h-lab.net  Fri Aug 25 22:43:33 2006
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Fri, 25 Aug 2006 15:43:33 -0500
Subject: [Tutor] omnicomplete vim python
In-Reply-To: <20060825075726.36876.qmail@web55910.mail.re3.yahoo.com>
References: <20060825075726.36876.qmail@web55910.mail.re3.yahoo.com>
Message-ID: <44EF60F5.8060003@h-lab.net>



anil maran wrote:
> do u guys know how to enable omnicomplete using vim
> for python thanks

Google is your friend, here's a page:

http://www.vim.org/tips/tip.php?tip_id=1311

Actually, I didn't ven know this existed.

Hugo


From hmm at woolgathering.cx  Mon Aug 28 18:11:59 2006
From: hmm at woolgathering.cx (William O'Higgins Witteman)
Date: Mon, 28 Aug 2006 12:11:59 -0400
Subject: [Tutor] Regex help
In-Reply-To: <44F30D72.2050804@tds.net>
References: <20060826122712.GA26838@sillyrabbi.dyndns.org>
	<44F05060.90004@tds.net>
	<20060828150424.GA6494@sillyrabbi.dyndns.org>
	<44F30D72.2050804@tds.net>
Message-ID: <20060828161159.GA6729@sillyrabbi.dyndns.org>

On Mon, Aug 28, 2006 at 11:36:18AM -0400, Kent Johnson wrote:
>William O'Higgins Witteman wrote:
>> Thank you for this. The problem is apparently not my syntax, but
>> something else.  Here is a pared-down snippet of what I'm doing:
>>
>> In [1]: import re
>>     
>> In [2]: pat = re.compile('''
>>         ...:copy of
>>         ...:|
>>         ...:admin
>>         ...:''', re.IGNORECASE | re.VERBOSE)
>>
>> In [3]: pat.search('''\\some\unc\path\Copy of somedarnfilename.exn''')
>>
>> In [4]:
>>
>> I don't get my match, and I really think I should.  Can anyone tell me
>> what I'm missing?  Thanks.
>There are several problems here.
>
>First, when re.VERBOSE claims to ignore whitespace, it isn't kidding. 
>Space, tab and newline are all whitespace, so your re is equivalent to
>
>  pat = re.compile('''copyof|admin''', re.IGNORECASE) [redacted]
>
>To get the space between 'copy' and 'of' to be included, you have to escape it, e.g. 'copy\ of'.

D'oh!  I'm an idjit, thanks for your patience.

>But even if you do escape the space, I'm not sure what you expect to match. Colon is not special to regexes (except in non-grouping parentheses (?:...) ), so your regex expects literal colons in the string, which you don't have.

Um, that is the output of the iPython shell, which I thought you used.
I just copied the output into the window.  It indicates an indent.  I
didn't mean to muddy the waters.  Sorry.

>Finally, in your test string you use backslash characters which you mean to be literal backslashes, not character escapes. You should use a raw string for this:
>  pat.search(r'''\\some\unc\path\Copy of somedarnfilename.exn''')

Excellent, thanks for that.
-- 

yours,

William

From kent37 at tds.net  Mon Aug 28 18:26:48 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 28 Aug 2006 12:26:48 -0400
Subject: [Tutor] Regex help
In-Reply-To: <20060828161159.GA6729@sillyrabbi.dyndns.org>
References: <20060826122712.GA26838@sillyrabbi.dyndns.org>	<44F05060.90004@tds.net>	<20060828150424.GA6494@sillyrabbi.dyndns.org>	<44F30D72.2050804@tds.net>
	<20060828161159.GA6729@sillyrabbi.dyndns.org>
Message-ID: <44F31948.1000404@tds.net>

William O'Higgins Witteman wrote:
> On Mon, Aug 28, 2006 at 11:36:18AM -0400, Kent Johnson wrote:
>   
>> William O'Higgins Witteman wrote:
>>     
>>> Thank you for this. The problem is apparently not my syntax, but
>>> something else.  Here is a pared-down snippet of what I'm doing:
>>>
>>> In [1]: import re
>>>     
>>> In [2]: pat = re.compile('''
>>>         ...:copy of
>>>         ...:|
>>>         ...:admin
>>>         ...:''', re.IGNORECASE | re.VERBOSE)
>>>
>>>       
>> But even if you do escape the space, I'm not sure what you expect to match. Colon is not special to regexes (except in non-grouping parentheses (?:...) ), so your regex expects literal colons in the string, which you don't have.
>>     
>
> Um, that is the output of the iPython shell, which I thought you used.
> I just copied the output into the window.  It indicates an indent.  I
> didn't mean to muddy the waters.  Sorry.

Uh, right. I guess it's my turn to look like an idiot :-) The indenting 
got messed up so it looks like part of the code. (Yeah, that's right, 
I'll blame it on the email software ;)

Kent


From Mike.Hansen at atmel.com  Mon Aug 28 19:38:56 2006
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Mon, 28 Aug 2006 11:38:56 -0600
Subject: [Tutor] tkinter events: <B1-Motion>
Message-ID: <57B026980605A64F9B23484C5659E32E255991@poccso.US.ad.atmel.com>

Yep...across multiple lines. 

Here's a tinyurl of it

http://tinyurl.com/n93au

Mike

> -----Original Message-----
> From: Zsiros Levente [mailto:zslevi at sch.bme.hu] 
> Sent: Friday, August 25, 2006 11:37 PM
> To: Mike Hansen
> Cc: python tutor
> Subject: Re: [Tutor] tkinter events: <B1-Motion>
> 
> The link is broken.
> 
> Mike Hansen wrote:
> 
> > 
> >
> >  
> >
> >>-----Original Message-----
> >>From: tutor-bounces at python.org 
> >>[mailto:tutor-bounces at python.org] On Behalf Of Zsiros Levente
> >>Sent: Thursday, August 24, 2006 2:21 PM
> >>To: Danny Yoo
> >>Cc: python tutor
> >>Subject: Re: [Tutor] tkinter events: <B1-Motion>
> >>
> >>If we're talking about data hiding, let me ask: why Python doesn't 
> >>implement data hiding (I mean 'private' and 'protected')? I 
> >>consider it 
> >>a very important OOP feature, because that makes OOP different from 
> >>structural programming.
> >>
> >>    
> >>
> >
> >This might explain...
> >
> >http://pyfaq.infogami.com/tutor-how-do-i-make-public-and-priv
> ate-attribu
> >tes-and-methods-in-my-classes
> >
> >Mike
**********************************************************************************************
IMPORTANT: The contents of this email and any attachments are confidential. They are intended for the 
named recipient(s) only.
If you have received this email in error, please notify the system manager or the sender immediately and do 
not disclose the contents to anyone or make copies thereof.
*** eSafe scanned this email for viruses, vandals, and malicious content. ***
**********************************************************************************************


From tiagosaboga at terra.com.br  Mon Aug 28 20:29:52 2006
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Mon, 28 Aug 2006 15:29:52 -0300
Subject: [Tutor] re syntax
In-Reply-To: <44F2F9D2.2070904@tds.net>
References: <200608281026.00659.tiagosaboga@terra.com.br>
	<44F2F9D2.2070904@tds.net>
Message-ID: <200608281529.53446.tiagosaboga@terra.com.br>

Em Segunda 28 Agosto 2006 11:12, Kent Johnson escreveu:
> Ahem. Which part of "Whitespace within the pattern is ignored" do you
> not understand? :-)

It's easy ;-) It's the "whitespace" part. I read it as the space character, 
not as any blank character. I should have noted that new lines are ignored 
too, but I didn't. 

(I just looked a little around in my system and it seems like it's not just my 
own opinion, the ascii(7), regex(7) and wctype(3) man pages talk about spaces 
and blank characters, and the latter means what is meant by "whitespace" in 
python docs).

Anyway, you (and Michael, who replied off-list) made it really clear.

Thanks,

Tiago.

From kent37 at tds.net  Mon Aug 28 20:54:52 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 28 Aug 2006 14:54:52 -0400
Subject: [Tutor] re syntax
In-Reply-To: <200608281529.53446.tiagosaboga@terra.com.br>
References: <200608281026.00659.tiagosaboga@terra.com.br>	<44F2F9D2.2070904@tds.net>
	<200608281529.53446.tiagosaboga@terra.com.br>
Message-ID: <44F33BFC.3090401@tds.net>

Tiago Saboga wrote:
> Em Segunda 28 Agosto 2006 11:12, Kent Johnson escreveu:
>   
>> Ahem. Which part of "Whitespace within the pattern is ignored" do you
>> not understand? :-)
>>     
>
> It's easy ;-) It's the "whitespace" part. I read it as the space character, 
> not as any blank character. I should have noted that new lines are ignored 
> too, but I didn't. 
>
> (I just looked a little around in my system and it seems like it's not just my 
> own opinion, the ascii(7), regex(7) and wctype(3) man pages talk about spaces 
> and blank characters, and the latter means what is meant by "whitespace" in 
> python docs).

A 'space character' is the single character \x20. A 'whitespace 
character' is any character in a some set of non-printing (white) 
characters. I guess it is a subtle distinction but it's common usage, 
not just Python; it even has a Wikipedia entry:
http://en.wikipedia.org/wiki/Whitespace_%28computer_science%29

(Not to be confused with Whitespace the programming language, in which 
all *non* white space characters are ignored:
http://en.wikipedia.org/wiki/Whitespace_programming_language :-))

Kent


From oriehurst at hotmail.com  Mon Aug 28 20:58:21 2006
From: oriehurst at hotmail.com (ORIE HURST)
Date: Mon, 28 Aug 2006 14:58:21 -0400
Subject: [Tutor] re syntax
In-Reply-To: <44F33BFC.3090401@tds.net>
Message-ID: <BAY22-F699DD87E51B67F4BAB1D5B6380@phx.gbl>




>From: Kent Johnson <kent37 at tds.net>
>CC: tutor at python.orgdont txtx back> >>
> >
> > It's easy ;-) It's the "whitespace" part. I read it as the space 
>character,
> > not as any blank character. I should have noted that new lines are 
>ignored
> > too, but I didn't.
> >
> > (I just looked a little around in my system and it seems like it's not 
>just my
> > own opinion, the ascii(7), regex(7) and wctype(3) man pages talk about 
>spaces
> > and blank characters, and the latter means what is meant by "whitespace" 
>in
> > python docs).
>
>A 'space character' is the single character \x20. A 'whitespace
>character' is any character in a some set of non-printing (white)
>characters. I guess it is a subtle distinction but it's common usage,
>not just Python; it even has a Wikipedia entry:
>http://en.wikipedia.org/wiki/Whitespace_%28computer_science%29
>
>(Not to be confused with Whitespace the programming language, in which
>all *non* white space characters are ignored:
>http://en.wikipedia.org/wiki/Whitespace_programming_language :-))
>
>Kent
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor

_________________________________________________________________
Don't just search. Find. Check out the new MSN Search! 
http://search.msn.com/


From kayrivertree at yahoo.com  Mon Aug 28 21:44:50 2006
From: kayrivertree at yahoo.com (Kay White)
Date: Mon, 28 Aug 2006 12:44:50 -0700 (PDT)
Subject: [Tutor] making independent program?
Message-ID: <20060828194450.25284.qmail@web56101.mail.re3.yahoo.com>

Hello again,
  
  Can you make programs that don't require an installation of Python to  run? I want my little program to run on other peoples' computers,  without them having to install Python to use it. I've searched through  tutorials and there doesn't seem to be any information about this. 
  
 		
---------------------------------
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1?/min.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060828/1d95dc81/attachment.htm 

From Mike.Hansen at atmel.com  Mon Aug 28 21:49:42 2006
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Mon, 28 Aug 2006 13:49:42 -0600
Subject: [Tutor] making independent program?
Message-ID: <57B026980605A64F9B23484C5659E32E2559C1@poccso.US.ad.atmel.com>

	From: tutor-bounces+mike.hansen=atmel.com at python.org
[mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On Behalf Of Kay
White
	Sent: Monday, August 28, 2006 1:45 PM
	To: tutor at python.org
	Subject: [Tutor] making independent program?
	
	
	Hello again,
	
	Can you make programs that don't require an installation of
Python to run? I want my little program to run on other peoples'
computers, without them having to install Python to use it. I've
searched through tutorials and there doesn't seem to be any information
about this. 
	

	________________________________



http://pyfaq.infogami.com/tutor-how-do-i-make-an-executable-out-of-my-py
thon-program

or
	 
http://tinyurl.com/gtrpa
	 
if the url is too long.

Mike
**********************************************************************************************
IMPORTANT: The contents of this email and any attachments are confidential. They are intended for the 
named recipient(s) only.
If you have received this email in error, please notify the system manager or the sender immediately and do 
not disclose the contents to anyone or make copies thereof.
*** eSafe scanned this email for viruses, vandals, and malicious content. ***
**********************************************************************************************


From alan.gauld at freenet.co.uk  Mon Aug 28 21:55:50 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 28 Aug 2006 20:55:50 +0100
Subject: [Tutor] omnicomplete vim python
References: <20060825075726.36876.qmail@web55910.mail.re3.yahoo.com>
	<44EF60F5.8060003@h-lab.net>
Message-ID: <001a01c6cadb$f67c7d00$0201a8c0@XPpro>

> anil maran wrote:
>> do u guys know how to enable omnicomplete using vim
>> for python thanks
>
> Google is your friend, here's a page:
>
> http://www.vim.org/tips/tip.php?tip_id=1311
>
> Actually, I didn't ven know this existed.

And for those like me who still didn't know what it is:

http://vimdoc.sourceforge.net/htmldoc/version7.html#new-omni-completion

gives the explanation - basically its intellisense for vim...

Alan G. 


From kayrivertree at yahoo.com  Mon Aug 28 22:08:10 2006
From: kayrivertree at yahoo.com (Kay White)
Date: Mon, 28 Aug 2006 13:08:10 -0700 (PDT)
Subject: [Tutor] making independent program?
In-Reply-To: <57B026980605A64F9B23484C5659E32E2559C1@poccso.US.ad.atmel.com>
Message-ID: <20060828200810.296.qmail@web56106.mail.re3.yahoo.com>



Mike Hansen <Mike.Hansen at atmel.com> wrote:   From: tutor-bounces+mike.hansen=atmel.com at python.org
[mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On Behalf Of Kay
White
 Sent: Monday, August 28, 2006 1:45 PM
 To: tutor at python.org
 Subject: [Tutor] making independent program?
 
 
 Hello again,
 
 Can you make programs that don't require an installation of
Python to run? I want my little program to run on other peoples'
computers, without them having to install Python to use it. I've
searched through tutorials and there doesn't seem to be any information
about this. 
 

 ________________________________



http://pyfaq.infogami.com/tutor-how-do-i-make-an-executable-out-of-my-py
thon-program

or
  
http://tinyurl.com/gtrpa
  
if the url is too long.

Mike
**********************************************************************************************
IMPORTANT: The contents of this email and any attachments are confidential. They are intended for the 
named recipient(s) only.
If you have received this email in error, please notify the system manager or the sender immediately and do 
not disclose the contents to anyone or make copies thereof.
*** eSafe scanned this email for viruses, vandals, and malicious content. ***
**********************************************************************************************

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor
Thank you! :)

 		
---------------------------------
How low will we go? Check out Yahoo! Messenger?s low  PC-to-Phone call rates.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060828/8f75ae47/attachment.html 

From alan.gauld at btinternet.com  Mon Aug 28 22:23:16 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Aug 2006 21:23:16 +0100
Subject: [Tutor] tkinter events: <B1-Motion>
References: <44E9B6E0.3060305@sch.bme.hu><Pine.LNX.4.64.0608221249580.27647@hkn.eecs.berkeley.edu>
	<44EE0A39.3070708@sch.bme.hu>
Message-ID: <ecvjbl$e02$1@sea.gmane.org>

I just found this message (because Mike posted the tinyurl....)
and couldn't resist responding...

"Zsiros Levente" <zslevi at sch.bme.hu> wrote
> If we're talking about data hiding, let me ask: why Python doesn't
> implement data hiding (I mean 'private' and 'protected')? I consider 
> it
> a very important OOP feature, because that makes OOP different from
> structural programming.

This is a hot-button of mine...

Why do you think data hiding is important for OOP?
And in particular why do you think it differentiates
OOP from structural techniques?

Data Hiding was not part of the early OOP languages
(Simula, Lisp and the first Smalltalks) it was introduced
first by Smalltalk in (Smalltalk 74 I think) and it was only
when C++ came out that all the public/private nonsense
appeared, followed by protected in C++ v2.0

Many OOP languages do not support data hiding, it is
not necessary for OOP. Data hiding is supported in many
structual languages like the Modula family and ADA.,
but they are not OOP. (The concept was introduced by
David Parnas in 1972 - long before OOP became popular)

The point being that Data hiding is an orthogonal issue
to OOP which relies on encapsulation and polymorphism.
- Encapsulation(*) is the ability to treat the data and methods
  as a single entity - an object.
- Polymorphism is the ability for different objects supporting
  the same protocol to react in different ways to the same
  message.

Inheritance is an optional extra but is usually required to
implement polymorphism...

(*)Some texts get data hiding and encapsulation confused.
Encapsulation as originally applied to OOP is about joining
the data and function together - so fundamental to OOP that
some folks forget its even there as a feature!

Data hiding is about making data available through an API.
That API could be an object's protocol or it could be a
module interface. It's usually a good thing to do, but not
a requirement of OOP.

Rant over,

If anyone wants a more academic review oif the differences
between data hiding (or more correctly, information hiding),
encapsulation and abstraction see this white paper:

http://www.itmweb.com/essay550.htm

by Ed Berard.

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



From alan.gauld at btinternet.com  Mon Aug 28 22:54:22 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Aug 2006 21:54:22 +0100
Subject: [Tutor] making independent program?
References: <20060828194450.25284.qmail@web56101.mail.re3.yahoo.com>
Message-ID: <ecvl5v$k9i$1@sea.gmane.org>

>   Can you make programs that don't require an installation 
> of Python to  run? 

Yes, and no. See below...

> I want my little program to run on other peoples' computers,  
> without them having to install Python to use it. 

There are several ways to fake this, nearly all of them involve 
packaging your script with the Python interpreter and the 
minimum number of modules required by your code into 
a fairly large exe file.

Another option is to use Jython and then compile your code 
to Java bytecode. The resultant program will work on any 
computer with a JVM installed. I believe the same can be 
done using IronPython - the .NET version of Python.

> I've searched through  tutorials and there doesn't seem 
> to be any information about this. 

Thats probably because the most common methods for 
producing an exe file are "non-trivial" to use, especially for 
newbies.  

Look up py2exe on Google...

HTH,

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


From john at fouhy.net  Mon Aug 28 23:32:52 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 29 Aug 2006 09:32:52 +1200
Subject: [Tutor] making independent program?
In-Reply-To: <ecvl5v$k9i$1@sea.gmane.org>
References: <20060828194450.25284.qmail@web56101.mail.re3.yahoo.com>
	<ecvl5v$k9i$1@sea.gmane.org>
Message-ID: <5e58f2e40608281432k19a81b7dl8c379afb0fd421c6@mail.gmail.com>

On 29/08/06, Alan Gauld <alan.gauld at btinternet.com> wrote:
> Thats probably because the most common methods for
> producing an exe file are "non-trivial" to use, especially for
> newbies.
>
> Look up py2exe on Google...

py2exe is not too hard for simple tasks (unless something goes wrong),
especially if you can find someone to throw a sample setup.py at you.
There are people on this list who can help..

-- 
John.

From mjrmonkeyman at aol.com  Mon Aug 28 23:17:42 2006
From: mjrmonkeyman at aol.com (mjrmonkeyman at aol.com)
Date: Mon, 28 Aug 2006 17:17:42 -0400
Subject: [Tutor] How would I make a program that password protects on an
	inactivity timer?
Message-ID: <8C898FE8841E8C0-1538-2DB2@MBLK-M33.sysops.aol.com>

 (This is on Windows, on something called novell, or something close which acts as a logon service)
 
 I recently got into high school and we tested our logins for the computers... That was when I noticed that there's no way to activate password protection on inactivity, or no way to secure the computer at all without logging off (with the old computers, logging off and on takes about 10 mins) and deleting personal files was one of the favorite pranks in middle school. I was wondering how I would go about creating a program, that ran a timer that reset when you move the mouse or hit a key, so that when the timer runs out it freezes all processes except itself and brings itself up to the top, so it unfreezes the processes when you enter the password.
 
 I have a basic understanding of python...mostly what I need to know is how to freeze and unfreeze the processes, and bring the program to the top. Also, If there is a way to turn off/restart the computer, or log off (of novell) I'd appreciate it if you could tell me.
 
 If this is not possible, is there any way to end/restart the explorer.exe program? If not, is there any other way you would reccomend securing the computer? (not a program thats downloaded, we have to prove that everything we download is for educational purposes @_@)
  
________________________________________________________________________
Check out AOL.com today. Breaking news, video search, pictures, email and IM. All on demand. Always Free.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060828/53d6cddf/attachment.htm 

From john at fouhy.net  Tue Aug 29 00:57:53 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 29 Aug 2006 10:57:53 +1200
Subject: [Tutor] How would I make a program that password protects on an
	inactivity timer?
In-Reply-To: <8C898FE8841E8C0-1538-2DB2@MBLK-M33.sysops.aol.com>
References: <8C898FE8841E8C0-1538-2DB2@MBLK-M33.sysops.aol.com>
Message-ID: <5e58f2e40608281557y2ec537e5h54a510c766546339@mail.gmail.com>

On 29/08/06, mjrmonkeyman at aol.com <mjrmonkeyman at aol.com> wrote:
> If this is not possible, is there any way to end/restart the explorer.exe
> program? If not, is there any other way you would reccomend securing the
> computer? (not a program thats downloaded, we have to prove that everything
> we download is for educational purposes @_@)

Hmm, one thing that might work, as a way of manually locking your
screen: write a Tkinter app that pops up a password dialog and exits
when you type in the correct password.  Then set the global grab for
the Entry widget.

I haven't actually used global grab before (it's pretty bad manners!),
but I think it will restrict all input to itself, and refuse attempts
to let anything else have focus. Not certain, though.  But it may be
worth a try.

-- 
John.

From mjrmonkeyman at aol.com  Tue Aug 29 01:11:14 2006
From: mjrmonkeyman at aol.com (mjrmonkeyman at aol.com)
Date: Mon, 28 Aug 2006 19:11:14 -0400
Subject: [Tutor] Securing a Computer...
Message-ID: <8C8990E64EFDD20-288-44F9@MBLK-M30.sysops.aol.com>

 I just got into high school, and the network and all the computers aren't secure at all...I'm trying to make a program that password protects the computer after an inactivity time, but there are some specific things I can't find how I'm supposed to do it.
 
 1. Freeze/unfreeze Windows processes OR start/end Windows processes (Preferrably the first)
 2. Turn off/restart the computer
 3. I can probably find this somewhere else, but I surprisingly haven't: Make a timer that resets when the mouse moves or a key is pressed (That still resets when the window is minimized, inactive, etc.)
  
________________________________________________________________________
Check out AOL.com today. Breaking news, video search, pictures, email and IM. All on demand. Always Free.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060828/fc0f0851/attachment.html 

From anilmrn at yahoo.com  Tue Aug 29 03:00:59 2006
From: anilmrn at yahoo.com (anil maran)
Date: Mon, 28 Aug 2006 18:00:59 -0700 (PDT)
Subject: [Tutor] omnicomplete vim python
In-Reply-To: <001a01c6cadb$f67c7d00$0201a8c0@XPpro>
Message-ID: <20060829010059.2796.qmail@web55907.mail.re3.yahoo.com>

i want some form of suggestion or autocompletion
so if i say
import aspell
and then type
aspell.
i know what are available without running to pyshell or some interpreter
and aspell.Dict(
should suggest wat are the possible arguments


Alan Gauld <alan.gauld at freenet.co.uk> wrote: > anil maran wrote:
>> do u guys know how to enable omnicomplete using vim
>> for python thanks
>
> Google is your friend, here's a page:
>
> http://www.vim.org/tips/tip.php?tip_id=1311
>
> Actually, I didn't ven know this existed.

And for those like me who still didn't know what it is:

http://vimdoc.sourceforge.net/htmldoc/version7.html#new-omni-completion

gives the explanation - basically its intellisense for vim...

Alan G. 

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


 		
---------------------------------
 All-new Yahoo! Mail - Fire up a more powerful email and get things done faster.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060828/2e5c1d0e/attachment.htm 

From conradbellman at gmail.com  Tue Aug 29 01:39:45 2006
From: conradbellman at gmail.com (Conrad Bellman)
Date: Mon, 28 Aug 2006 16:39:45 -0700
Subject: [Tutor] interested in python
Message-ID: <88cad3b50608281639g2435310fn1f4b0e918f83bd7b@mail.gmail.com>

I am just wondering if I would be able to hire a tutor to learn Python or
not, I know there is a tutorial, but I dont seem to be learning throught
tuturials, my questions is there any tutors Online & Phone, i reside in
Canada , Ontario , Brampton.

conradbellman at gmail.com   thank you very much for your time and patients.

Respectfully

Conrad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060828/d298fb71/attachment.html 

From alan.gauld at freenet.co.uk  Tue Aug 29 09:25:40 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 29 Aug 2006 08:25:40 +0100
Subject: [Tutor] omnicomplete vim python
References: <20060829010059.2796.qmail@web55907.mail.re3.yahoo.com>
Message-ID: <001301c6cb3c$554b91d0$0201a8c0@XPpro>

>i want some form of suggestion or autocompletion
> so if i say
> import aspell
> and then type
> aspell.
> i know what are available without running to pyshell or some 
> interpreter
> and aspell.Dict(
> should suggest wat are the possible arguments

This isn't answering Anil's question but I'm curious.
I've had access to editors that do this kind of thing since 1988
when I first encountered DECs LSE(Language Sensitive Editor)
for the VAX. and in a more limited form C and Lisp modes on emacs.
Then it became popular on PC editors in Visual Studio and
the Borland tools.

But does anyone actually use this feature? I know I don't, in
fact I usually turn it off because I find it distracting! I usually
know what attributes or methods I need to call, and the
parameters that I need to pass often depend on context anyway
so the tools often get it wrong.

So I'm curious, how many folks actively use these so-called
productivity features like intellisense/omnicomplete?

BTW I don't mind toopltips - where they tell you the signature
of a function but don't fill it in... Its the autocomplete feature 
I've
never found helpful.

Alan G



From alan.gauld at freenet.co.uk  Tue Aug 29 12:15:51 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 29 Aug 2006 11:15:51 +0100
Subject: [Tutor] How would I make a program that password protects on
	aninactivity timer?
References: <8C898FE8841E8C0-1538-2DB2@MBLK-M33.sysops.aol.com>
Message-ID: <001801c6cb54$1bed0f50$0201a8c0@XPpro>

> (This is on Windows, on something called novell, 
> or something close which acts as a logon service)

Hmm, Novell, the second biggest networking company in the 
world might not be too pleased with that description... :-)

Novell provides a comprehensive network resource 
and inventory management service as well as a directory 
service and shared storage and alarm management. 
If you are not on Win2K or XP its probably pretty 
fundamental to your entire network operation.

It also provides logon services including such features as
password history protection, password timeouts, 
password composition rules etc. But it primarily 
operates at the network level, it will prevent you 
accessing the network rather than the PC (although 
it can do the latter if you have the appropriate client 
installed).


> I noticed that there's no way to activate password 
> protection on inactivity, or no way to secure the 
> computer at all without logging off 

This will depend on the OS. If it is Windows NT, 
Win 2000 or XP you can do a lot of this from 
Windows. On older Windows versions the protection 
is still there but not as strong. Simply activate 
the Screen saver and set up a password.

> creating a program, that ran a timer that reset 
> when you move the mouse or hit a key, 

This is possible by detecting Windows events 
and resetting the time, but its not that easy and 
not really necessary. Windows provides all the 
protection you should need.

> I have a basic understanding of python...mostly 
> what I need to know is how to freeze and 
> unfreeze the processes, and bring the 
> program to the top. 

You shouldn't freeze processes but you do want to 
bar access to them, typically by forcing your program 
to the front and swallowing all the usual bypass 
mechanisms such as Ctrl-Alt-Del, Alt-Tab etc.

> Also, If there is a way to turn off/restart the computer, 
> or log off (of novell) I'd appreciate it if you could tell me.

Search MSDN for that one, there is a way but I confess 
I've forgotten how!

> If this is not possible, is there any way to end/restart 
> the explorer.exe program? 

Thats possible too but not recommended, you mess up 
all the users session settings!

I'd try the screen saver settings first, its much easier!

Alan G.


From alan.gauld at freenet.co.uk  Tue Aug 29 12:41:20 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 29 Aug 2006 11:41:20 +0100
Subject: [Tutor] interested in python
References: <88cad3b50608281639g2435310fn1f4b0e918f83bd7b@mail.gmail.com>
Message-ID: <004001c6cb57$aa631010$0201a8c0@XPpro>

Hi Conrad,

Welcome to the tutor list.

>I am just wondering if I would be able to hire a tutor to learn 
>Python or

We come free.

> not, I know there is a tutorial, but I dont seem to be learning 
> throught
> tuturials,

OK, The way this list works is you pick one (or more!) tutorials
and try to work through them. When you hit something you
don't understand you ask a question on the list and  whoever
thinks they know the answer will send a reply.

The questions can be specific to code:

"here's what I wrote but it doesn't work - Here is the error
message I got"
- it's very important to include the error messages!

or conceptual, eg:

"I don't understand how parameters work with functions..."

> my questions is there any tutors Online

This list operates online only

> i reside in  Canada , Ontario , Brampton.

And the internet renders that irrelevant :-)

Regards from Scotland,

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


From amonroe at columbus.rr.com  Tue Aug 29 12:54:19 2006
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Tue, 29 Aug 2006 06:54:19 -0400
Subject: [Tutor] How would I make a program that password protects on
	aninactivity timer?
In-Reply-To: <001801c6cb54$1bed0f50$0201a8c0@XPpro>
References: <8C898FE8841E8C0-1538-2DB2@MBLK-M33.sysops.aol.com>
	<001801c6cb54$1bed0f50$0201a8c0@XPpro>
Message-ID: <158-1762168204.20060829065419@columbus.rr.com>


> I'd try the screen saver settings first, its much easier!

This is not Python specific, but very informative:
http://www.codeproject.com/cpp/holsavers.asp

Alan


From tim.golden at viacom-outdoor.co.uk  Tue Aug 29 13:08:15 2006
From: tim.golden at viacom-outdoor.co.uk (Tim Golden)
Date: Tue, 29 Aug 2006 12:08:15 +0100
Subject: [Tutor] program that 'waits' for file?
Message-ID: <CCAC78D42E32184F8E26DC163DB98306C1B3EB@vogbs009.gb.vo.local>

[Kay White]

| I'm trying to make a program that will wait for a specific 
| file to be made by another program, and when that happens it 
| opens and modifies that file. The other program is a 
| commercial game that allows the player to take screenshots. 
| It saves the screenshots in a particular directory, naming 
| each one "screenshot#.bmp". The # is a number that increases 
| with each new file. 

Given the ".bmp" suffix, I'm going to assume you're running
on some flavour of Windows. In that case, you might want to
make use of some form of directory-monitoring (possibly inside
a thread) which would watch the directory where the screenshots
are saved and reacts when a file is created within.

Have a look at:

http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_c
hanges.html

for a few possibilities.

TJG

________________________________________________________________________
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________

From Mike.Hansen at atmel.com  Tue Aug 29 15:57:46 2006
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Tue, 29 Aug 2006 07:57:46 -0600
Subject: [Tutor] omnicomplete vim python
Message-ID: <57B026980605A64F9B23484C5659E32E2E77FB@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Alan Gauld
> Sent: Tuesday, August 29, 2006 1:26 AM
> To: anil maran
> Cc: tutor at python.org
> Subject: Re: [Tutor] omnicomplete vim python
> 
[...]
> 
> This isn't answering Anil's question but I'm curious.
> I've had access to editors that do this kind of thing since 1988
> when I first encountered DECs LSE(Language Sensitive Editor)
> for the VAX. and in a more limited form C and Lisp modes on emacs.
> Then it became popular on PC editors in Visual Studio and
> the Borland tools.
> 
> But does anyone actually use this feature? I know I don't, in
> fact I usually turn it off because I find it distracting! I usually
> know what attributes or methods I need to call, and the
> parameters that I need to pass often depend on context anyway
> so the tools often get it wrong.
> 
> So I'm curious, how many folks actively use these so-called
> productivity features like intellisense/omnicomplete?
> 
> BTW I don't mind toopltips - where they tell you the signature
> of a function but don't fill it in... Its the autocomplete feature 
> I've
> never found helpful.
> 
> Alan G

I switch between Komodo and VIM. Komodo has autocomplete. I've never
found it distracting. It's kind of useful. I haven't explored
omnicomplete in VIM yet. I still just ctrl-n instead of using the new
omnicomplete stuff. I like the background syntax checking in Komodo. It
has been helping me clean up problems before I get around to running
Pyflakes on the program. 

BTW, the next version of Komodo will have vi key-bindings!

Mike  
**********************************************************************************************
IMPORTANT: The contents of this email and any attachments are confidential. They are intended for the 
named recipient(s) only.
If you have received this email in error, please notify the system manager or the sender immediately and do 
not disclose the contents to anyone or make copies thereof.
*** eSafe scanned this email for viruses, vandals, and malicious content. ***
**********************************************************************************************


From kent37 at tds.net  Tue Aug 29 16:16:40 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 29 Aug 2006 10:16:40 -0400
Subject: [Tutor] How would I make a program that password protects on
 an	inactivity timer?
In-Reply-To: <8C898FE8841E8C0-1538-2DB2@MBLK-M33.sysops.aol.com>
References: <8C898FE8841E8C0-1538-2DB2@MBLK-M33.sysops.aol.com>
Message-ID: <44F44C48.9090401@tds.net>

mjrmonkeyman at aol.com wrote:
>  If this is not possible, is there any way to end/restart the explorer.exe program? If not, is there any other way you would reccomend securing the computer? (not a program thats downloaded, we have to prove that everything we download is for educational purposes @_@)

This might be of interest:
http://tgolden.sc.sabren.com/python/win32_how_do_i/lock_my_workstation.html

Kent


From j.gamman at gmail.com  Tue Aug 29 16:58:02 2006
From: j.gamman at gmail.com (Joe Gamman)
Date: Tue, 29 Aug 2006 15:58:02 +0100
Subject: [Tutor] thanks
Message-ID: <7c4cfdc0608290758l7c4a926bx895044d9d866e04b@mail.gmail.com>

just a quick note to say thanks to all the replies i got from the
community.  once again, my idea has already been done, and far better than i
could have imagined.
i'm off to wander aimlessly around the useless python site ;-)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060829/f6e57d8d/attachment.htm 

From andrew.arobert at gmail.com  Tue Aug 29 18:07:02 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Tue, 29 Aug 2006 12:07:02 -0400
Subject: [Tutor] omnicomplete vim python
In-Reply-To: <57B026980605A64F9B23484C5659E32E2E77FB@poccso.US.ad.atmel.com>
References: <57B026980605A64F9B23484C5659E32E2E77FB@poccso.US.ad.atmel.com>
Message-ID: <44F46626.9060301@gmail.com>

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



Mike Hansen wrote:
>  
> 
>> -----Original Message-----
>> From: tutor-bounces at python.org 
>> [mailto:tutor-bounces at python.org] On Behalf Of Alan Gauld
>> Sent: Tuesday, August 29, 2006 1:26 AM
>> To: anil maran
>> Cc: tutor at python.org
>> Subject: Re: [Tutor] omnicomplete vim python
>>
> [...]
>> This isn't answering Anil's question but

ditto .. but you may wish to consider the following python add-on for VIM.

http://www.vim.org/scripts/script.php?script_id=790

It includes:

Enhanced version of the original (from vim6.1) python.vim for Python
programming language.

The changes since the original python.vim are:

- - changed strings highlighting;
- - enhanced special symbols highlighting inside strings;
- - enhanced numbers highlighting;
- - added optional highlighting for %-formatting inside strings;
- - added highlighting for some error conditions (wrong symbols in source
file,
  mixing spaces and tabs, wrong number values,
  wrong %-formatting inside strings);
- - added highlighting for magic comments: source code encoding
  and #! (executable) strings;
- - added highlighting for new exceptions and builtins introduced in
python 2.3, 2.4 and 2.5;
- - added highlighting for doctests;
- - added highlighting for new @decorator syntax introduced in Python 2.4a2;
- - added highlighting for trailing-space errors (triggered by new
  option: python_highlight_space_errors);
- - added highlighting for variable name errors;
- - added highlighting for hex number errors;
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFE9GYjDvn/4H0LjDwRAtecAJ4oWEqO5CQN0vLyFOKpRyb7PtRhSACgr9gJ
v4MQqzHAFdk8OJMHulpW9uM=
=fces
-----END PGP SIGNATURE-----

From alan.gauld at btinternet.com  Tue Aug 29 19:47:51 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Aug 2006 18:47:51 +0100
Subject: [Tutor] omnicomplete vim python
References: <57B026980605A64F9B23484C5659E32E2E77FB@poccso.US.ad.atmel.com>
	<44F46626.9060301@gmail.com>
Message-ID: <ed1uk8$jft$1@sea.gmane.org>

Thanks for that, it definitely improves a few things, well worth 
having.
Thanks.

And the other advantage of this thread is it let me know vim 7 is
out - yippee! :-)

Alan G.

"Andrew Robert" <andrew.arobert at gmail.com> wrote in message 
news:44F46626.9060301 at gmail.com...
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
>
>
> Mike Hansen wrote:
>>
>>
>>> -----Original Message-----
>>> From: tutor-bounces at python.org
>>> [mailto:tutor-bounces at python.org] On Behalf Of Alan Gauld
>>> Sent: Tuesday, August 29, 2006 1:26 AM
>>> To: anil maran
>>> Cc: tutor at python.org
>>> Subject: Re: [Tutor] omnicomplete vim python
>>>
>> [...]
>>> This isn't answering Anil's question but
>
> ditto .. but you may wish to consider the following python add-on 
> for VIM.
>
> http://www.vim.org/scripts/script.php?script_id=790
>
> It includes:
>
> Enhanced version of the original (from vim6.1) python.vim for Python
> programming language.
>
> The changes since the original python.vim are:
>
> - - changed strings highlighting;
> - - enhanced special symbols highlighting inside strings;
> - - enhanced numbers highlighting;
> - - added optional highlighting for %-formatting inside strings;
> - - added highlighting for some error conditions (wrong symbols in 
> source
> file,
>  mixing spaces and tabs, wrong number values,
>  wrong %-formatting inside strings);
> - - added highlighting for magic comments: source code encoding
>  and #! (executable) strings;
> - - added highlighting for new exceptions and builtins introduced in
> python 2.3, 2.4 and 2.5;
> - - added highlighting for doctests;
> - - added highlighting for new @decorator syntax introduced in 
> Python 2.4a2;
> - - added highlighting for trailing-space errors (triggered by new
>  option: python_highlight_space_errors);
> - - added highlighting for variable name errors;
> - - added highlighting for hex number errors;
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.2.1 (MingW32)
> Comment: GnuPT 2.7.2
>
> iD8DBQFE9GYjDvn/4H0LjDwRAtecAJ4oWEqO5CQN0vLyFOKpRyb7PtRhSACgr9gJ
> v4MQqzHAFdk8OJMHulpW9uM=
> =fces
> -----END PGP SIGNATURE-----
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



From billburns at pennswoods.net  Tue Aug 29 21:47:40 2006
From: billburns at pennswoods.net (Bill Burns)
Date: Tue, 29 Aug 2006 15:47:40 -0400
Subject: [Tutor] How would I make a program that password protects on
 aninactivity timer?
In-Reply-To: <001801c6cb54$1bed0f50$0201a8c0@XPpro>
References: <8C898FE8841E8C0-1538-2DB2@MBLK-M33.sysops.aol.com>
	<001801c6cb54$1bed0f50$0201a8c0@XPpro>
Message-ID: <44F499DC.3010004@pennswoods.net>

[Alan Gauld]
> I'd try the screen saver settings first, its much easier!
> 

As Alan has stated above, the screen saver idea is probably the easiest
way to go, but personally... I always to do it the the hard way :-)

Using ideas from eariler posts (regarding Windows events and ctypes),
here's my attempt.

Warning: This is an initial start that you can fix-up and build upon.

Suggestions welcome.

Bill

<code>
"""
Locks a Windows WorkStation if a user is idle for a specific
amount of time.

My definition of idle is:
1). No keys have been pressed.
2). The mouse has not been moved.

To run this, you will need to install:
pywin32     -> http://sourceforge.net/projects/pywin32/
ctypes      -> http://sourceforge.net/projects/ctypes/
pyHook      -> http://www.cs.unc.edu/Research/assist/developer.shtml

This works for me on Windows 2000 Pro SP4 using:
Python 2.4.3
pywin32 Build 208
ctypes-0.9.6
pyHook-1.4

Things that should probably be fixed:
1). This only runs once. When we hit the limit in idleTimer(), we
break out of the loop and never go back. Ideally, it should reset /
restart when we logon again...
2). Do we need a method to stop the message pump? Right now, it
just runs indefinitely.
"""

import time
from threading import Thread
import Queue

import pythoncom
import ctypes
import win32api
import pyHook

def idleTimer(limit, queue):
     # Count how long we are idle by incrementing our
     # queue. The mouse and keyboard events will 'reset'
     # the queue to zero. If the limit is hit, we lock
     # the WorkStation.
     while True:
         idleTime = queue.get_nowait()
         print "We've been idle for %s second(s)." % (idleTime)
         if idleTime == limit:
             # Lock the WorkStation.
             ctypes.windll.user32.LockWorkStation()
             break
         queue.put(idleTime + 1)
         time.sleep(1)

def mouseEvent(event):
     # If the mouse moves, this get fired.
     if event.MessageName == 'mouse move':
         try:
             # The mouse was moved, so 'reset' the timer.
             # Note: When the mouse is moving, this function
             # gets hit 'a lot'... Initially, I was only
             # doing queue.put(0), but that just clobbered
             # the queue with zeros. To combat that, I do
             # a get() then a put(). There's gotta be a
             # better way....
             queue.get_nowait()
             queue.put(0)
             # We don't want to stop these events, so we
             # need to return True. Don't change this!
             return True
         except Queue.Empty:
             # Again, don't change this!
             return True

def keyboardEvent(event):
     # Same as above except for key presses.
     if event.MessageName == 'key down':
         try:
             queue.get_nowait()
             queue.put(0)
             return True
         except Queue.Empty:
             return True

if __name__ == '__main__':
     # Set the idle limit (in seconds).
     idleLimit = 10
     # Make a queue.
     queue = Queue.Queue()
     # Put an initial value into the queue.
     queue.put(0)
     # Fire-up our idle timer.
     timer = Thread(target=idleTimer, args=(idleLimit, queue))
     timer.setDaemon(True)
     timer.start()
     # Hook both the mouse and keyboard events.
     # Create the hook manager.
     hm = pyHook.HookManager()
     # Watch for these events.
     hm.MouseAll = mouseEvent
     hm.KeyDown = keyboardEvent
     # Set the hooks.
     hm.HookMouse()
     hm.HookKeyboard()
     # Wait forever.
     pythoncom.PumpMessages()

</code>






From billburns at pennswoods.net  Tue Aug 29 22:30:03 2006
From: billburns at pennswoods.net (Bill Burns)
Date: Tue, 29 Aug 2006 16:30:03 -0400
Subject: [Tutor] How would I make a program that password protects on
 aninactivity timer?
In-Reply-To: <44F499DC.3010004@pennswoods.net>
References: <8C898FE8841E8C0-1538-2DB2@MBLK-M33.sysops.aol.com>	<001801c6cb54$1bed0f50$0201a8c0@XPpro>
	<44F499DC.3010004@pennswoods.net>
Message-ID: <44F4A3CB.6090809@pennswoods.net>

[Bill Burns]

> import pythoncom
> import ctypes
> import win32api

<snip>

You can lose the win32api import in my code.

Initially, I was using `win32api.ExitWindowsEx(0, 0)` to logout, but
after Kent posted the link to ctypes.windll.user32.LockWorkStation(), I
switched to the cytpes method. I just forgot to pull the import.

Bill


From osullivanm at redlandscc.edu  Tue Aug 29 20:51:01 2006
From: osullivanm at redlandscc.edu (Maureen OSullivan)
Date: Tue, 29 Aug 2006 13:51:01 -0500
Subject: [Tutor] Install problems
Message-ID: <179959062F6BD2419FF5E50BBB05711FD033D6@MERCURY.redlandscc.edu>

When I tried to install Windows/x86 I got this message:  Internal Error
2229. ,Control, SELECT 'Control', 'Type', 'X', 'Y', 'Width', 'Height',
'Attributes', 'Property', 'Text', 'Control_Next', 'Help' FROM 'Control'
WHERE 'Dialog_'=?

 

Can you tell me how to get Python to install. 

 

Thanks

Maureen

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060829/182b56aa/attachment.html 

From singletoned at gmail.com  Tue Aug 29 22:39:49 2006
From: singletoned at gmail.com (Ed Singleton)
Date: Tue, 29 Aug 2006 21:39:49 +0100
Subject: [Tutor] Unicode problems
Message-ID: <34bb7f5b0608291339s619c279di8c5c9cd7c6bf6e1a@mail.gmail.com>

I've been having unicode problems in python on Mac OS 10.4.

I googled for it and found a good page in Dive Into Python that I
thought might help
(http://www.diveintopython.org/xml_processing/unicode.html).

I tried following the instructions and set my default encoding using a
sitecustomize.py, but got the following:

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> s = u'La Pe\xf1a'
>>> print s
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in
position 5: ordinal not in range(128)
>>>

As I understand it, that should work.  I tried using different
character sets (like latin-1, etc), but none of them work.

The main problem  I am having is in getting python not to give an
error when it encounters a sterling currency sign (?, pound sign here
in UK), which I suspect might be some wider problem on the mac as when
I type that character in the terminal it shows a # (but in Python it
shows a ?).

Any help, or hints greatly appreciated.

Thanks

Ed

From amadeo.bellotti at gmail.com  Tue Aug 29 23:06:35 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Tue, 29 Aug 2006 17:06:35 -0400
Subject: [Tutor] File IO
Message-ID: <d7253a230608291406s7992d77fl20f5e8e234420bb8@mail.gmail.com>

Ok im trying to create a file that the user chooses the name of and print a
varible that is a string to the text file. but for some reason whne i do
this code:

FILE = open(filename, "w")
FILE.write(puzzleanswers)
FILE.close()

it doesnt write anything does anyone know how to fix it  so it works?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060829/0c8199af/attachment.htm 

From kent37 at tds.net  Tue Aug 29 23:09:34 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 29 Aug 2006 17:09:34 -0400
Subject: [Tutor] Unicode problems
In-Reply-To: <34bb7f5b0608291339s619c279di8c5c9cd7c6bf6e1a@mail.gmail.com>
References: <34bb7f5b0608291339s619c279di8c5c9cd7c6bf6e1a@mail.gmail.com>
Message-ID: <44F4AD0E.8050104@tds.net>

Ed Singleton wrote:
> I've been having unicode problems in python on Mac OS 10.4.
>
> I googled for it and found a good page in Dive Into Python that I
> thought might help
> (http://www.diveintopython.org/xml_processing/unicode.html).
>
> I tried following the instructions and set my default encoding using a
> sitecustomize.py, but got the following:
>
>   
>>>> import sys
>>>> sys.getdefaultencoding()
>>>>         
> 'utf-8'
>   
>>>> s = u'La Pe\xf1a'
>>>> print s
>>>>         
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in
> position 5: ordinal not in range(128)
>   
>
> As I understand it, that should work.  I tried using different
> character sets (like latin-1, etc), but none of them work.
>   
I'm not sure Dive into Python is correct. Here is what I get on Windows:
In [1]: s = u'La Pe\xf1a'

In [2]: print s
La Pe?a

In [3]: import sys

In [4]: sys.getdefaultencoding()
Out[4]: 'ascii'

In [5]: sys.stdout.encoding
Out[5]: 'cp437'

I think print converts to the encoding of sys.stdout, not the default 
encoding. What is the value of sys.stdout.encoding on your machine?

Kent
> The main problem  I am having is in getting python not to give an
> error when it encounters a sterling currency sign (?, pound sign here
> in UK), which I suspect might be some wider problem on the mac as when
> I type that character in the terminal it shows a # (but in Python it
> shows a ?).

Where is the pound sign coming from? What encoding is it in? What do you 
mean, in Python it shows ?? You said Python gives an error...Fixing your 
first problem may not help this one without a bit more digging... (BTW 
in the US a # is sometimes called a 'pound sign', maybe the computer is 
trying to translate for you ;) - though it is for pound weight, not 
pound sterling.)

Kent


From kent37 at tds.net  Tue Aug 29 23:15:19 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 29 Aug 2006 17:15:19 -0400
Subject: [Tutor] File IO
In-Reply-To: <d7253a230608291406s7992d77fl20f5e8e234420bb8@mail.gmail.com>
References: <d7253a230608291406s7992d77fl20f5e8e234420bb8@mail.gmail.com>
Message-ID: <44F4AE67.3070708@tds.net>

Amadeo Bellotti wrote:
> Ok im trying to create a file that the user chooses the name of and print a
> varible that is a string to the text file. but for some reason whne i do
> this code:
>
> FILE = open(filename, "w")
> FILE.write(puzzleanswers)
> FILE.close()
>
> it doesnt write anything does anyone know how to fix it  so it works?

I would
print filename
print puzzleanswers

to make sure you know what should happen.

Kent


From amadeo.bellotti at gmail.com  Tue Aug 29 23:34:08 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Tue, 29 Aug 2006 17:34:08 -0400
Subject: [Tutor] File IO
In-Reply-To: <44F4AE67.3070708@tds.net>
References: <d7253a230608291406s7992d77fl20f5e8e234420bb8@mail.gmail.com>
	<44F4AE67.3070708@tds.net>
Message-ID: <d7253a230608291434i59bb004fh9b18c2192ccf72d8@mail.gmail.com>

i do and they have writing but its just not printing it at all

On 8/29/06, Kent Johnson <kent37 at tds.net> wrote:
>
> Amadeo Bellotti wrote:
> > Ok im trying to create a file that the user chooses the name of and
> print a
> > varible that is a string to the text file. but for some reason whne i do
> > this code:
> >
> > FILE = open(filename, "w")
> > FILE.write(puzzleanswers)
> > FILE.close()
> >
> > it doesnt write anything does anyone know how to fix it  so it works?
>
> I would
> print filename
> print puzzleanswers
>
> to make sure you know what should happen.
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060829/e81f6bfa/attachment.html 

From bgailer at alum.rpi.edu  Tue Aug 29 23:47:36 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 29 Aug 2006 14:47:36 -0700
Subject: [Tutor] File IO
In-Reply-To: <d7253a230608291406s7992d77fl20f5e8e234420bb8@mail.gmail.com>
References: <d7253a230608291406s7992d77fl20f5e8e234420bb8@mail.gmail.com>
Message-ID: <44F4B5F8.5030007@alum.rpi.edu>

Amadeo Bellotti wrote:
> Ok im trying to create a file that the user chooses the name of and 
> print a varible that is a string to the text file. but for some reason 
> whne i do this code:
>
> FILE = open(filename, "w")
> FILE.write(puzzleanswers)
> FILE.close()
>
> it doesnt write anything 
That could mean you get an empty file or you don't see the file. Which 
is it?
If the file is empty that means puzzleanswers is  empty.
If you don't see the file that means it is being written someplace other 
than where you are looking.

-- 
Bob Gailer
510-978-4454


From amadeo.bellotti at gmail.com  Wed Aug 30 00:06:16 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Tue, 29 Aug 2006 18:06:16 -0400
Subject: [Tutor] File IO
In-Reply-To: <44F4B5F8.5030007@alum.rpi.edu>
References: <d7253a230608291406s7992d77fl20f5e8e234420bb8@mail.gmail.com>
	<44F4B5F8.5030007@alum.rpi.edu>
Message-ID: <d7253a230608291506x2494833fgb40d7bbb215f106b@mail.gmail.com>

well i made a typo and puzzleanswers was empty i fixed it and it works fine
thank you guys so much

On 8/29/06, Bob Gailer <bgailer at alum.rpi.edu> wrote:
>
> Amadeo Bellotti wrote:
> > Ok im trying to create a file that the user chooses the name of and
> > print a varible that is a string to the text file. but for some reason
> > whne i do this code:
> >
> > FILE = open(filename, "w")
> > FILE.write(puzzleanswers)
> > FILE.close()
> >
> > it doesnt write anything
> That could mean you get an empty file or you don't see the file. Which
> is it?
> If the file is empty that means puzzleanswers is  empty.
> If you don't see the file that means it is being written someplace other
> than where you are looking.
>
> --
> Bob Gailer
> 510-978-4454
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060829/35abe572/attachment.html 

From alan.gauld at freenet.co.uk  Wed Aug 30 01:27:36 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 30 Aug 2006 00:27:36 +0100
Subject: [Tutor] Install problems
References: <179959062F6BD2419FF5E50BBB05711FD033D6@MERCURY.redlandscc.edu>
Message-ID: <003901c6cbc2$b6af3ef0$0201a8c0@XPpro>

Maureen,

> When I tried to install Windows/x86 I got this message:  Internal 
> Error
>2229. ,Control, SELECT 'Control', 'Type', 'X', 'Y', 'Width', 
>'Height',
>'Attributes', 'Property', 'Text', 'Control_Next', 'Help' FROM 
>'Control'
> WHERE 'Dialog_'=?

>Can you tell me how to get Python to install.

 What exactly did you try to install? Where did you download it from?

For a Windows install I strongly recommend the ActiveState version
over the ordinary Python.org version. Opensource purists may object
but the bonus features all built in is worth it IMHO.

But it should be as simple as running the installer after downloading 
it.

Alan G.


From alan.gauld at freenet.co.uk  Wed Aug 30 01:29:55 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 30 Aug 2006 00:29:55 +0100
Subject: [Tutor] File IO
References: <d7253a230608291406s7992d77fl20f5e8e234420bb8@mail.gmail.com><44F4AE67.3070708@tds.net>
	<d7253a230608291434i59bb004fh9b18c2192ccf72d8@mail.gmail.com>
Message-ID: <004f01c6cbc3$098ffb50$0201a8c0@XPpro>


>i do and they have writing but its just not printing it at all
>

How do you know? Where are you looking for the file?
Are you sure its not a Path issue?

Alan G.


> On 8/29/06, Kent Johnson <kent37 at tds.net> wrote:
>>
>> Amadeo Bellotti wrote:
>> > Ok im trying to create a file that the user chooses the name of 
>> > and
>> print a
>> > varible that is a string to the text file. but for some reason 
>> > whne i do
>> > this code:
>> >
>> > FILE = open(filename, "w")
>> > FILE.write(puzzleanswers)
>> > FILE.close()
>> >
>> > it doesnt write anything does anyone know how to fix it  so it 
>> > works?
>>
>> I would
>> print filename
>> print puzzleanswers
>>
>> to make sure you know what should happen.
>>
>> Kent
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> 


From amadeo.bellotti at gmail.com  Wed Aug 30 01:54:53 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Tue, 29 Aug 2006 19:54:53 -0400
Subject: [Tutor] File IO
In-Reply-To: <004f01c6cbc3$098ffb50$0201a8c0@XPpro>
References: <d7253a230608291406s7992d77fl20f5e8e234420bb8@mail.gmail.com>
	<44F4AE67.3070708@tds.net>
	<d7253a230608291434i59bb004fh9b18c2192ccf72d8@mail.gmail.com>
	<004f01c6cbc3$098ffb50$0201a8c0@XPpro>
Message-ID: <d7253a230608291654p70f34f1fi6b465a7981af6de@mail.gmail.com>

no no the file shows up in the same directory as the .py file and i no it
works cause i read the text file

On 8/29/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
>
> >i do and they have writing but its just not printing it at all
> >
>
> How do you know? Where are you looking for the file?
> Are you sure its not a Path issue?
>
> Alan G.
>
>
> > On 8/29/06, Kent Johnson <kent37 at tds.net> wrote:
> >>
> >> Amadeo Bellotti wrote:
> >> > Ok im trying to create a file that the user chooses the name of
> >> > and
> >> print a
> >> > varible that is a string to the text file. but for some reason
> >> > whne i do
> >> > this code:
> >> >
> >> > FILE = open(filename, "w")
> >> > FILE.write(puzzleanswers)
> >> > FILE.close()
> >> >
> >> > it doesnt write anything does anyone know how to fix it  so it
> >> > works?
> >>
> >> I would
> >> print filename
> >> print puzzleanswers
> >>
> >> to make sure you know what should happen.
> >>
> >> Kent
> >>
> >> _______________________________________________
> >> Tutor maillist  -  Tutor at python.org
> >> http://mail.python.org/mailman/listinfo/tutor
> >>
> >
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060829/3d509f55/attachment.html 

From tiagosaboga at terra.com.br  Wed Aug 30 05:12:48 2006
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Wed, 30 Aug 2006 00:12:48 -0300
Subject: [Tutor] re syntax
In-Reply-To: <44F33BFC.3090401@tds.net>
References: <200608281026.00659.tiagosaboga@terra.com.br>
	<200608281529.53446.tiagosaboga@terra.com.br>
	<44F33BFC.3090401@tds.net>
Message-ID: <200608300012.48722.tiagosaboga@terra.com.br>

Em Segunda 28 Agosto 2006 15:54, Kent Johnson escreveu:
> A 'space character' is the single character \x20. A 'whitespace
> character' is any character in a some set of non-printing (white)
> characters. I guess it is a subtle distinction but it's common usage,
> not just Python; it even has a Wikipedia entry:
> http://en.wikipedia.org/wiki/Whitespace_%28computer_science%29
>
> (Not to be confused with Whitespace the programming language, in which
> all *non* white space characters are ignored:
> http://en.wikipedia.org/wiki/Whitespace_programming_language :-))

Ok, you won. ;-)

Thanks.

Tiago.

From redredliuyan at hotmail.com  Wed Aug 30 05:44:45 2006
From: redredliuyan at hotmail.com (=?gb2312?B?wO4gvajHvw==?=)
Date: Wed, 30 Aug 2006 03:44:45 +0000
Subject: [Tutor] About cholesky funtion
Message-ID: <BAY21-F39C8E6F9B05DE3740FD61C93E0@phx.gbl>

Hi,
In my procedure, I use the cholesky(a) function in the scipy.linalg.decomp 
model. If the max number of row and column in matrix a is less equal 15, 
cholesky(a) is OK. But when the max number is larger than 15, there will 
have a error message:
 ¡°File "C:\Python24\Lib\site-packages\scipy\linalg\decomp.py", line 413, 
in cholesky
    if info>0: raise LinAlgError, "matrix not positive definite"
scipy.linalg.basic.LinAlgError: matrix not positive definite¡±.
My matrix is a real symmetric matrix and positive definite, so I don¡¯t 
know why the error emerges. Have there some limits on the number of row and 
column in a matrix?  Please give me your help.

Thanks!

Best wishes,

yan

_________________________________________________________________
Ãâ·ÑÏÂÔØ MSN Explorer:   http://explorer.msn.com/lccn  


From alan.gauld at freenet.co.uk  Wed Aug 30 09:22:34 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed, 30 Aug 2006 08:22:34 +0100
Subject: [Tutor] File IO
References: <d7253a230608291406s7992d77fl20f5e8e234420bb8@mail.gmail.com>
	<44F4AE67.3070708@tds.net>
	<d7253a230608291434i59bb004fh9b18c2192ccf72d8@mail.gmail.com>
	<004f01c6cbc3$098ffb50$0201a8c0@XPpro>
	<d7253a230608291654p70f34f1fi6b465a7981af6de@mail.gmail.com>
Message-ID: <005f01c6cc05$10ad1840$0201a8c0@XPpro>

>> How do you know? Where are you looking for the file?
>> Are you sure its not a Path issue?

> no no the file shows up in the same directory as the .py file and i 
> no it
> works cause i read the text file

OK, In that case can you show us what puzzleanswers looks like?

>> > On 8/29/06, Kent Johnson <kent37 at tds.net> wrote:
>> >> I would
>> >> print filename
>> >> print puzzleanswers
>> >>
>> >> to make sure you know what should happen.

Also, if the code is not too long can you post it too?

Alan G. 


From devayani.barve at gmail.com  Wed Aug 30 11:03:13 2006
From: devayani.barve at gmail.com (devayani barve)
Date: Wed, 30 Aug 2006 14:33:13 +0530
Subject: [Tutor] DOM using python
Message-ID: <301929340608300203l6752862dlaea8aa417d72816b@mail.gmail.com>

Hi all,
I'm using python 2.3;
I want to learn dom implementation in python right from the very basics
do i need to install pyxml or anything else?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060830/a65a723c/attachment.html 

From kent37 at tds.net  Wed Aug 30 12:35:07 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 30 Aug 2006 06:35:07 -0400
Subject: [Tutor] About cholesky funtion
In-Reply-To: <BAY21-F39C8E6F9B05DE3740FD61C93E0@phx.gbl>
References: <BAY21-F39C8E6F9B05DE3740FD61C93E0@phx.gbl>
Message-ID: <44F569DB.7010601@tds.net>

Àî ½¨Ç¿ wrote:
> Hi,
> In my procedure, I use the cholesky(a) function in the scipy.linalg.decomp 
> model. 

I may be wrong, but I don't think we have any SciPy experts on this
list. You'll probably do better on the SciPy users mailing list:
http://www.scipy.org/Mailing_Lists

Kent


From kent37 at tds.net  Wed Aug 30 12:41:02 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 30 Aug 2006 06:41:02 -0400
Subject: [Tutor] DOM using python
In-Reply-To: <301929340608300203l6752862dlaea8aa417d72816b@mail.gmail.com>
References: <301929340608300203l6752862dlaea8aa417d72816b@mail.gmail.com>
Message-ID: <44F56B3E.902@tds.net>

devayani barve wrote:
> Hi all,
> I'm using python 2.3;
> I want to learn dom implementation in python right from the very basics
> do i need to install pyxml or anything else?

The standard Python install includes a simple DOM implementation in the 
xml.dom packages. PyXML adds more capabilities.

If you are just starting and don't specifically require DOM, you might 
want to consider something else. Many people (including me) prefer to 
use a more Pythonic XML processing package. ElementTree is very popular 
and is included in the standard library as of Python 2.5 but there are 
many others as well.
http://effbot.org/zone/element.htm
http://docs.python.org/dev/whatsnew/modules.html#SECTION0001420000000000000000

Kent


From govilakanksha at yahoo.com  Wed Aug 30 14:25:59 2006
From: govilakanksha at yahoo.com (Akanksha Govil)
Date: Wed, 30 Aug 2006 05:25:59 -0700 (PDT)
Subject: [Tutor] SAX and Python
Message-ID: <20060830122559.17282.qmail@web36509.mail.mud.yahoo.com>

Hi,

I have written a small code in python for reading xml using SAX.

I am importing xml.sax using the following:

from xml.sax import saxlib, saxexts
On executing the code I get the following error:

ImportError: cannot import name saxlib

Both python-xml and pyxml are installed on my machine along with python 2.4.

What am I missing here?

Thanks
Akanksha

 		
---------------------------------
 All-new Yahoo! Mail - Fire up a more powerful email and get things done faster.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060830/e89d6ca1/attachment.html 

From dkuhlman at rexx.com  Wed Aug 30 18:30:13 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Wed, 30 Aug 2006 09:30:13 -0700
Subject: [Tutor] SAX and Python
In-Reply-To: <20060830122559.17282.qmail@web36509.mail.mud.yahoo.com>
References: <20060830122559.17282.qmail@web36509.mail.mud.yahoo.com>
Message-ID: <20060830163013.GA71497@cutter.rexx.com>

On Wed, Aug 30, 2006 at 05:25:59AM -0700, Akanksha Govil wrote:
> Hi,
> 
> I have written a small code in python for reading xml using SAX.
> 
> I am importing xml.sax using the following:
> 
> from xml.sax import saxlib, saxexts
> On executing the code I get the following error:
> 
> ImportError: cannot import name saxlib
> 
> Both python-xml and pyxml are installed on my machine along with
> python 2.4.
> 

I believe that there have been a few changes to the organization of
the SAX modules and the interfaces of the classes themselves.

Attached is a simple SAX example that should help get you started,
if you haven't already groped your way through it.

Also, you will want to read the following and the pages it links
to:

    http://docs.python.org/lib/module-xml.sax.html
    http://docs.python.org/lib/module-xml.sax.xmlreader.html
    http://docs.python.org/lib/module-xml.sax.handler.html
    Etc.

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test_sax2.py
Type: text/x-python
Size: 1709 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060830/c28d08b6/attachment.py 

From carroll at tjc.com  Wed Aug 30 22:36:19 2006
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 30 Aug 2006 13:36:19 -0700 (PDT)
Subject: [Tutor] omnicomplete vim python
In-Reply-To: <001301c6cb3c$554b91d0$0201a8c0@XPpro>
Message-ID: <Pine.LNX.4.44.0608301329310.23723-100000@violet.rahul.net>

On Tue, 29 Aug 2006, Alan Gauld wrote:

> But does anyone actually use this feature? 

I have, in Visual Basic.  Its advantage to me wasn't so much that it saved 
me from typing, but saved me from typing the the incorrect thing, ii.e., 
if I's been using a variable name "fluid_boiling_pt" I won't, later in the 
program, type "fluid_boiling_point."

I realize that, if I was coding in nice small modules, like I should, I
wouldn't have this problem, because the whole code unit would fit on the
screen; but this was for a particular course where the fact that I knew
enough about programming to have opinions like this was best kept hidden!



From amadeo.bellotti at gmail.com  Wed Aug 30 22:42:02 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Wed, 30 Aug 2006 16:42:02 -0400
Subject: [Tutor] File IO
In-Reply-To: <005f01c6cc05$10ad1840$0201a8c0@XPpro>
References: <d7253a230608291406s7992d77fl20f5e8e234420bb8@mail.gmail.com>
	<44F4AE67.3070708@tds.net>
	<d7253a230608291434i59bb004fh9b18c2192ccf72d8@mail.gmail.com>
	<004f01c6cbc3$098ffb50$0201a8c0@XPpro>
	<d7253a230608291654p70f34f1fi6b465a7981af6de@mail.gmail.com>
	<005f01c6cc05$10ad1840$0201a8c0@XPpro>
Message-ID: <d7253a230608301342x23d51133y28d57088f42e303e@mail.gmail.com>

the code is way to long but i can post the output of puzzleanswers

Answer:
6 1 4 2 9 3 8 5 7
8 5 9 1 6 7 2 3 4
2 3 7 8 5 4 9 1 6
7 8 6 9 1 2 5 4 3
4 2 1 3 7 5 6 9 8
3 9 5 4 8 6 1 7 2
9 4 3 5 2 8 7 6 1
5 6 8 7 4 1 3 2 9
1 7 2 6 3 9 4 8 5

for those of you who dont know its a sudoku puzzle if you guys want i can
attach the .py file.

On 8/30/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
>
> >> How do you know? Where are you looking for the file?
> >> Are you sure its not a Path issue?
>
> > no no the file shows up in the same directory as the .py file and i
> > no it
> > works cause i read the text file
>
> OK, In that case can you show us what puzzleanswers looks like?
>
> >> > On 8/29/06, Kent Johnson <kent37 at tds.net> wrote:
> >> >> I would
> >> >> print filename
> >> >> print puzzleanswers
> >> >>
> >> >> to make sure you know what should happen.
>
> Also, if the code is not too long can you post it too?
>
> Alan G.
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060830/2f6c869c/attachment.html 

From amadeo.bellotti at gmail.com  Thu Aug 31 01:37:47 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Wed, 30 Aug 2006 19:37:47 -0400
Subject: [Tutor] Can you tell me whats wrong with this code?
Message-ID: <d7253a230608301637p431a92f0o64b6945fc97c0a73@mail.gmail.com>

first of all i have random.randint imported as rand like this:

from random import randint as rand

it is giving me an error at the line

    space = rand(1,82)

the error its giving me is

    Traceback (most recent call last):
      File "sudoku.py", line 1050, in ?
        space = rand(1,82)
    TypeError: 'int' object is not callable

what is wrong with the line i have no clue i spent an hour looking it up
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060830/997c834d/attachment.html 

From john at fouhy.net  Thu Aug 31 01:43:56 2006
From: john at fouhy.net (John Fouhy)
Date: Thu, 31 Aug 2006 11:43:56 +1200
Subject: [Tutor] Can you tell me whats wrong with this code?
In-Reply-To: <d7253a230608301637p431a92f0o64b6945fc97c0a73@mail.gmail.com>
References: <d7253a230608301637p431a92f0o64b6945fc97c0a73@mail.gmail.com>
Message-ID: <5e58f2e40608301643n5f1abfbes2d55e9a6ba625e2b@mail.gmail.com>

On 31/08/06, Amadeo Bellotti <amadeo.bellotti at gmail.com> wrote:
> first of all i have random.randint imported as rand like this:
>
> from random import randint as rand
>
> it is giving me an error at the line
>
>     space = rand(1,82)
>
> the error its giving me is
>
>     Traceback (most recent call last):
>       File "sudoku.py", line 1050, in ?
>         space = rand(1,82)
>     TypeError: 'int' object is not callable

It's telling you that "rand" is an int.  Since it didn't start off
like that, I suspect you have assigned to rand somewhere.

Have a look through your code; are there any lines starting with:

    rand =

?

Also, in my opinion, it's a bad idea to rename standard library
functions like that.  If another python programmer looked at your
code, they would probably be familiar with randint and understand what
it does, but they won't know exactly what "rand" does without looking
through the rest of your code.

-- 
John.

From amadeo.bellotti at gmail.com  Thu Aug 31 01:57:13 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Wed, 30 Aug 2006 19:57:13 -0400
Subject: [Tutor] Can you tell me whats wrong with this code?
In-Reply-To: <5e58f2e40608301643n5f1abfbes2d55e9a6ba625e2b@mail.gmail.com>
References: <d7253a230608301637p431a92f0o64b6945fc97c0a73@mail.gmail.com>
	<5e58f2e40608301643n5f1abfbes2d55e9a6ba625e2b@mail.gmail.com>
Message-ID: <d7253a230608301657r32135495s45f343143c964332@mail.gmail.com>

Thank you sooo much thats exactly what went wrong thank you so much

On 8/30/06, John Fouhy <john at fouhy.net> wrote:
>
> On 31/08/06, Amadeo Bellotti <amadeo.bellotti at gmail.com> wrote:
> > first of all i have random.randint imported as rand like this:
> >
> > from random import randint as rand
> >
> > it is giving me an error at the line
> >
> >     space = rand(1,82)
> >
> > the error its giving me is
> >
> >     Traceback (most recent call last):
> >       File "sudoku.py", line 1050, in ?
> >         space = rand(1,82)
> >     TypeError: 'int' object is not callable
>
> It's telling you that "rand" is an int.  Since it didn't start off
> like that, I suspect you have assigned to rand somewhere.
>
> Have a look through your code; are there any lines starting with:
>
>     rand =
>
> ?
>
> Also, in my opinion, it's a bad idea to rename standard library
> functions like that.  If another python programmer looked at your
> code, they would probably be familiar with randint and understand what
> it does, but they won't know exactly what "rand" does without looking
> through the rest of your code.
>
> --
> John.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060830/9e15d379/attachment-0001.htm 

From python at kapitalisten.no  Thu Aug 31 16:11:37 2006
From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=)
Date: Thu, 31 Aug 2006 16:11:37 +0200 (CEST)
Subject: [Tutor] IP-range
Message-ID: <4054.193.71.158.152.1157033497.squirrel@mail.sporck.net>

Hello.

I have a database where I have some IP-ranges. Then I have some logs over
IPs from customers and need to connect the two.

So, for example:

Range 1:
123.132.122.4-123.132.122.255

How do I check if IP 123.132.122.58 is a part of that? I have thought
about 4 if statements:

split(.)
if ip[0] in iprange_from[0] and iprange_to[0]:
  if ip[1] in iprange_from[1] and iprange_to[1]:
    if ip[2] in iprange_from[2] and iprange_to[2]:
      if ip[3] in iprange_from[3] and iprange_to[3]:
        then ok

But that seems silly. Is there some better way?

Thanks in advance


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


From dyoo at hkn.eecs.berkeley.edu  Thu Aug 31 16:32:56 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 31 Aug 2006 07:32:56 -0700 (PDT)
Subject: [Tutor] IP-range
In-Reply-To: <4054.193.71.158.152.1157033497.squirrel@mail.sporck.net>
References: <4054.193.71.158.152.1157033497.squirrel@mail.sporck.net>
Message-ID: <Pine.LNX.4.64.0608310729530.9739@hkn.eecs.berkeley.edu>



On Thu, 31 Aug 2006, Øyvind wrote:

> I have a database where I have some IP-ranges. Then I have some logs 
> over IPs from customers and need to connect the two.
>
> So, for example:
>
> Range 1:
> 123.132.122.4-123.132.122.255

Hello,

You might want to consider using tuple comparison.  For example:

###
>>> (1, 2) <= (1, 3) <= (1, 4)
True
###

Hope this helps!

From kent37 at tds.net  Thu Aug 31 16:42:53 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 31 Aug 2006 10:42:53 -0400
Subject: [Tutor] IP-range
In-Reply-To: <4054.193.71.158.152.1157033497.squirrel@mail.sporck.net>
References: <4054.193.71.158.152.1157033497.squirrel@mail.sporck.net>
Message-ID: <44F6F56D.30609@tds.net>

?yvind wrote:
> Hello.
>
> I have a database where I have some IP-ranges. Then I have some logs over
> IPs from customers and need to connect the two.
>
> So, for example:
>
> Range 1:
> 123.132.122.4-123.132.122.255
>
> How do I check if IP 123.132.122.58 is a part of that? I have thought
> about 4 if statements:
>
> split(.)
> if ip[0] in iprange_from[0] and iprange_to[0]:
>   if ip[1] in iprange_from[1] and iprange_to[1]:
>     if ip[2] in iprange_from[2] and iprange_to[2]:
>       if ip[3] in iprange_from[3] and iprange_to[3]:
>         then ok
>
> But that seems silly. Is there some better way?

If the IPs are stored as lists or tuples of integers you can compare 
them directly and Python will do the right thing. If they are strings, a 
simple helper function can convert them to lists:
In [1]: def ipStrToList(ip):
   ...:     return map(int, ip.split('.'))
   ...:

In [2]: ipStrToList('123.132.122.4')
Out[2]: [123, 132, 122, 4]

In [3]: lower = _

In [4]: upper = ipStrToList('123.132.122.255')

In [5]: lower <= ipStrToList('123.132.122.58') <= upper
Out[5]: True

In [6]: lower <= ipStrToList('123.132.123.58') <= upper
Out[6]: False

Kent


From kent37 at tds.net  Thu Aug 31 16:48:37 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 31 Aug 2006 10:48:37 -0400
Subject: [Tutor] IP-range
In-Reply-To: <4054.193.71.158.152.1157033497.squirrel@mail.sporck.net>
References: <4054.193.71.158.152.1157033497.squirrel@mail.sporck.net>
Message-ID: <44F6F6C5.5020700@tds.net>

?yvind wrote:
> Hello.
>
> I have a database where I have some IP-ranges. Then I have some logs over
> IPs from customers and need to connect the two.

Also you might be interested in
http://c0re.23.nu/c0de/IPy/

Kent


From kent37 at tds.net  Thu Aug 31 16:57:03 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 31 Aug 2006 10:57:03 -0400
Subject: [Tutor] Unicode problems
In-Reply-To: <34bb7f5b0608310342kf2766fex2a4bcaf6b0ee6796@mail.gmail.com>
References: <34bb7f5b0608291339s619c279di8c5c9cd7c6bf6e1a@mail.gmail.com>	
	<44F4AD0E.8050104@tds.net>
	<34bb7f5b0608310342kf2766fex2a4bcaf6b0ee6796@mail.gmail.com>
Message-ID: <44F6F8BF.8080906@tds.net>

Ed Singleton wrote:
> On 8/29/06, Kent Johnson <kent37 at tds.net> wrote:
>>> The main problem  I am having is in getting python not to give an
>>> error when it encounters a sterling currency sign (?, pound sign here
>>> in UK), which I suspect might be some wider problem on the mac as when
>>> I type that character in the terminal it shows a # (but in Python it
>>> shows a ?).
>>>       
>> Where is the pound sign coming from? What encoding is it in? What do you
>> mean, in Python it shows ?? You said Python gives an error...Fixing your
>> first problem may not help this one without a bit more digging... (BTW
>> in the US a # is sometimes called a 'pound sign', maybe the computer is
>> trying to translate for you ;) - though it is for pound weight, not
>> pound sterling.)
>>     
>
> The pound sign is in the source code in a string, or in a text file I
> was reading in.  Both should be in utf-8 as I save all files to that
> by default.  I think it was (hopefully) just that python was choking
> on printing the character (I was printing everything for debugging
> purposes).
>   
You also need to tell Python that the file is in UTF-8 by putting an 
encoding declaration at the top of the file.

# -*- coding: utf-8 -*-

You probably want to make the strings Unicode strings as well, e.g. u'xxx'.
> If I type "?" into a text document and copy and paste it to the python
> console, it comes out as " ?" (with a space).  If I copy and paste it
> back, the space is gone.
>   
Sounds like maybe you are pasting Unicode (two bytes) and the console 
interprets it as two characters.
> If I type "test ?" (without quotes) into a text document and copy and
> paste it to the console it comes out as "#test" and goes to a new
> line, as if I had pressed enter.
>   
That on is very strange.

By the way you can explicitly control the conversion on output by using e.g.

print someString.encode('utf-8')

Finally, please keep the discussion on list.

Kent
> I'll keep digging and trying things out.
>
> Thanks
>
> Ed
>   



From janos.juhasz at VELUX.com  Thu Aug 31 17:00:26 2006
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Thu, 31 Aug 2006 17:00:26 +0200
Subject: [Tutor] Python decorator
In-Reply-To: <mailman.36339.1156873734.27774.tutor@python.org>
Message-ID: <OFC950191D.463091CC-ONC12571DB.0050F955-C12571DB.00527046@velux.com>

Hi,

I have just started to play with TurboGears - it is really nice - and I 
couldn't understand the decorators used by it.
I have tried to interpret the http://wiki.python.org/moin/PythonDecorators 
about decorators, but it is too difficult for me.

May someone explain decorators in very sortly, what is it for and why ?
Do I need it anyway ?

Yours sincerely, 
______________________________
Janos Juhasz 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060831/f01c41fa/attachment.html 

From kent37 at tds.net  Thu Aug 31 17:46:22 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 31 Aug 2006 11:46:22 -0400
Subject: [Tutor] Python decorator
In-Reply-To: <OFC950191D.463091CC-ONC12571DB.0050F955-C12571DB.00527046@velux.com>
References: <OFC950191D.463091CC-ONC12571DB.0050F955-C12571DB.00527046@velux.com>
Message-ID: <44F7044E.5020603@tds.net>

J?nos Juh?sz wrote:
> Hi,
>
> I have just started to play with TurboGears - it is really nice - and I 
> couldn't understand the decorators used by it.
> I have tried to interpret the http://wiki.python.org/moin/PythonDecorators 
> about decorators, but it is too difficult for me.

That's not the best starting point, it is more of historical interest. 
There was a huge debate about the syntax to use for decorators, it is 
summarized on that page.

See if this makes more sense:
http://docs.python.org/whatsnew/node6.html

You might also be interested in the examples in PEP 318 and this wiki page:
http://wiki.python.org/moin/PythonDecoratorLibrary?highlight=%28decorator%29

Kent


From amadeo.bellotti at gmail.com  Thu Aug 31 22:12:41 2006
From: amadeo.bellotti at gmail.com (Amadeo Bellotti)
Date: Thu, 31 Aug 2006 16:12:41 -0400
Subject: [Tutor] GUI Programing
Message-ID: <d7253a230608311312j698b46a5k63f5a3e6f555e5a0@mail.gmail.com>

I'm going to try some GUI programming does anyone know where the start like
using tk or wx or what ever i want it to it will run on Windows UNIX and Mac
systems can you tell me whats best to use and give me a link to a good
tutorial?

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060831/1e1fc626/attachment.htm 

From H.FANGOHR at soton.ac.uk  Thu Aug 31 22:14:34 2006
From: H.FANGOHR at soton.ac.uk (Hans Fangohr)
Date: Thu, 31 Aug 2006 21:14:34 +0100 (BST)
Subject: [Tutor] logging module, how to print line numbers?
Message-ID: <Pine.OSX.4.58.0608312111160.23167@jarjar.sesnet.soton.ac.uk>

Hi,

I have some trouble with the logging module.

When I run this program with python2.3:

#------------
import logging,sys
formatter = logging.Formatter('%(name)s :%(asctime)s %(filename)s
%(lineno)s %(levelname)s  %(message)s')
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
logger=logging.getLogger('')
logger.addHandler(stdout_handler)
logger.setLevel(logging.DEBUG)
logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bows')
#------------

I get the following output:

root :2006-08-31 20:20:15,085 __init__.py 988 DEBUG  A debug message
root :2006-08-31 20:20:15,085 __init__.py 988 INFO  Some information
root :2006-08-31 20:20:15,085 __init__.py 988 WARNING  A shot across thebows

Note that the line number always appears as 988. I'd like it to be the
line number where the logging command has been executed. The documentation
says that %(lineno)d should work 'if available'.

Is this generally not available? Can I make it available? If so, how?

Any advice welcome.

Many thanks in advance,

Hans






From rabidpoobear at gmail.com  Thu Aug 31 23:17:31 2006
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 31 Aug 2006 16:17:31 -0500
Subject: [Tutor] Securing a Computer...
In-Reply-To: <8C8990E64EFDD20-288-44F9@MBLK-M30.sysops.aol.com>
References: <8C8990E64EFDD20-288-44F9@MBLK-M30.sysops.aol.com>
Message-ID: <dfeb4470608311417p1df0a1dcv9320b526eb579413@mail.gmail.com>

On 8/28/06, mjrmonkeyman at aol.com <mjrmonkeyman at aol.com> wrote:
>
> I just got into high school, and the network and all the computers aren't
> secure at all...I'm trying to make a program that password protects the
> computer after an inactivity time, but there are some specific things I
> can't find how I'm supposed to do it.
>

Windoze has this feature built in.  It's called 'locking' the computer.
Look into it.

1. Freeze/unfreeze Windows processes OR start/end Windows processes
> (Preferrably the first)
>

the user may need oto be on an administrative account for you to be able to
end processes.
At a school that's unlikely.

2. Turn off/restart the computer
>

Again this is implemented by the 'lock' feature in Windows.

3. I can probably find this somewhere else, but I surprisingly haven't: Make
> a timer that resets when the mouse     moves or a key is pressed (That still
> resets when the window is minimized, inactive, etc.)
>

You could make a Pygame program that does a grab_all, or tkinter for that
matter.
this probably won't work though.
I won't go into detail.
-Luke

------------------------------
> *Check out AOL.com today*<http://pr.atwola.com/promoclk/1615326657x4311227241x4298082137/aol?redir=http%3A%2F%2Fwww%2Eaol%2Ecom>.
> Breaking news, video search, pictures, email and IM. All on demand. Always
> Free.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060831/887f3c3b/attachment.html 

From fiveholiday55 at hotmail.com  Thu Aug 31 23:23:01 2006
From: fiveholiday55 at hotmail.com (Henry Dominik)
Date: Thu, 31 Aug 2006 22:23:01 +0100
Subject: [Tutor] GUI Programing
References: <d7253a230608311312j698b46a5k63f5a3e6f555e5a0@mail.gmail.com>
Message-ID: <BAY111-DAV95D9F3B4AC03503602DC4AD3F0@phx.gbl>

This guy has been documenting his progress as he learns Python GUI programming. See if you can pick up a few tips http://www.learningpython.com/

  ----- Original Message ----- 
  From: Amadeo Bellotti 
  To: Tutor 
  Sent: Thursday, August 31, 2006 9:12 PM
  Subject: [Tutor] GUI Programing


  I'm going to try some GUI programming does anyone know where the start like using tk or wx or what ever i want it to it will run on Windows UNIX and Mac systems can you tell me whats best to use and give me a link to a good tutorial?

  Thanks



------------------------------------------------------------------------------


  _______________________________________________
  Tutor maillist  -  Tutor at python.org
  http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060831/61af4b7b/attachment.htm